diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0ac60b83..5db7dd4c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,6 +11,9 @@ jobs: timeout-minutes: 20 steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 + persist-credentials: false - uses: astral-sh/setup-uv@v6 with: version: "0.8.22" @@ -20,6 +23,8 @@ jobs: - run: make db-up - name: Run complete checks including the M0 security gate id: complete-checks + env: + OPENAPI_BASELINE_REF: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }} run: make check - name: Retain M0 security gate evidence if: always() diff --git a/Makefile b/Makefile index bf949816..ae39e10f 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: install build lint typecheck test catalog security-gate smoke db-up db-down db-reset integration check +.PHONY: install build lint typecheck test catalog security-gate smoke db-up db-down db-reset integration openapi-generate openapi-check openapi-breaking-check check install: uv sync --frozen @@ -37,4 +37,13 @@ db-reset: integration: ./scripts/database_harness.sh integration -check: build lint typecheck test catalog smoke integration security-gate +openapi-generate: + uv run python scripts/freeze_openapi.py generate + +openapi-check: + uv run python scripts/freeze_openapi.py check $(if $(OPENAPI_BASELINE_REF),--baseline-ref $(OPENAPI_BASELINE_REF),) + +openapi-breaking-check: + uv run pytest -q tests/unit/test_openapi_v0_snapshot.py + +check: build lint typecheck openapi-check test catalog smoke integration security-gate diff --git a/adapters/http/app.py b/adapters/http/app.py index 45513fd5..971765d8 100644 --- a/adapters/http/app.py +++ b/adapters/http/app.py @@ -25,6 +25,7 @@ ) from adapters.http.contracts import ( AcquireWire, + ApplicationForbiddenWire, AuthenticationFailureWire, ChannelEgressGrantWire, CitationNotAvailableWire, @@ -33,11 +34,13 @@ InvalidRequestWire, ModelEgressGrantWire, OpenCitationWire, + RateLimitedWire, RequestNotAvailableWire, ResolutionOutcomeWire, ResolvedWire, ResolveWire, ServiceUnavailableWire, + resolution_outcome_public_document, ) from adapters.http.membership_authority import ( MembershipAuthority, @@ -48,6 +51,11 @@ OrganizationVerificationRejected, RejectingOrganizationAuthority, ) +from adapters.http.route_policy import ( + AllowAuthenticatedResolveRoutePolicy, + ResolveRouteDecision, + ResolveRoutePolicy, +) from adapters.http.scope_authority import ( MissingTrustedScopeAuthority, ScopeAuthority, @@ -110,6 +118,7 @@ ) from engine.runtime.package_digest import QueryDigestKeyring from engine.runtime.policy_epoch import PolicyEpochAuthorityUnavailable +from engine.runtime.release_lineage import ActiveReleaseUnavailable from engine.runtime.scope_authority import InvalidTrustedScopeSnapshot HEALTH_RESPONSE: Final = { @@ -121,7 +130,12 @@ AUTHENTICATION_FAILED_RESPONSE: Final = {"code": "authentication_failed"} INVALID_REQUEST_RESPONSE: Final = {"code": "invalid_request"} SERVICE_UNAVAILABLE_RESPONSE: Final = {"code": "service_unavailable"} -RESOLVE_PATH: Final = "/v1/context:resolve" +APPLICATION_FORBIDDEN_RESPONSE: Final = {"code": "application_forbidden"} +RATE_LIMITED_RESPONSE: Final = {"code": "rate_limited"} +PUBLIC_API_VERSION: Final = "0.0.0" +PUBLIC_RESOLVE_PATH: Final = "/v0/resolve" +LEGACY_RESOLVE_PATH: Final = "/v1/context:resolve" +RESOLVE_PATHS: Final = frozenset({PUBLIC_RESOLVE_PATH, LEGACY_RESOLVE_PATH}) class TransportAuthenticationFailed(Exception): @@ -132,6 +146,14 @@ class TrustedAuthorityUnavailable(Exception): """A required trusted authority failed without exposing identity detail.""" +class ResolveApplicationForbidden(Exception): + """The authenticated application is not allowed to use this route.""" + + +class ResolveRateLimited(Exception): + """The authenticated application exceeded a route-only resource policy.""" + + class InvalidRequestMediaType(Exception): """Resolve received a body outside its sole JSON media type.""" @@ -181,6 +203,7 @@ def create_app( organization_authority: OrganizationAuthority | None = None, membership_authority: MembershipAuthority | None = None, scope_authority: ScopeAuthority | None = None, + route_policy: ResolveRoutePolicy | None = None, runtime: Runtime | None = None, query_digest_keyring: QueryDigestKeyring | None = None, invocation_observer: Callable[[AuthenticatedInvocation], None] | None = None, @@ -213,16 +236,17 @@ def create_app( membership_authority or RejectingMembershipAuthority() ) selected_scope_authority = scope_authority or MissingTrustedScopeAuthority() + selected_route_policy = route_policy or AllowAuthenticatedResolveRoutePolicy() bearer = HTTPBearer( scheme_name="ContextEngineBearer", bearerFormat="opaque", auto_error=False, ) - app = FastAPI(title="ContextEngine", version=BUILD_IDENTIFIER) + app = FastAPI(title="ContextEngine", version=PUBLIC_API_VERSION) app.add_middleware( ResolveBodyLimitMiddleware, profile=transport_profile, - resolve_path=RESOLVE_PATH, + resolve_paths=RESOLVE_PATHS, invalid_response=INVALID_REQUEST_RESPONSE, ) @@ -245,6 +269,22 @@ async def trusted_authority_unavailable( del request, error return JSONResponse(SERVICE_UNAVAILABLE_RESPONSE, status_code=503) + @app.exception_handler(ResolveApplicationForbidden) + async def application_forbidden( + request: Request, + error: ResolveApplicationForbidden, + ) -> JSONResponse: + del request, error + return JSONResponse(APPLICATION_FORBIDDEN_RESPONSE, status_code=403) + + @app.exception_handler(ResolveRateLimited) + async def rate_limited( + request: Request, + error: ResolveRateLimited, + ) -> JSONResponse: + del request, error + return JSONResponse(RATE_LIMITED_RESPONSE, status_code=429) + @app.exception_handler(InvalidRequestMediaType) @app.exception_handler(InvalidJsonTransport) async def invalid_media_type( @@ -326,16 +366,47 @@ def verified_authentication( raise TransportAuthenticationFailed return context + def require_public_request_id( + authentication: Annotated[ + VerifiedAuthenticationContext, + Depends(verified_authentication), + ], + context_request_id: Annotated[ + str, + Header( + alias="X-Context-Request-Id", + min_length=1, + max_length=transport_profile.max_correlation_id_characters, + pattern=r".*\S.*", + ), + ], + ) -> None: + """Require request-bound metadata on the frozen public carrier.""" + + del authentication, context_request_id + @app.get("/health", include_in_schema=False) def health() -> dict[str, str]: return HEALTH_RESPONSE.copy() @app.post( - RESOLVE_PATH, + LEGACY_RESOLVE_PATH, + include_in_schema=False, status_code=200, response_model=ResolutionOutcomeWire, response_model_by_alias=True, dependencies=[Depends(require_closed_json_transport)], + ) + @app.post( + PUBLIC_RESOLVE_PATH, + operation_id="resolveContextV0", + status_code=200, + response_model=ResolutionOutcomeWire, + response_model_by_alias=True, + dependencies=[ + Depends(require_closed_json_transport), + Depends(require_public_request_id), + ], responses={ 400: { "model": InvalidRequestWire, @@ -354,10 +425,18 @@ def health() -> dict[str, str]: } }, }, + 403: { + "model": ApplicationForbiddenWire, + "description": "The authenticated application is not allowed.", + }, 422: { "model": InvalidRequestWire, "description": "The closed request schema rejected the body.", }, + 429: { + "model": RateLimitedWire, + "description": "The application exceeded the route resource policy.", + }, 503: { "model": ServiceUnavailableWire, "description": "A required trusted authority is unavailable.", @@ -385,7 +464,7 @@ def resolve_context( alias="X-Context-Delivery-Evidence-Ref", min_length=1, max_length=transport_profile.max_delivery_evidence_ref_characters, - pattern=r".*\S.*", + pattern=r"^\S+$", ), ] = None, ) -> JSONResponse: @@ -394,6 +473,16 @@ def resolve_context( runtime_request = _runtime_request_from_wire(body) request_id = context_request_id or request_id_factory() received_at = clock() + try: + route_decision = selected_route_policy.decide(authentication) + except Exception: + raise TrustedAuthorityUnavailable from None + if route_decision is ResolveRouteDecision.FORBID: + raise ResolveApplicationForbidden + if route_decision is ResolveRouteDecision.RATE_LIMIT: + raise ResolveRateLimited + if route_decision is not ResolveRouteDecision.ALLOW: + raise TrustedAuthorityUnavailable private_binding = authentication.private_delivery_binding if delivery_evidence_ref is None: if private_binding is not None: @@ -508,8 +597,7 @@ def resolve_context( raise TransportAuthenticationFailed redemption_session = ( current_membership_verification - .delivery_evidence_redemption_session - ) + ).delivery_evidence_redemption_session if redemption_session is None: raise TrustedAuthorityUnavailable try: @@ -590,11 +678,7 @@ def resolve_context( if type(outcome) is Resolved and resolution_observer is not None: resolution_observer(outcome) return JSONResponse( - response.model_dump( - mode="json", - by_alias=True, - exclude_none=True, - ), + resolution_outcome_public_document(response), status_code=200, headers={ "Cache-Control": "no-store", @@ -617,6 +701,8 @@ def resolve_context( raise TrustedAuthorityUnavailable from None except ScopeAuthorityUnavailable: raise TrustedAuthorityUnavailable from None + except ActiveReleaseUnavailable: + raise TrustedAuthorityUnavailable from None except InvalidTrustedScopeSnapshot: raise TrustedAuthorityUnavailable from None diff --git a/adapters/http/contracts.py b/adapters/http/contracts.py index b8f811d3..82f305c4 100644 --- a/adapters/http/contracts.py +++ b/adapters/http/contracts.py @@ -10,7 +10,8 @@ MAX_NARROWING_REF_LENGTH, MAX_NARROWING_REFS, MAX_OPAQUE_CAPABILITY_LENGTH, - ORGANIZATION_PACKAGE_REF_PATTERN, + PACKAGE_REF_PATTERN, + complete_context_package_nullable_fields, ) from engine.runtime.evidence import ( MAX_PROJECTED_FIELD_REF_LENGTH, @@ -38,9 +39,9 @@ str, Field(strict=True, min_length=1, pattern=r".*\S.*"), ] -OrganizationPackageOutputRef = Annotated[ +PackageOutputRef = Annotated[ str, - Field(strict=True, pattern=ORGANIZATION_PACKAGE_REF_PATTERN), + Field(strict=True, pattern=PACKAGE_REF_PATTERN), ] DecisionOutputRef = Annotated[ str, @@ -186,9 +187,9 @@ class BudgetUsageWire(ClosedWireModel): """Actual resources consumed by this Package.""" tokens: NonnegativeExactInteger - providerCalls: Literal[0] - costMicrounits: Literal[0] - elapsedMs: Literal[0] + providerCalls: NonnegativeExactInteger + costMicrounits: NonnegativeExactInteger + elapsedMs: NonnegativeExactInteger class BlockWire(ClosedWireModel): @@ -210,6 +211,40 @@ def bind_id_to_its_evidence(self) -> Self: return self +class LiveSourceAclEvidenceWire(ClosedWireModel): + kind: Literal["live"] + sourceDecisionRef: OpaqueOutputRef + checkedAt: datetime + verificationProtocolRef: OpaqueOutputRef + + +class MirroredSourceAclEvidenceWire(ClosedWireModel): + kind: Literal["mirrored"] + projectionRef: OpaqueOutputRef + aclAsOf: datetime + freshnessProfileRef: OpaqueOutputRef + + +class WeakSourceAclEvidenceWire(ClosedWireModel): + kind: Literal["weak"] + declarationRef: OpaqueOutputRef + checkedAt: datetime + boundedMembershipEvidenceRef: OpaqueOutputRef + snapshotAsOf: datetime + expiresAt: datetime + membershipCompleteness: Literal["complete"] + sensitivityPolicyRef: OpaqueOutputRef + historySemanticsRef: OpaqueOutputRef + + +type SourceAclEvidenceWire = Annotated[ + LiveSourceAclEvidenceWire + | MirroredSourceAclEvidenceWire + | WeakSourceAclEvidenceWire, + Field(discriminator="kind"), +] + + class EvidenceWire(ClosedWireModel): """Public request-scoped Evidence and its authorization lineage.""" @@ -228,7 +263,8 @@ class EvidenceWire(ClosedWireModel): decisionRef: DecisionOutputRef policySnapshotRef: OpaqueOutputRef policyEpoch: PositivePolicyEpoch - sourceDecisionRef: OpaqueOutputRef + sourceAclEvidence: SourceAclEvidenceWire + citationOpenRef: OpaqueOutputRef | None @model_validator(mode="after") def require_unique_projected_fields(self) -> Self: @@ -242,36 +278,74 @@ def require_unique_projected_fields(self) -> Self: return self +class GapWire(ClosedWireModel): + category: Literal[ + "source_unavailable", + "stale_evidence", + "budget_exhausted", + "capability_unsupported", + ] + retryable: bool = Field(strict=True) + + class CoverageWire(ClosedWireModel): """Typed tenant-safe coverage for the selected package content.""" - status: Literal["empty", "sufficient"] - reason: Literal["no_authorized_evidence"] | None = None + status: Literal["empty", "partial", "sufficient"] + reason: ( + Literal[ + "no_authorized_evidence", + "source_unavailable", + "stale_evidence", + "budget_exhausted", + "capability_unsupported", + ] + | None + ) = None @model_validator(mode="after") def require_status_specific_reason(self) -> Self: - if self.status == "empty" and self.reason != "no_authorized_evidence": + if self.status == "empty" and self.reason is None: raise ValueError("empty coverage requires its tenant-safe reason") if self.status == "sufficient" and self.reason is not None: - raise ValueError("sufficient coverage cannot carry an empty reason") + raise ValueError("sufficient coverage cannot carry a gap reason") + if self.status == "partial" and self.reason in { + None, + "no_authorized_evidence", + }: + raise ValueError("partial coverage requires a non-empty gap reason") return self +class ContinuationOfferWire(ClosedWireModel): + continuationToken: OpaqueCapabilityInput + remainingBudgetDigest: PackageDigestOutput + + class ContextPackageWire(ClosedWireModel): """Public package with an exact block/Evidence closure.""" - organizationRef: OrganizationPackageOutputRef + packageId: PackageOutputRef + packageDigest: PackageDigestOutput purpose: NonblankPurpose - ttlSeconds: PositiveExactInteger + audienceDigest: PackageDigestOutput + policyEpoch: PositivePolicyEpoch + policySnapshotRef: OpaqueOutputRef + decisionRef: DecisionOutputRef + runRef: OpaqueOutputRef + releaseManifestRef: OpaqueOutputRef + retentionPolicyRef: OpaqueOutputRef asOf: datetime expiresAt: datetime - decisionRef: DecisionOutputRef - packageDigest: PackageDigestOutput + ttlSeconds: PositiveExactInteger + tokenizerRef: OpaqueOutputRef + packageSchemaRef: OpaqueOutputRef blocks: tuple[BlockWire, ...] evidence: tuple[EvidenceWire, ...] - gaps: tuple[()] - budgetUsage: BudgetUsageWire + gaps: tuple[GapWire, ...] coverage: CoverageWire + budgetUsage: BudgetUsageWire + continuation: ContinuationOfferWire | None @model_validator(mode="after") def require_exact_authorized_content_closure(self) -> Self: @@ -301,6 +375,9 @@ def require_exact_authorized_content_closure(self) -> Self: item.purpose != self.purpose or item.authorizationAsOf != self.asOf or item.decisionRef != self.decisionRef + or item.policyEpoch != self.policyEpoch + or item.policySnapshotRef != self.policySnapshotRef + or item.runRef != self.runRef ): raise ValueError( "Evidence lineage must match its enclosing package decision" @@ -311,6 +388,7 @@ def require_exact_authorized_content_closure(self) -> Self: exclude={"packageDigest"}, exclude_none=True, ) + complete_context_package_nullable_fields(digest_document) if not verify_context_package_digest( digest_document, self.packageDigest, @@ -341,7 +419,6 @@ class ResolvedWire(ClosedWireModel): kind: Literal["resolved"] package: ContextPackageWire egressGrant: ModelEgressGrantWire | ChannelEgressGrantWire | None = Field( - default=None, discriminator="kind", repr=False, ) @@ -382,3 +459,27 @@ class ServiceUnavailableWire(ClosedWireModel): """Closed response when a required trusted authority is unavailable.""" code: Literal["service_unavailable"] + + +class ApplicationForbiddenWire(ClosedWireModel): + code: Literal["application_forbidden"] + + +class RateLimitedWire(ClosedWireModel): + code: Literal["rate_limited"] + + +def resolution_outcome_public_document( + outcome: ResolutionOutcomeWire, +) -> dict[str, object]: + """Serialize one closed outcome with every frozen required-nullable field.""" + + document = outcome.model_dump(mode="json", by_alias=True, exclude_none=True) + if type(outcome) is not ResolvedWire: + return document + document["egressGrant"] = document.get("egressGrant") + package = document.get("package") + if not isinstance(package, dict): + raise TypeError("resolved wire package must be an object") + complete_context_package_nullable_fields(package) + return document diff --git a/adapters/http/route_policy.py b/adapters/http/route_policy.py new file mode 100644 index 00000000..0f8bd8e3 --- /dev/null +++ b/adapters/http/route_policy.py @@ -0,0 +1,40 @@ +"""Server-owned resolve route policy independent of protected objects.""" + +from __future__ import annotations + +from enum import StrEnum +from typing import Protocol + +from adapters.http.authentication import VerifiedAuthenticationContext + + +class ResolveRouteDecision(StrEnum): + ALLOW = "allow" + FORBID = "forbid" + RATE_LIMIT = "rate_limit" + + +class ResolveRoutePolicy(Protocol): + def decide( + self, + authentication: VerifiedAuthenticationContext, + ) -> ResolveRouteDecision: ... + + +class AllowAuthenticatedResolveRoutePolicy: + """Default server policy after successful transport authentication.""" + + def decide( + self, + authentication: VerifiedAuthenticationContext, + ) -> ResolveRouteDecision: + if type(authentication) is not VerifiedAuthenticationContext: + raise TypeError("resolve route policy requires verified authentication") + return ResolveRouteDecision.ALLOW + + +__all__ = [ + "AllowAuthenticatedResolveRoutePolicy", + "ResolveRouteDecision", + "ResolveRoutePolicy", +] diff --git a/adapters/http/transport.py b/adapters/http/transport.py index 1cd10bea..e0941e9e 100644 --- a/adapters/http/transport.py +++ b/adapters/http/transport.py @@ -51,12 +51,21 @@ def __init__( app: ASGIApp, *, profile: HttpTransportProfile, - resolve_path: str, + resolve_paths: frozenset[str], invalid_response: dict[str, str], ) -> None: self._app = app self._profile = profile - self._resolve_path = resolve_path + if ( + type(resolve_paths) is not frozenset + or not resolve_paths + or any( + type(path) is not str or not path.startswith("/") + for path in resolve_paths + ) + ): + raise ValueError("resolve paths must be a non-empty frozen path set") + self._resolve_paths = resolve_paths self._invalid_response = invalid_response async def __call__( @@ -118,7 +127,7 @@ async def bounded_receive() -> Message: def _is_resolve_request(self, scope: Scope) -> bool: return ( scope.get("method") == "POST" - and _route_relative_path(scope) == self._resolve_path + and _route_relative_path(scope) in self._resolve_paths ) async def _reject(self, scope: Scope, receive: Receive, send: Send) -> None: @@ -162,7 +171,5 @@ def enforce_json_nesting(document: object, *, maximum_depth: int) -> None: else: continue pending.extend( - (child, depth + 1) - for child in children - if isinstance(child, dict | list) + (child, depth + 1) for child in children if isinstance(child, dict | list) ) diff --git a/docs/decisions/0026-normalize-no-authorized-evidence.md b/docs/decisions/0026-normalize-no-authorized-evidence.md index e5ad8ec5..a44e884f 100644 --- a/docs/decisions/0026-normalize-no-authorized-evidence.md +++ b/docs/decisions/0026-normalize-no-authorized-evidence.md @@ -1,6 +1,6 @@ --- name: adr-0026-normalize-no-authorized-evidence -version: "1.1.0" +version: "1.2.0" description: > Make denied, cross-Organization, and nonexistent Acquire candidates share one externally indistinguishable no-authorized-Evidence outcome. @@ -50,12 +50,14 @@ The deterministic oracle compares status, body, the closed product headers, and the Runtime domain outcome. It may normalize only the pre-registered per-resolve values, in this order: -1. `body.package.organizationRef` +1. `body.package.packageId` 2. `body.package.decisionRef` -3. `body.package.asOf` -4. `body.package.expiresAt` -5. `body.package.packageDigest` -6. `headers.X-Context-Request-Id` +3. `body.package.policySnapshotRef` +4. `body.package.runRef` +5. `body.package.asOf` +6. `body.package.expiresAt` +7. `body.package.packageDigest` +8. `headers.X-Context-Request-Id` The compared product headers are `Content-Type`, `Cache-Control`, and `X-Context-Request-Id`. Incidental framework or server headers are not part of @@ -72,11 +74,13 @@ Candidate/Fragment/Resource content, identifier, name, score, reason, or count, remains absent from `Resolved` and HTTP, and cannot treat hostile Candidate metadata as an observed fact. -`packageDigest` joins the normalization allowlist because every per-resolve -Package contains fresh Organization and decision references, so the correct -digest necessarily changes with them. The digest is still required and is -verified against each exact unnormalized Package before comparison; adding it -to this allowlist does not permit arbitrary body drift. +ADR-0047 replaces the earlier Organization-derived outbound reference with an +independent request-scoped `packageId` and adds current run and policy-snapshot +lineage. Those four opaque per-resolve refs and the decision/timestamps vary +without revealing why Evidence is absent. `packageDigest` necessarily changes +with them. The digest is still required and is verified against each exact +unnormalized Package before comparison; adding it to this allowlist does not +permit arbitrary body drift. ## Rationale diff --git a/docs/decisions/0047-freeze-openapi-v0-through-one-runtime-path.md b/docs/decisions/0047-freeze-openapi-v0-through-one-runtime-path.md new file mode 100644 index 00000000..be07ca7b --- /dev/null +++ b/docs/decisions/0047-freeze-openapi-v0-through-one-runtime-path.md @@ -0,0 +1,103 @@ +--- +name: adr-0047-openapi-v0-runtime-bridge +version: "1.0.0" +description: > + Freeze one public OpenAPI v0 resolve contract while keeping the provisional + v1 route as a hidden transport bridge to the same sealed Runtime path. +--- + +# 0047. Freeze OpenAPI v0 through one sealed Runtime path + +- Status: accepted +- Date: 2026-07-23 +- Refines: ADR-0017, ADR-0022, ADR-0028, ADR-0033, ADR-0045, ADR-0046 + +## Context + +M1 exposed the provisional `/v1/context:resolve` route before the public wire +contract was frozen. M2 requires one deterministic public `/v0/resolve` +operation, a complete ContextPackage, authenticated metadata, and an immutable +breaking-change gate. Publishing both paths in OpenAPI would create two client +contracts; implementing two authorization compositions would create a bypass +risk. + +The complete Package also names active release and tokenizer lineage. Those +facts cannot be supplied by a caller or filled with server placeholders. +ContextLearning already owns the sole Organization release pointer, while the +Runtime role previously had no read access to that pointer. + +## Decision + +OpenAPI exposes exactly `POST /v0/resolve`. The provisional +`/v1/context:resolve` route remains temporarily callable but is hidden from the +schema. Both route registrations invoke the same HTTP handler, trusted ingress +construction, sealed Runtime, AuthorizationKernel, Package gates, and egress +gate. The compatibility bridge has no independent domain or authorization +composition. + +The v0 request remains the discriminator-closed Acquire, Continue, and +OpenCitation union. Its authenticated carrier requires one bounded +`X-Context-Request-Id` and permits at most one bounded opaque +`X-Context-Delivery-Evidence-Ref`; duplicate metadata is invalid. The hidden v1 +bridge may retain its temporary server-issued request reference while callers +migrate. Route-level application policy may return only generic 403 or 429 +outcomes after authentication and before Organization, Membership, scope, or +content work. Protected-object authorization never selects those statuses. + +ContextPackage v0 uses a request-scoped opaque `packageId`; it does not expose a +raw Organization identity. It carries the trusted audience digest, policy +epoch/snapshot, decision/run lineage, release manifest, digest-only retention +policy, tokenizer and Package schema refs. File Evidence declares locally +managed Mirrored SourceAclEvidence. Citation and continuation fields are +present but nullable until their owning capabilities activate. + +Runtime receives read-only FORCE-RLS `SELECT` access to the active pointer and +immutable manifest for its exact Organization inside the retained current +UserActor transaction. Both release tables require the complete current +UserActor database context, not an Organization setting alone. A shared +Organization release lock serializes each online observation through delivery +commit with ContextLearning's exclusive promotion lock. + +The observation binds the exact activation generation, manifest digest, +Runtime/Content/Index profile refs and digests, tokenizer, Package schema, and +the exact registered curation-off profile. The public Package release ref is a +domain-separated digest-derived opaque ref over both manifest digest and +activation generation; it never exposes the durable Organization-owned manifest +label and cannot collapse an `A -> B -> A` activation history. v0 recognizes +only its exact registered Content, Index, Runtime, and curation-off profile refs, +digests, schemas, tokenizer, and Package schema. Missing, malformed, or unknown +lineage makes Acquire unavailable before candidate discovery or content work. +Under curation-off, Supply's active Revision pointer remains independently +transactional: ordinary File replacement does not require a release promotion. +If curation-on activates later, its compatible Revision set must be handled in +the same database snapshot required by ADR-0014 rather than as an asynchronous +post-publication Runtime filter. + +Runtime receives no insert, update, delete, promote-function, or audit +authority. It cannot publish, repair, reinterpret, or select a fallback +manifest. + +The accepted `openapi/v0/openapi.json` and checksum are historical artifacts. +The check command regenerates deterministically, verifies recursive structural +equality, verifies its checksum, and requires exact server equality. CI also +loads both artifacts from the pull-request base or preceding push commit and +rejects any byte mutation after first publication, even when code and snapshot +are edited together. The generator refuses to overwrite an existing version +directory; a reviewed new version is required for any contract change. + +## Consequences + +- Generated clients see one public resolve operation and one closed schema. +- Existing internal M1 callers can migrate without a second Runtime path. +- Successful Acquire now proves the Package release/tokenizer lineage was + published by ContextLearning for the exact Organization, while Supply retains + atomic old-or-new active Revision visibility under curation-off. +- Adding fields or changing v0 deliberately requires a new reviewed contract + version rather than rewriting historical evidence. + +## Revisit trigger + +Remove the hidden v1 bridge after all repository-owned callers use the generated +v0 SDK. Revisit release observation only if a measured deployment boundary +requires a separately authenticated read service; it must not add publication +authority or a Runtime fallback manifest. diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 1441d4dd..a0a6ef29 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -44,6 +44,7 @@ kernel, capability separation, and publication visibility model. | File Source progress | [0043 — Separate acquisition and publication progress](0043-separate-file-acquisition-progress-from-publication-progress.md) | Append accepted changes separately from contiguous Runtime-visibility completion and expose them through an Organization/Source-scoped Control read | One ambiguous checkpoint, skipped publication gaps, Runtime authorization from watermarks, or false standard ProviderPort capability claims | | File Source offboarding | [0044 — Disable before cleanup](0044-disable-file-sources-before-cleanup.md) | One trusted Control transaction terminally disables the Source, advances its Organization Policy Epoch, cancels outstanding work, and records immutable pending cleanup lineage | Cleanup-defined revocation, bulk Resource deletion, application-only lifecycle checks, post-disable leases/tickets, or treating progress as authority | | Private delivery ingress | [0045 — Redeem private delivery evidence at ingress](0045-redeem-private-delivery-evidence-at-ingress.md) | One digest-only service/request/asker/audience/epoch-bound DeliveryEvidenceRef constructs private TrustedDeliveryContext inside the current UserActor transaction before content work | Raw trusted delivery facts on the wire, bearer persistence, application-role minting/table reads, alternate Runtime paths, or claiming later M2 carriers | +| Public OpenAPI v0 | [0047 — Freeze OpenAPI v0 through one Runtime path](0047-freeze-openapi-v0-through-one-runtime-path.md) | One public `/v0/resolve` schema and a hidden provisional v1 bridge share the same sealed Runtime; Package release lineage is read-only from the Learning-published active manifest | Two authorization compositions, caller-authored release facts, Runtime publication/fallback, or in-place mutation of historical snapshots | Each baseline ADR is `accepted` and contains Context, Decision, Rationale, Consequences, and Revisit trigger sections. A revisit trigger permits review; it diff --git a/engine/persistence/membership_context.py b/engine/persistence/membership_context.py index ba89f161..d23fe0bb 100644 --- a/engine/persistence/membership_context.py +++ b/engine/persistence/membership_context.py @@ -65,6 +65,7 @@ _observe_current_policy_epoch, _open_policy_epoch_authority_scope, ) +from engine.runtime.release_lineage import ActiveRuntimeRelease class MembershipNotCurrent(Exception): @@ -450,6 +451,75 @@ def project( ) +def _observe_active_runtime_release( + connection: Connection, + organization_id: UUID, +) -> ActiveRuntimeRelease | None: + """Read the sole Learning-published active Runtime profile under FORCE RLS.""" + + row = connection.execute( + text( + """ + SELECT + manifest.organization_id, + active.active_generation, + manifest.manifest_digest, + manifest.content_profile_ref, + manifest.content_schema_ref, + manifest.index_profile_ref, + manifest.index_schema_ref, + manifest.runtime_profile_ref, + manifest.runtime_profile_digest, + manifest.runtime_content_profile_digest, + manifest.runtime_index_profile_digest, + manifest.runtime_tokenizer_ref, + manifest.runtime_package_schema_ref, + manifest.curation_profile_ref, + manifest.curation_profile_digest, + manifest.curation_mode, + manifest.curation_snapshot_ref, + manifest.curation_evaluation_digest, + manifest.compatible_revision_refs, + manifest.active_revision_refs + FROM active_release_manifest AS active + JOIN release_manifest AS manifest + ON manifest.organization_id = active.organization_id + AND manifest.manifest_ref = active.manifest_ref + AND manifest.manifest_digest = active.manifest_digest + WHERE active.organization_id = :organization_id + """ + ), + {"organization_id": organization_id}, + ).one_or_none() + if row is None: + return None + try: + return ActiveRuntimeRelease( + organization_id=row.organization_id, + manifest_digest=row.manifest_digest, + active_generation=row.active_generation, + content_profile_ref=row.content_profile_ref, + content_schema_ref=row.content_schema_ref, + index_profile_ref=row.index_profile_ref, + index_schema_ref=row.index_schema_ref, + runtime_profile_ref=row.runtime_profile_ref, + runtime_profile_digest=row.runtime_profile_digest, + content_profile_digest=row.runtime_content_profile_digest, + index_profile_digest=row.runtime_index_profile_digest, + tokenizer_ref=row.runtime_tokenizer_ref, + package_schema_ref=row.runtime_package_schema_ref, + curation_profile_ref=row.curation_profile_ref, + curation_profile_digest=row.curation_profile_digest, + curation_mode=row.curation_mode, + curation_snapshot_ref=row.curation_snapshot_ref, + curation_evaluation_digest=row.curation_evaluation_digest, + compatible_revision_refs=tuple(row.compatible_revision_refs), + active_revision_refs=tuple(row.active_revision_refs), + ) + except (TypeError, ValueError): + return None + + class _PostgreSQLPolicyEpochPort: """Current Organization epoch reads on the retained Membership transaction.""" @@ -816,6 +886,20 @@ def _current_user_actor_transaction( ), {"organization_id": identity.organization_id}, ) + connection.execute( + text( + """ + SELECT pg_catalog.pg_advisory_xact_lock_shared( + pg_catalog.hashtextextended( + 'context-engine.release:' + || CAST(:organization_id AS text), + 0 + ) + ) + """ + ), + {"organization_id": identity.organization_id}, + ) scope = _open_membership_authority_scope() projection_scope = _open_materialized_projection_scope() @@ -865,6 +949,10 @@ def _current_user_actor_transaction( port=_PostgreSQLEgressGrantIssuancePort(connection), ) ), + active_runtime_release=_observe_active_runtime_release( + connection, + identity.organization_id, + ), ) finally: _close_egress_grant_issuance_scope(egress_issuance_scope) diff --git a/engine/persistence/schema_security_manifest.yaml b/engine/persistence/schema_security_manifest.yaml index 779ac079..9ad1c00d 100644 --- a/engine/persistence/schema_security_manifest.yaml +++ b/engine/persistence/schema_security_manifest.yaml @@ -10,7 +10,10 @@ "organizationScopedIdempotency": true, "filesystemAccessAllowed": false, "durableJobCreationAllowed": false, - "atomicWrites": ["context_source", "source_version"] + "atomicWrites": [ + "context_source", + "source_version" + ] }, { "name": "change_resource_access", @@ -31,9 +34,19 @@ "directTableMutationAllowed": false, "trustedOrganizationSource": "TrustedControlCall", "databaseOwnedTime": true, - "idempotencyBinding": ["organization_id", "source_id", "resource_ref"], + "idempotencyBinding": [ + "organization_id", + "source_id", + "resource_ref" + ], "runtimeVisibilityBarrier": "Organization-scoped shared Runtime/exclusive publication transaction advisory lock", - "atomicWrites": ["context_resource", "organization_policy_epoch", "file_resource_cleanup_intent", "file_source_acquisition_checkpoint", "file_source_publish_watermark"] + "atomicWrites": [ + "context_resource", + "organization_policy_epoch", + "file_resource_cleanup_intent", + "file_source_acquisition_checkpoint", + "file_source_publish_watermark" + ] }, { "name": "offboard_file_source", @@ -43,11 +56,19 @@ "directTableMutationAllowed": false, "trustedOrganizationSource": "TrustedControlCall", "databaseOwnedTime": true, - "idempotencyBinding": ["organization_id", "source_id"], + "idempotencyBinding": [ + "organization_id", + "source_id" + ], "runtimeVisibilityBarrier": "Organization-scoped shared Runtime/exclusive publication transaction advisory lock", "securityCompletion": "source disabled and Organization Policy Epoch advanced before commit", "cleanupCompletion": "asynchronous and pending", - "atomicWrites": ["context_source", "organization_policy_epoch", "file_source_cleanup_intent", "file_import_job"] + "atomicWrites": [ + "context_source", + "organization_policy_epoch", + "file_source_cleanup_intent", + "file_import_job" + ] }, { "name": "read_file_source_progress", @@ -56,10 +77,17 @@ "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false, "trustedOrganizationSource": "TrustedControlCall", - "scope": ["organization_id", "source_id"], + "scope": [ + "organization_id", + "source_id" + ], "watermarkRule": "highest contiguous acquisition sequence with a committed visibility outcome", "runtimeAuthorityAllowed": false, - "reads": ["context_source", "file_source_acquisition_checkpoint", "file_source_publish_watermark"] + "reads": [ + "context_source", + "file_source_acquisition_checkpoint", + "file_source_publish_watermark" + ] }, { "name": "issue_noop_worker_lease", @@ -70,7 +98,9 @@ "databaseOwnedTime": true, "maxTtlSeconds": 3600, "expiredLeaseReissuance": true, - "atomicWrites": ["worker_noop_job"] + "atomicWrites": [ + "worker_noop_job" + ] }, { "name": "complete_noop_worker_job", @@ -87,7 +117,9 @@ "operation": "noop.complete" }, "callerSuppliedReceiverDimensions": [], - "atomicWrites": ["worker_noop_job"] + "atomicWrites": [ + "worker_noop_job" + ] }, { "name": "prepare_file_import", @@ -100,7 +132,13 @@ "databaseOwnedTime": true, "filesystemAccessAllowed": false, "durableJobCreationAllowed": true, - "atomicWrites": ["source_version", "context_source", "file_acquisition", "file_import_job", "file_source_acquisition_checkpoint"] + "atomicWrites": [ + "source_version", + "context_source", + "file_acquisition", + "file_import_job", + "file_source_acquisition_checkpoint" + ] }, { "name": "issue_file_import_lease", @@ -111,8 +149,16 @@ "databaseOwnedTime": true, "maxTtlSeconds": 3600, "signedLeaseGeneration": true, - "reclaimableStatesAfterExpiry": ["leased", "running", "prepared", "ready"], - "atomicWrites": ["file_import_job", "file_import_job_event"] + "reclaimableStatesAfterExpiry": [ + "leased", + "running", + "prepared", + "ready" + ], + "atomicWrites": [ + "file_import_job", + "file_import_job_event" + ] }, { "name": "redeem_file_import_lease", @@ -127,7 +173,9 @@ "workerAudience": "context-engine-worker", "operation": "file.import" }, - "atomicWrites": ["file_import_job"] + "atomicWrites": [ + "file_import_job" + ] }, { "name": "publish_file_import", @@ -141,17 +189,30 @@ "rawNonceComparedAsSha256": true, "contentIdentity": { "domain": "context-engine.file-content-identity.v1", - "dimensions": ["organization_id", "source_id", "resource_ref", "canonical_content_hash", "compiler_version", "config_version"], + "dimensions": [ + "organization_id", + "source_id", + "resource_ref", + "canonical_content_hash", + "compiler_version", + "config_version" + ], "concurrencyArbitration": "file_resource_ingestion_guard row lock", "unchangedReasonCode": "active-content-identity-match", "sourceContentRetainedInOutcome": false }, "atomicWrites": [ - "file_resource_ingestion_guard", "file_acquisition_result", - "context_resource", "context_revision", "file_revision_snapshot", - "context_fragment", "revision_publication_event", - "exact_phrase_candidate", "resource_access_policy", - "membership_resource_field_right", "file_import_job", + "file_resource_ingestion_guard", + "file_acquisition_result", + "context_resource", + "context_revision", + "file_revision_snapshot", + "context_fragment", + "revision_publication_event", + "exact_phrase_candidate", + "resource_access_policy", + "membership_resource_field_right", + "file_import_job", "file_source_publish_watermark" ] }, @@ -166,22 +227,32 @@ "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false, "rawNonceComparedAsSha256": true, - "transactions": ["stage complete replacement", "activate active pointer"], + "transactions": [ + "stage complete replacement", + "activate active pointer" + ], "stageInvariant": "the old active Revision remains the only Runtime-visible Revision until the complete replacement is prepared and indexed", "stageRaceOutcome": "an equivalent concurrent winner completes the late job as unchanged only after the supplied v1/v2 compilation exactly matches the active artifact", "activationInvariant": "one compare-and-swap transaction changes the active pointer, appends active evidence and supersession lineage, and completes the job", "runtimeVisibilityBarrier": "Organization-scoped shared Runtime/exclusive activation transaction advisory lock", "retention": "superseded Revisions remain immutable and retained_until_explicit_cleanup", "stageAtomicWrites": [ - "file_resource_ingestion_guard", "file_acquisition_result", - "context_revision", "file_revision_snapshot", "context_fragment", - "revision_publication_event", "exact_phrase_candidate", - "file_revision_replacement_plan", "file_import_job", + "file_resource_ingestion_guard", + "file_acquisition_result", + "context_revision", + "file_revision_snapshot", + "context_fragment", + "revision_publication_event", + "exact_phrase_candidate", + "file_revision_replacement_plan", + "file_import_job", "file_source_publish_watermark" ], "activationAtomicWrites": [ - "context_resource", "revision_publication_event", - "file_revision_supersession", "file_import_job", + "context_resource", + "revision_publication_event", + "file_revision_supersession", + "file_import_job", "file_source_publish_watermark" ] }, @@ -198,16 +269,62 @@ "role": "context_engine_worker", "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false, - "durableBoundaries": ["acquired", "prepared", "ready", "completed"], + "durableBoundaries": [ + "acquired", + "prepared", + "ready", + "completed" + ], "leaseReclaim": "only an expired leased, running, prepared, or ready job can receive a higher lease generation; the old nonce can no longer redeem or mutate", - "idempotencyBinding": ["organization_id", "job_id", "source_id", "resource_ref", "revision_id", "content_identity_digest", "publication_payload_digest"], + "idempotencyBinding": [ + "organization_id", + "job_id", + "source_id", + "resource_ref", + "revision_id", + "content_identity_digest", + "publication_payload_digest" + ], "concurrentPublicationArbitration": "the Organization/Source/Resource ingestion guard serializes classification; a late identical job observes the winner as unchanged", "activationInvariant": "authorization and complete Fragment/index evidence are revalidated before one active-pointer transaction", "atomicWritesByBoundary": { - "acquired": ["file_resource_ingestion_guard", "file_acquisition_result", "file_source_publish_watermark", "file_publication_recovery", "file_import_job", "file_import_job_event"], - "prepared": ["context_resource", "context_revision", "file_revision_snapshot", "context_fragment", "revision_publication_event", "resource_access_policy", "membership_resource_field_right", "file_publication_recovery", "file_import_job", "file_import_job_event"], - "ready": ["exact_phrase_candidate", "revision_publication_event", "file_revision_replacement_plan", "file_publication_recovery", "file_import_job", "file_import_job_event"], - "completed": ["context_resource", "revision_publication_event", "file_source_publish_watermark", "file_revision_supersession", "file_publication_recovery", "file_import_job", "file_import_job_event"] + "acquired": [ + "file_resource_ingestion_guard", + "file_acquisition_result", + "file_source_publish_watermark", + "file_publication_recovery", + "file_import_job", + "file_import_job_event" + ], + "prepared": [ + "context_resource", + "context_revision", + "file_revision_snapshot", + "context_fragment", + "revision_publication_event", + "resource_access_policy", + "membership_resource_field_right", + "file_publication_recovery", + "file_import_job", + "file_import_job_event" + ], + "ready": [ + "exact_phrase_candidate", + "revision_publication_event", + "file_revision_replacement_plan", + "file_publication_recovery", + "file_import_job", + "file_import_job_event" + ], + "completed": [ + "context_resource", + "revision_publication_event", + "file_source_publish_watermark", + "file_revision_supersession", + "file_publication_recovery", + "file_import_job", + "file_import_job_event" + ] } }, { @@ -219,7 +336,9 @@ "databaseOwnedTime": true, "rawNonceComparedAsSha256": true, "reasonOrContentPersistenceAllowed": false, - "atomicWrites": ["file_import_job"] + "atomicWrites": [ + "file_import_job" + ] }, { "name": "context_learning_promote_release", @@ -229,7 +348,10 @@ "directTableMutationAllowed": false, "databaseOwnedTime": true, "securityDefiner": true, - "searchPath": ["pg_catalog", "pg_temp"], + "searchPath": [ + "pg_catalog", + "pg_temp" + ], "rowSecurity": true, "sessionUser": "context_engine_learning", "expectedState": { @@ -279,7 +401,9 @@ "purpose": "Organization security root", "primaryKey": { "name": "pk_organization", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] }, "permittedOperations": { "context_engine_runtime": [], @@ -294,7 +418,9 @@ "purpose": "Global user identity root without tenant rights", "primaryKey": { "name": "pk_user_account", - "columns": ["user_id"] + "columns": [ + "user_id" + ] }, "permittedOperations": { "context_engine_runtime": [], @@ -307,7 +433,9 @@ "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-SCOPE-INTERSECTION-004", - "selector": {"table": "membership"} + "selector": { + "table": "membership" + } }, "purpose": "Organization-scoped current UserActor membership authority", "organizationColumn": "organization_id", @@ -315,34 +443,52 @@ { "name": "pk_membership", "kind": "primary_key", - "columns": ["organization_id", "membership_id"] + "columns": [ + "organization_id", + "membership_id" + ] }, { "name": "uq_membership_organization_user", "kind": "unique", - "columns": ["organization_id", "user_id"] + "columns": [ + "organization_id", + "user_id" + ] }, { "name": "uq_membership_organization_id_version", "kind": "unique", - "columns": ["organization_id", "membership_id", "membership_version"] + "columns": [ + "organization_id", + "membership_id", + "membership_version" + ] } ], "foreignKeys": [ { "name": "fk_membership_organization", - "columns": ["organization_id"], + "columns": [ + "organization_id" + ], "references": { "table": "organization", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] } }, { "name": "fk_membership_user_account", - "columns": ["user_id"], + "columns": [ + "user_id" + ], "references": { "table": "user_account", - "columns": ["user_id"] + "columns": [ + "user_id" + ] } } ], @@ -367,42 +513,60 @@ { "name": "membership_current_user_actor", "command": "SELECT", - "roles": ["context_engine_runtime"], + "roles": [ + "context_engine_runtime" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'user' AND user_id = NULLIF(current_setting('app.user_id', true), '')::uuid AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL AND membership_id = NULLIF(current_setting('app.membership_id', true), '')::uuid AND membership_version = NULLIF(current_setting('app.membership_version', true), '')::bigint AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL AND NULLIF(current_setting('app.authentication_binding_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL AND status = 'active' AND valid_from <= NULLIF(current_setting('app.checked_at', true), '')::timestamptz AND (valid_until IS NULL OR valid_until > NULLIF(current_setting('app.checked_at', true), '')::timestamptz)" }, { "name": "membership_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" }, { "name": "membership_file_import_definer_select", "command": "SELECT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "membership_delivery_evidence_definer_select", "command": "SELECT", - "roles": ["context_engine_delivery_evidence_definer"], + "roles": [ + "context_engine_delivery_evidence_definer" + ], "using": "true" }, { "name": "membership_egress_definer_select", "command": "SELECT", - "roles": ["context_engine_egress_grant_definer"], + "roles": [ + "context_engine_egress_grant_definer" + ], "using": "true" } ] }, "permittedOperations": { - "context_engine_runtime": ["SELECT"], + "context_engine_runtime": [ + "SELECT" + ], "context_engine_worker": [], - "context_engine_worker_lease_definer": ["SELECT"], - "context_engine_delivery_evidence_definer": ["SELECT"], - "context_engine_egress_grant_definer": ["SELECT"] + "context_engine_worker_lease_definer": [ + "SELECT" + ], + "context_engine_delivery_evidence_definer": [ + "SELECT" + ], + "context_engine_egress_grant_definer": [ + "SELECT" + ] }, "partitions": [], "securityInvariantIds": [ @@ -422,61 +586,201 @@ "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-DELIVERY-EVIDENCE-063", - "selector": {"table": "delivery_evidence"} + "selector": { + "table": "delivery_evidence" + } }, "purpose": "Digest-only exact private delivery evidence with stable logical retry identity", "organizationColumn": "organization_id", "organizationInclusiveKeys": [ - {"name": "pk_delivery_evidence", "kind": "primary_key", "columns": ["organization_id", "evidence_digest"]}, - {"name": "uq_delivery_evidence_logical_request", "kind": "unique", "columns": ["organization_id", "authenticated_service_ref", "request_id"]}, - {"name": "uq_delivery_evidence_logical_resolution", "kind": "unique", "columns": ["organization_id", "logical_resolution_ref"]} + { + "name": "pk_delivery_evidence", + "kind": "primary_key", + "columns": [ + "organization_id", + "evidence_digest" + ] + }, + { + "name": "uq_delivery_evidence_logical_request", + "kind": "unique", + "columns": [ + "organization_id", + "authenticated_service_ref", + "request_id" + ] + }, + { + "name": "uq_delivery_evidence_logical_resolution", + "kind": "unique", + "columns": [ + "organization_id", + "logical_resolution_ref" + ] + } ], "capabilityUniqueKeys": [ - {"name": "uq_delivery_evidence_digest_global", "kind": "unique", "columns": ["evidence_digest"], "rationale": "one bearer digest identifies at most one Organization-bound attestation locator"} + { + "name": "uq_delivery_evidence_digest_global", + "kind": "unique", + "columns": [ + "evidence_digest" + ], + "rationale": "one bearer digest identifies at most one Organization-bound attestation locator" + } ], "foreignKeys": [ - {"name": "fk_delivery_evidence_organization", "columns": ["organization_id"], "references": {"table": "organization", "columns": ["organization_id"]}, "onDelete": "CASCADE"}, - {"name": "fk_delivery_evidence_membership_version_same_organization", "columns": ["organization_id", "membership_id", "membership_version"], "references": {"table": "membership", "columns": ["organization_id", "membership_id", "membership_version"]}} + { + "name": "fk_delivery_evidence_organization", + "columns": [ + "organization_id" + ], + "references": { + "table": "organization", + "columns": [ + "organization_id" + ] + }, + "onDelete": "CASCADE" + }, + { + "name": "fk_delivery_evidence_membership_version_same_organization", + "columns": [ + "organization_id", + "membership_id", + "membership_version" + ], + "references": { + "table": "membership", + "columns": [ + "organization_id", + "membership_id", + "membership_version" + ] + } + } ], "checkConstraints": [ - {"name": "ck_delivery_evidence_digest_sha256", "expression": "octet_length(evidence_digest) = 32"}, - {"name": "ck_delivery_evidence_digest_profile", "expression": "digest_profile = 'delivery-evidence-ref-sha256-v1'"}, - {"name": "ck_delivery_evidence_private_kind", "expression": "delivery_kind = 'private'"}, - {"name": "ck_delivery_evidence_profile", "expression": "profile_ref = 'private-delivery-evidence-v1'"}, - {"name": "ck_delivery_evidence_positive_versions", "expression": "membership_version > 0 AND policy_epoch > 0"}, - {"name": "ck_delivery_evidence_audience_digest", "expression": "audience_digest ~ '^[0-9a-f]{64}$'"}, - {"name": "ck_delivery_evidence_timestamp_order", "expression": "expires_at > issued_at AND (first_redeemed_at IS NULL OR (first_redeemed_at >= issued_at AND first_redeemed_at < expires_at))"}, - {"name": "ck_delivery_evidence_bindings_nonblank", "expression": "all exact service/request/destination/consumer/purpose/logical-resolution bindings are nonblank"} + { + "name": "ck_delivery_evidence_digest_sha256", + "expression": "octet_length(evidence_digest) = 32" + }, + { + "name": "ck_delivery_evidence_digest_profile", + "expression": "digest_profile = 'delivery-evidence-ref-sha256-v1'" + }, + { + "name": "ck_delivery_evidence_private_kind", + "expression": "delivery_kind = 'private'" + }, + { + "name": "ck_delivery_evidence_profile", + "expression": "profile_ref = 'private-delivery-evidence-v1'" + }, + { + "name": "ck_delivery_evidence_positive_versions", + "expression": "membership_version > 0 AND policy_epoch > 0" + }, + { + "name": "ck_delivery_evidence_audience_digest", + "expression": "audience_digest ~ '^[0-9a-f]{64}$'" + }, + { + "name": "ck_delivery_evidence_timestamp_order", + "expression": "expires_at > issued_at AND (first_redeemed_at IS NULL OR (first_redeemed_at >= issued_at AND first_redeemed_at < expires_at))" + }, + { + "name": "ck_delivery_evidence_bindings_nonblank", + "expression": "all exact service/request/destination/consumer/purpose/logical-resolution bindings are nonblank" + } ], "rowLevelSecurity": { "enabled": true, "forced": true, "policies": [ - {"name": "delivery_evidence_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "delivery_evidence_definer_all", "command": "ALL", "roles": ["context_engine_delivery_evidence_definer"], "using": "true", "withCheck": "true"} + { + "name": "delivery_evidence_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "delivery_evidence_definer_all", + "command": "ALL", + "roles": [ + "context_engine_delivery_evidence_definer" + ], + "using": "true", + "withCheck": "true" + } ] }, - "functionOnlyMutation": {"databaseFunctions": ["context_identity_issue_private_delivery_evidence", "context_identity_delete_expired_private_delivery_evidence", "context_runtime_redeem_private_delivery_evidence"], "definerRole": "context_engine_delivery_evidence_definer", "directTableMutationAllowed": false}, - "retention": {"class": "short_lived_digest_only", "bearerStored": false, "expirySource": "versioned private delivery profile", "cleanup": "context_identity_delete_expired_private_delivery_evidence deletes only database-expired private rows in one exact Organization"}, + "functionOnlyMutation": { + "databaseFunctions": [ + "context_identity_issue_private_delivery_evidence", + "context_identity_delete_expired_private_delivery_evidence", + "context_runtime_redeem_private_delivery_evidence" + ], + "definerRole": "context_engine_delivery_evidence_definer", + "directTableMutationAllowed": false + }, + "retention": { + "class": "short_lived_digest_only", + "bearerStored": false, + "expirySource": "versioned private delivery profile", + "cleanup": "context_identity_delete_expired_private_delivery_evidence deletes only database-expired private rows in one exact Organization" + }, "permittedOperations": { - "context_engine_identity": ["EXECUTE context_identity_issue_private_delivery_evidence", "EXECUTE context_identity_delete_expired_private_delivery_evidence"], - "context_engine_runtime": ["EXECUTE context_runtime_redeem_private_delivery_evidence"], - "context_engine_delivery_evidence_definer": ["SELECT", "INSERT", "UPDATE", "DELETE"], + "context_engine_identity": [ + "EXECUTE context_identity_issue_private_delivery_evidence", + "EXECUTE context_identity_delete_expired_private_delivery_evidence" + ], + "context_engine_runtime": [ + "EXECUTE context_runtime_redeem_private_delivery_evidence" + ], + "context_engine_delivery_evidence_definer": [ + "SELECT", + "INSERT", + "UPDATE", + "DELETE" + ], "context_engine_control": [], "context_engine_worker": [], "context_engine_learning": [], "context_engine_security_operator": [] }, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "REVOCATION-006", "TRANSPORT-UNTRUSTED-008", "NON-ENUMERATION-009", "TRACE-REDACTION-012"], - "negativeTestIds": ["DB-001", "DB-002", "DB-004", "DB-008", "DB-009", "DB-010", "OBS-004", "OBS-005"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "REVOCATION-006", + "TRANSPORT-UNTRUSTED-008", + "NON-ENUMERATION-009", + "TRACE-REDACTION-012" + ], + "negativeTestIds": [ + "DB-001", + "DB-002", + "DB-004", + "DB-008", + "DB-009", + "DB-010", + "OBS-004", + "OBS-005" + ] }, { "name": "organization_record", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-TENANT-FK-002", - "selector": {"table": "organization_record"} + "selector": { + "table": "organization_record" + } }, "purpose": "Representative tenant-owned record protected by current UserActor Membership", "organizationColumn": "organization_id", @@ -484,24 +788,37 @@ { "name": "pk_organization_record", "kind": "primary_key", - "columns": ["organization_id", "record_id"] + "columns": [ + "organization_id", + "record_id" + ] } ], "foreignKeys": [ { "name": "fk_organization_record_organization", - "columns": ["organization_id"], + "columns": [ + "organization_id" + ], "references": { "table": "organization", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] } }, { "name": "fk_organization_record_parent_same_organization", - "columns": ["organization_id", "parent_record_id"], + "columns": [ + "organization_id", + "parent_record_id" + ], "references": { "table": "organization_record", - "columns": ["organization_id", "record_id"] + "columns": [ + "organization_id", + "record_id" + ] } } ], @@ -512,14 +829,18 @@ { "name": "organization_record_organization_isolation", "command": "ALL", - "roles": ["context_engine_runtime"], + "roles": [ + "context_engine_runtime" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND EXISTS (SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = organization_record.organization_id AND actor_membership.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'user' AND actor_membership.user_id = NULLIF(current_setting('app.user_id', true), '')::uuid AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL AND actor_membership.membership_id = NULLIF(current_setting('app.membership_id', true), '')::uuid AND actor_membership.membership_version = NULLIF(current_setting('app.membership_version', true), '')::bigint AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL AND NULLIF(current_setting('app.authentication_binding_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL AND actor_membership.status = 'active' AND actor_membership.valid_from <= NULLIF(current_setting('app.checked_at', true), '')::timestamptz AND (actor_membership.valid_until IS NULL OR actor_membership.valid_until > NULLIF(current_setting('app.checked_at', true), '')::timestamptz))", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND EXISTS (SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = organization_record.organization_id AND actor_membership.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'user' AND actor_membership.user_id = NULLIF(current_setting('app.user_id', true), '')::uuid AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL AND actor_membership.membership_id = NULLIF(current_setting('app.membership_id', true), '')::uuid AND actor_membership.membership_version = NULLIF(current_setting('app.membership_version', true), '')::bigint AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL AND NULLIF(current_setting('app.authentication_binding_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL AND actor_membership.status = 'active' AND actor_membership.valid_from <= NULLIF(current_setting('app.checked_at', true), '')::timestamptz AND (actor_membership.valid_until IS NULL OR actor_membership.valid_until > NULLIF(current_setting('app.checked_at', true), '')::timestamptz))" }, { "name": "organization_record_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" } @@ -529,14 +850,23 @@ "function": "organization_record_require_write_context", "timing": "BEFORE", "orientation": "STATEMENT", - "events": ["INSERT", "UPDATE", "DELETE"], + "events": [ + "INSERT", + "UPDATE", + "DELETE" + ], "missingContextSqlstate": "42501", "requiredActorKind": "user", "requiresCurrentMembership": true } }, "permittedOperations": { - "context_engine_runtime": ["SELECT", "INSERT", "UPDATE", "DELETE"], + "context_engine_runtime": [ + "SELECT", + "INSERT", + "UPDATE", + "DELETE" + ], "context_engine_worker": [] }, "partitions": [], @@ -564,7 +894,9 @@ "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-FILE-SOURCE-RLS-021", - "selector": {"table": "context_source"} + "selector": { + "table": "context_source" + } }, "purpose": "Stable Organization-owned File source identity, active immutable SourceVersion pointer, and terminal disabled lifecycle", "organizationColumn": "organization_id", @@ -572,30 +904,49 @@ { "name": "pk_context_source", "kind": "primary_key", - "columns": ["organization_id", "source_id"] + "columns": [ + "organization_id", + "source_id" + ] }, { "name": "uq_context_source_registration_idempotency", "kind": "unique", - "columns": ["organization_id", "registration_operation", "idempotency_key"] + "columns": [ + "organization_id", + "registration_operation", + "idempotency_key" + ] } ], "foreignKeys": [ { "name": "fk_context_source_organization", - "columns": ["organization_id"], + "columns": [ + "organization_id" + ], "references": { "table": "organization", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] }, "onDelete": "CASCADE" }, { "name": "fk_context_source_active_version_same_organization", - "columns": ["organization_id", "source_id", "active_version_id"], + "columns": [ + "organization_id", + "source_id", + "active_version_id" + ], "references": { "table": "source_version", - "columns": ["organization_id", "source_id", "version_id"] + "columns": [ + "organization_id", + "source_id", + "version_id" + ] }, "onDelete": "RESTRICT", "deferrable": true, @@ -603,8 +954,19 @@ }, { "name": "fk_context_source_disabled_version_exact", - "columns": ["organization_id", "source_id", "disabled_version_id"], - "references": {"table": "source_version", "columns": ["organization_id", "source_id", "version_id"]}, + "columns": [ + "organization_id", + "source_id", + "disabled_version_id" + ], + "references": { + "table": "source_version", + "columns": [ + "organization_id", + "source_id", + "version_id" + ] + }, "deferrable": true, "initially": "DEFERRED" } @@ -642,58 +1004,82 @@ { "name": "context_source_control_insert", "command": "INSERT", - "roles": ["context_engine_control"], + "roles": [ + "context_engine_control" + ], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "context_source_control_select", "command": "SELECT", - "roles": ["context_engine_control"], + "roles": [ + "context_engine_control" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "context_source_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" }, { "name": "context_source_file_import_definer_select", "command": "SELECT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND lifecycle_state = 'active'" }, { "name": "context_source_file_import_definer_update", "command": "UPDATE", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND lifecycle_state = 'active'", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND lifecycle_state = 'active'" }, { "name": "context_source_access_policy_definer_select", "command": "SELECT", - "roles": ["context_engine_access_policy_definer"], + "roles": [ + "context_engine_access_policy_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "context_source_access_policy_definer_update", "command": "UPDATE", - "roles": ["context_engine_access_policy_definer"], + "roles": [ + "context_engine_access_policy_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" } ] }, "permittedOperations": { - "context_engine_access_policy_definer": ["SELECT", "UPDATE lifecycle_state, disabled_version_id, disabled_at"], - "context_engine_control": ["SELECT", "INSERT", "EXECUTE context_control_offboard_file_source"], + "context_engine_access_policy_definer": [ + "SELECT", + "UPDATE lifecycle_state, disabled_version_id, disabled_at" + ], + "context_engine_control": [ + "SELECT", + "INSERT", + "EXECUTE context_control_offboard_file_source" + ], "context_engine_learning": [], "context_engine_runtime": [], "context_engine_security_operator": [], "context_engine_worker": [], - "context_engine_worker_lease_definer": ["SELECT", "UPDATE"] + "context_engine_worker_lease_definer": [ + "SELECT", + "UPDATE" + ] }, "partitions": [], "securityInvariantIds": [ @@ -702,14 +1088,22 @@ "RLS-FAIL-CLOSED-003", "REVOCATION-006" ], - "negativeTestIds": ["DB-001", "DB-003", "DB-004", "DB-008", "PG-FILE-SOURCE-OFFBOARD-030"] + "negativeTestIds": [ + "DB-001", + "DB-003", + "DB-004", + "DB-008", + "PG-FILE-SOURCE-OFFBOARD-030" + ] }, { "name": "source_version", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-FILE-SOURCE-RLS-021", - "selector": {"table": "source_version"} + "selector": { + "table": "source_version" + } }, "purpose": "Immutable Organization-owned File source configuration and exact capability declaration", "organizationColumn": "organization_id", @@ -717,16 +1111,26 @@ { "name": "pk_source_version", "kind": "primary_key", - "columns": ["organization_id", "source_id", "version_id"] + "columns": [ + "organization_id", + "source_id", + "version_id" + ] } ], "foreignKeys": [ { "name": "fk_source_version_source_same_organization", - "columns": ["organization_id", "source_id"], + "columns": [ + "organization_id", + "source_id" + ], "references": { "table": "context_source", - "columns": ["organization_id", "source_id"] + "columns": [ + "organization_id", + "source_id" + ] }, "deferrable": true, "initially": "DEFERRED" @@ -753,32 +1157,42 @@ { "name": "source_version_control_insert", "command": "INSERT", - "roles": ["context_engine_control"], + "roles": [ + "context_engine_control" + ], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "source_version_control_select", "command": "SELECT", - "roles": ["context_engine_control"], + "roles": [ + "context_engine_control" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "source_version_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" }, { "name": "source_version_file_import_definer_select", "command": "SELECT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "source_version_file_import_definer_insert", "command": "INSERT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" } ] @@ -786,16 +1200,25 @@ "immutableRows": { "trigger": "source_version_immutable", "function": "source_version_reject_mutation", - "events": ["UPDATE", "DELETE"], + "events": [ + "UPDATE", + "DELETE" + ], "sqlstate": "55000" }, "permittedOperations": { - "context_engine_control": ["SELECT", "INSERT"], + "context_engine_control": [ + "SELECT", + "INSERT" + ], "context_engine_learning": [], "context_engine_runtime": [], "context_engine_security_operator": [], "context_engine_worker": [], - "context_engine_worker_lease_definer": ["SELECT", "INSERT"] + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT" + ] }, "partitions": [], "securityInvariantIds": [ @@ -803,14 +1226,21 @@ "TENANT-FK-002", "RLS-FAIL-CLOSED-003" ], - "negativeTestIds": ["DB-001", "DB-003", "DB-004", "DB-008"] + "negativeTestIds": [ + "DB-001", + "DB-003", + "DB-004", + "DB-008" + ] }, { "name": "context_resource", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-INDEX-NOT-AUTHORITY-005", - "selector": {"table": "context_resource"} + "selector": { + "table": "context_resource" + } }, "purpose": "Stable Organization-owned source object and active immutable Revision pointer", "organizationColumn": "organization_id", @@ -818,24 +1248,39 @@ { "name": "pk_context_resource", "kind": "primary_key", - "columns": ["organization_id", "resource_ref"] + "columns": [ + "organization_id", + "resource_ref" + ] } ], "foreignKeys": [ { "name": "fk_context_resource_organization", - "columns": ["organization_id"], + "columns": [ + "organization_id" + ], "references": { "table": "organization", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] } }, { "name": "fk_context_resource_active_revision_same_organization", - "columns": ["organization_id", "resource_ref", "active_revision_id"], + "columns": [ + "organization_id", + "resource_ref", + "active_revision_id" + ], "references": { "table": "context_revision", - "columns": ["organization_id", "resource_ref", "revision_id"] + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ] }, "deferrable": true, "initially": "DEFERRED" @@ -848,57 +1293,96 @@ { "name": "context_resource_current_user_actor", "command": "SELECT", - "roles": ["context_engine_runtime"], + "roles": [ + "context_engine_runtime" + ], "using": "context_resource.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND context_resource.tombstoned IS FALSE AND EXISTS (SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = context_resource.organization_id AND actor_membership.user_id = NULLIF(current_setting('app.user_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'user' AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL AND actor_membership.membership_id = NULLIF(current_setting('app.membership_id', true), '')::uuid AND actor_membership.membership_version = NULLIF(current_setting('app.membership_version', true), '')::bigint AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL AND NULLIF(current_setting('app.authentication_binding_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL AND actor_membership.status = 'active' AND actor_membership.valid_from <= NULLIF(current_setting('app.checked_at', true), '')::timestamptz AND (actor_membership.valid_until IS NULL OR actor_membership.valid_until > NULLIF(current_setting('app.checked_at', true), '')::timestamptz)) AND public.context_runtime_file_source_lifecycle_allows(context_resource.organization_id, context_resource.source_ref)" }, { "name": "context_resource_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" }, { "name": "context_resource_file_import_definer_select", "command": "SELECT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "context_resource_file_import_definer_insert", "command": "INSERT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "context_resource_file_import_definer_update", "command": "UPDATE", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "context_resource_access_policy_definer_select", "command": "SELECT", - "roles": ["context_engine_access_policy_definer"], + "roles": [ + "context_engine_access_policy_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "context_resource_access_policy_definer_update", "command": "UPDATE", - "roles": ["context_engine_access_policy_definer"], + "roles": [ + "context_engine_access_policy_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" } ] }, - "functionOnlyMutation": {"databaseFunctions": ["context_worker_prepare_file_publication", "context_worker_activate_recoverable_file_publication", "context_control_tombstone_file_resource"], "definerRoles": ["context_engine_worker_lease_definer", "context_engine_access_policy_definer"], "directTableMutationAllowed": false}, + "functionOnlyMutation": { + "databaseFunctions": [ + "context_worker_prepare_file_publication", + "context_worker_activate_recoverable_file_publication", + "context_control_tombstone_file_resource" + ], + "definerRoles": [ + "context_engine_worker_lease_definer", + "context_engine_access_policy_definer" + ], + "directTableMutationAllowed": false + }, "permittedOperations": { - "context_engine_access_policy_definer": ["SELECT", "UPDATE tombstoned"], - "context_engine_control": ["EXECUTE context_control_tombstone_file_resource"], - "context_engine_runtime": ["SELECT"], - "context_engine_worker": ["EXECUTE context_worker_prepare_file_publication", "EXECUTE context_worker_activate_recoverable_file_publication"], - "context_engine_worker_lease_definer": ["SELECT", "INSERT", "UPDATE"] + "context_engine_access_policy_definer": [ + "SELECT", + "UPDATE tombstoned" + ], + "context_engine_control": [ + "EXECUTE context_control_tombstone_file_resource" + ], + "context_engine_runtime": [ + "SELECT" + ], + "context_engine_worker": [ + "EXECUTE context_worker_prepare_file_publication", + "EXECUTE context_worker_activate_recoverable_file_publication" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT", + "UPDATE" + ] }, "partitions": [], "securityInvariantIds": [ @@ -908,14 +1392,23 @@ "INDEX-NOT-AUTHORITY-005", "REVOCATION-006" ], - "negativeTestIds": ["DB-001", "DB-002", "DB-004", "DB-009", "DB-010", "PG-FILE-TOMBSTONE-028"] + "negativeTestIds": [ + "DB-001", + "DB-002", + "DB-004", + "DB-009", + "DB-010", + "PG-FILE-TOMBSTONE-028" + ] }, { "name": "context_revision", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-INDEX-NOT-AUTHORITY-005", - "selector": {"table": "context_revision"} + "selector": { + "table": "context_revision" + } }, "purpose": "Immutable canonical Revision lineage selected only by its Resource active pointer", "organizationColumn": "organization_id", @@ -923,24 +1416,38 @@ { "name": "pk_context_revision", "kind": "primary_key", - "columns": ["organization_id", "resource_ref", "revision_id"] + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ] } ], "foreignKeys": [ { "name": "fk_context_revision_organization", - "columns": ["organization_id"], + "columns": [ + "organization_id" + ], "references": { "table": "organization", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] } }, { "name": "fk_context_revision_resource_same_organization", - "columns": ["organization_id", "resource_ref"], + "columns": [ + "organization_id", + "resource_ref" + ], "references": { "table": "context_resource", - "columns": ["organization_id", "resource_ref"] + "columns": [ + "organization_id", + "resource_ref" + ] } } ], @@ -951,20 +1458,26 @@ { "name": "context_revision_current_user_actor", "command": "SELECT", - "roles": ["context_engine_runtime"], + "roles": [ + "context_engine_runtime" + ], "using": "context_revision.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND EXISTS (SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = context_revision.organization_id AND actor_membership.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'user' AND actor_membership.user_id = NULLIF(current_setting('app.user_id', true), '')::uuid AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL AND actor_membership.membership_id = NULLIF(current_setting('app.membership_id', true), '')::uuid AND actor_membership.membership_version = NULLIF(current_setting('app.membership_version', true), '')::bigint AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL AND NULLIF(current_setting('app.authentication_binding_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL AND actor_membership.status = 'active' AND actor_membership.valid_from <= NULLIF(current_setting('app.checked_at', true), '')::timestamptz AND (actor_membership.valid_until IS NULL OR actor_membership.valid_until > NULLIF(current_setting('app.checked_at', true), '')::timestamptz)) AND EXISTS (SELECT 1 FROM public.context_resource AS active_resource WHERE active_resource.organization_id = context_revision.organization_id AND active_resource.resource_ref = context_revision.resource_ref AND active_resource.active_revision_id = context_revision.revision_id AND active_resource.tombstoned IS FALSE)" }, { "name": "context_revision_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" }, { "name": "context_revision_file_import_definer_insert", "command": "INSERT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" } ] @@ -972,14 +1485,27 @@ "immutableRows": { "trigger": "context_revision_reject_mutation", "function": "context_content_reject_mutation", - "events": ["UPDATE", "DELETE"], + "events": [ + "UPDATE", + "DELETE" + ], "sqlstate": "55000" }, - "functionOnlyMutation": {"databaseFunction": "context_worker_prepare_file_publication", "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, + "functionOnlyMutation": { + "databaseFunction": "context_worker_prepare_file_publication", + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, "permittedOperations": { - "context_engine_runtime": ["SELECT"], - "context_engine_worker": ["EXECUTE context_worker_prepare_file_publication"], - "context_engine_worker_lease_definer": ["INSERT"] + "context_engine_runtime": [ + "SELECT" + ], + "context_engine_worker": [ + "EXECUTE context_worker_prepare_file_publication" + ], + "context_engine_worker_lease_definer": [ + "INSERT" + ] }, "partitions": [], "securityInvariantIds": [ @@ -987,14 +1513,22 @@ "TENANT-FK-002", "RLS-FAIL-CLOSED-003" ], - "negativeTestIds": ["DB-001", "DB-002", "DB-004", "DB-009", "DB-010"] + "negativeTestIds": [ + "DB-001", + "DB-002", + "DB-004", + "DB-009", + "DB-010" + ] }, { "name": "organization_policy_epoch", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-REVOCATION-006", - "selector": {"table": "organization_policy_epoch"} + "selector": { + "table": "organization_policy_epoch" + } }, "purpose": "Organization-owned monotonic freshness authority for Acquire decisions", "organizationColumn": "organization_id", @@ -1002,16 +1536,22 @@ { "name": "pk_organization_policy_epoch", "kind": "primary_key", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] } ], "foreignKeys": [ { "name": "fk_organization_policy_epoch_organization", - "columns": ["organization_id"], + "columns": [ + "organization_id" + ], "references": { "table": "organization", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] }, "onDelete": "CASCADE" } @@ -1029,49 +1569,74 @@ { "name": "organization_policy_epoch_current_user_actor", "command": "SELECT", - "roles": ["context_engine_runtime"], + "roles": [ + "context_engine_runtime" + ], "using": "organization_policy_epoch.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND EXISTS (SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = organization_policy_epoch.organization_id AND actor_membership.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'user' AND actor_membership.user_id = NULLIF(current_setting('app.user_id', true), '')::uuid AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL AND actor_membership.membership_id = NULLIF(current_setting('app.membership_id', true), '')::uuid AND actor_membership.membership_version = NULLIF(current_setting('app.membership_version', true), '')::bigint AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL AND NULLIF(current_setting('app.authentication_binding_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL AND actor_membership.status = 'active' AND actor_membership.valid_from <= NULLIF(current_setting('app.checked_at', true), '')::timestamptz AND (actor_membership.valid_until IS NULL OR actor_membership.valid_until > NULLIF(current_setting('app.checked_at', true), '')::timestamptz))" }, { "name": "organization_policy_epoch_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" }, { "name": "organization_policy_epoch_access_policy_definer_select", "command": "SELECT", - "roles": ["context_engine_access_policy_definer"], + "roles": [ + "context_engine_access_policy_definer" + ], "using": "organization_policy_epoch.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "organization_policy_epoch_access_policy_definer_update", "command": "UPDATE", - "roles": ["context_engine_access_policy_definer"], + "roles": [ + "context_engine_access_policy_definer" + ], "using": "organization_policy_epoch.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", "withCheck": "organization_policy_epoch.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "organization_policy_epoch_delivery_evidence_definer_select", "command": "SELECT", - "roles": ["context_engine_delivery_evidence_definer"], + "roles": [ + "context_engine_delivery_evidence_definer" + ], "using": "true" }, { "name": "organization_policy_epoch_egress_definer_select", "command": "SELECT", - "roles": ["context_engine_egress_grant_definer"], + "roles": [ + "context_engine_egress_grant_definer" + ], "using": "true" } ] }, "permittedOperations": { - "context_engine_access_policy_definer": ["SELECT", "UPDATE"], - "context_engine_control": ["EXECUTE change_resource_access", "EXECUTE context_control_tombstone_file_resource", "EXECUTE context_control_offboard_file_source"], - "context_engine_delivery_evidence_definer": ["SELECT"], - "context_engine_egress_grant_definer": ["SELECT"], - "context_engine_runtime": ["SELECT"], + "context_engine_access_policy_definer": [ + "SELECT", + "UPDATE" + ], + "context_engine_control": [ + "EXECUTE change_resource_access", + "EXECUTE context_control_tombstone_file_resource", + "EXECUTE context_control_offboard_file_source" + ], + "context_engine_delivery_evidence_definer": [ + "SELECT" + ], + "context_engine_egress_grant_definer": [ + "SELECT" + ], + "context_engine_runtime": [ + "SELECT" + ], "context_engine_worker": [] }, "partitions": [], @@ -1094,7 +1659,9 @@ "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-REVOCATION-006", - "selector": {"table": "resource_access_policy"} + "selector": { + "table": "resource_access_policy" + } }, "purpose": "Exact Principal-to-Resource access state changed only with its Organization epoch", "organizationColumn": "organization_id", @@ -1102,25 +1669,39 @@ { "name": "pk_resource_access_policy", "kind": "primary_key", - "columns": ["organization_id", "resource_ref", "principal_ref"] + "columns": [ + "organization_id", + "resource_ref", + "principal_ref" + ] } ], "foreignKeys": [ { "name": "fk_resource_access_policy_organization", - "columns": ["organization_id"], + "columns": [ + "organization_id" + ], "references": { "table": "organization", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] }, "onDelete": "CASCADE" }, { "name": "fk_resource_access_policy_resource_same_organization", - "columns": ["organization_id", "resource_ref"], + "columns": [ + "organization_id", + "resource_ref" + ], "references": { "table": "context_resource", - "columns": ["organization_id", "resource_ref"] + "columns": [ + "organization_id", + "resource_ref" + ] }, "onDelete": "CASCADE" } @@ -1154,50 +1735,78 @@ { "name": "resource_access_policy_current_user_actor", "command": "SELECT", - "roles": ["context_engine_runtime"], + "roles": [ + "context_engine_runtime" + ], "using": "resource_access_policy.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND EXISTS (SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = resource_access_policy.organization_id AND actor_membership.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'user' AND actor_membership.user_id = NULLIF(current_setting('app.user_id', true), '')::uuid AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL AND actor_membership.membership_id = NULLIF(current_setting('app.membership_id', true), '')::uuid AND actor_membership.membership_version = NULLIF(current_setting('app.membership_version', true), '')::bigint AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL AND NULLIF(current_setting('app.authentication_binding_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL AND actor_membership.status = 'active' AND actor_membership.valid_from <= NULLIF(current_setting('app.checked_at', true), '')::timestamptz AND (actor_membership.valid_until IS NULL OR actor_membership.valid_until > NULLIF(current_setting('app.checked_at', true), '')::timestamptz)) AND resource_access_policy.principal_ref = current_setting('app.principal_ref', true) AND resource_access_policy.access_state = 'allowed'" }, { "name": "resource_access_policy_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" }, { "name": "resource_access_policy_access_policy_definer_select", "command": "SELECT", - "roles": ["context_engine_access_policy_definer"], + "roles": [ + "context_engine_access_policy_definer" + ], "using": "resource_access_policy.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "resource_access_policy_access_policy_definer_update", "command": "UPDATE", - "roles": ["context_engine_access_policy_definer"], + "roles": [ + "context_engine_access_policy_definer" + ], "using": "resource_access_policy.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", "withCheck": "resource_access_policy.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "resource_access_policy_file_import_definer_insert", "command": "INSERT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "resource_access_policy_file_noop_definer_select", "command": "SELECT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" } ] }, - "functionOnlyMutation": {"databaseFunction": "context_worker_prepare_file_publication", "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, + "functionOnlyMutation": { + "databaseFunction": "context_worker_prepare_file_publication", + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, "permittedOperations": { - "context_engine_access_policy_definer": ["SELECT", "UPDATE"], - "context_engine_control": ["EXECUTE change_resource_access"], - "context_engine_runtime": ["SELECT"], - "context_engine_worker": ["EXECUTE context_worker_prepare_file_publication"], - "context_engine_worker_lease_definer": ["SELECT", "INSERT"] + "context_engine_access_policy_definer": [ + "SELECT", + "UPDATE" + ], + "context_engine_control": [ + "EXECUTE change_resource_access" + ], + "context_engine_runtime": [ + "SELECT" + ], + "context_engine_worker": [ + "EXECUTE context_worker_prepare_file_publication" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT" + ] }, "partitions": [], "securityInvariantIds": [ @@ -1220,7 +1829,9 @@ "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-TRACE-REDACTION-012", - "selector": {"table": "context_run"} + "selector": { + "table": "context_run" + } }, "purpose": "Authorized-only durable lineage for one finalized ContextPackage delivery; package and query bodies are never retained", "organizationColumn": "organization_id", @@ -1228,34 +1839,54 @@ { "name": "pk_context_run", "kind": "primary_key", - "columns": ["organization_id", "run_ref"] + "columns": [ + "organization_id", + "run_ref" + ] }, { "name": "uq_context_run_decision_ref", "kind": "unique", - "columns": ["organization_id", "decision_ref"] + "columns": [ + "organization_id", + "decision_ref" + ] }, { "name": "uq_context_run_lineage", "kind": "unique", - "columns": ["organization_id", "run_ref", "decision_ref"] + "columns": [ + "organization_id", + "run_ref", + "decision_ref" + ] } ], "foreignKeys": [ { "name": "fk_context_run_organization", - "columns": ["organization_id"], + "columns": [ + "organization_id" + ], "references": { "table": "organization", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] } }, { "name": "fk_context_run_membership_same_organization", - "columns": ["organization_id", "membership_id"], + "columns": [ + "organization_id", + "membership_id" + ], "references": { "table": "membership", - "columns": ["organization_id", "membership_id"] + "columns": [ + "organization_id", + "membership_id" + ] } } ], @@ -1294,7 +1925,7 @@ }, { "name": "ck_context_run_package_digest_profile", - "expression": "package_digest_profile IN ('context-package-canonical-json-v1', 'context-package-canonical-json-v2')" + "expression": "package_digest_profile IN ('context-package-canonical-json-v1', 'context-package-canonical-json-v2', 'context-package-canonical-json-v3')" }, { "name": "ck_context_run_package_digest_sha256", @@ -1336,30 +1967,45 @@ { "name": "context_run_current_user_actor_insert", "command": "INSERT", - "roles": ["context_engine_runtime"], + "roles": [ + "context_engine_runtime" + ], "withCheck": "context_run.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'user' AND context_run.user_id = NULLIF(current_setting('app.user_id', true), '')::uuid AND context_run.membership_id = NULLIF(current_setting('app.membership_id', true), '')::uuid AND context_run.membership_version = NULLIF(current_setting('app.membership_version', true), '')::bigint AND context_run.principal_ref = current_setting('app.principal_ref', true) AND context_run.request_id = current_setting('app.request_id', true) AND context_run.authentication_binding_ref = current_setting('app.authentication_binding_ref', true) AND context_run.accepted_at = NULLIF(current_setting('app.checked_at', true), '')::timestamptz AND EXISTS (SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = context_run.organization_id AND actor_membership.user_id = context_run.user_id AND actor_membership.membership_id = context_run.membership_id AND actor_membership.membership_version = context_run.membership_version AND actor_membership.status = 'active' AND actor_membership.valid_from <= context_run.accepted_at AND (actor_membership.valid_until IS NULL OR actor_membership.valid_until > context_run.accepted_at))" }, { "name": "context_run_context_run_reader_definer_read", "command": "SELECT", - "roles": ["context_engine_context_run_reader_definer"], + "roles": [ + "context_engine_context_run_reader_definer" + ], "using": "context_run.organization_id = NULLIF(current_setting('app.context_run_operator_ticket_organization_id', true), '')::uuid AND context_run.decision_ref = current_setting('app.context_run_operator_ticket_decision_ref', true) AND current_setting('app.context_run_operator_ticket_mode', true) IN ('issue', 'read')" }, { "name": "context_run_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" } ] }, "permittedOperations": { - "context_engine_runtime": ["INSERT"], - "context_engine_security_operator": ["EXECUTE read_context_run_by_operator_ticket"], - "context_engine_context_run_reader_definer": ["SELECT"], + "context_engine_runtime": [ + "INSERT" + ], + "context_engine_security_operator": [ + "EXECUTE read_context_run_by_operator_ticket" + ], + "context_engine_context_run_reader_definer": [ + "SELECT" + ], "context_engine_worker": [], - "context_engine_control": ["EXECUTE issue_context_run_operator_read_ticket", "EXECUTE revoke_context_run_operator_read_ticket"] + "context_engine_control": [ + "EXECUTE issue_context_run_operator_read_ticket", + "EXECUTE revoke_context_run_operator_read_ticket" + ] }, "partitions": [], "securityInvariantIds": [ @@ -1387,7 +2033,9 @@ "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-TRACE-REDACTION-012", - "selector": {"table": "context_run_operator_read_ticket"} + "selector": { + "table": "context_run_operator_read_ticket" + } }, "purpose": "Digest-only 60-second exact-read capability for one Organization and ContextRun decision; plaintext ticket material is never retained", "organizationColumn": "organization_id", @@ -1395,24 +2043,35 @@ { "name": "pk_context_run_operator_read_ticket", "kind": "primary_key", - "columns": ["organization_id", "ticket_digest"] + "columns": [ + "organization_id", + "ticket_digest" + ] } ], "capabilityUniqueKeys": [ { "name": "uq_context_run_operator_read_ticket_digest", "kind": "unique", - "columns": ["ticket_digest"], + "columns": [ + "ticket_digest" + ], "rationale": "A raw ticket can identify at most one Organization-bound capability; replay cannot revoke or consume a second tenant's row" } ], "foreignKeys": [ { "name": "fk_context_run_operator_ticket_exact_decision", - "columns": ["organization_id", "decision_ref"], + "columns": [ + "organization_id", + "decision_ref" + ], "references": { "table": "context_run", - "columns": ["organization_id", "decision_ref"] + "columns": [ + "organization_id", + "decision_ref" + ] }, "onDelete": "CASCADE" } @@ -1438,25 +2097,33 @@ { "name": "context_run_operator_read_ticket_context_run_reader_definer_ins", "command": "INSERT", - "roles": ["context_engine_context_run_reader_definer"], + "roles": [ + "context_engine_context_run_reader_definer" + ], "withCheck": "current_setting('app.context_run_operator_ticket_mode', true) = 'issue' AND context_run_operator_read_ticket.organization_id = NULLIF(current_setting('app.context_run_operator_ticket_organization_id', true), '')::uuid AND context_run_operator_read_ticket.decision_ref = current_setting('app.context_run_operator_ticket_decision_ref', true) AND context_run_operator_read_ticket.ticket_digest = pg_catalog.decode(NULLIF(current_setting('app.context_run_operator_ticket_digest', true), ''), 'hex')" }, { "name": "context_run_operator_read_ticket_context_run_reader_definer_del", "command": "DELETE", - "roles": ["context_engine_context_run_reader_definer"], + "roles": [ + "context_engine_context_run_reader_definer" + ], "using": "(current_setting('app.context_run_operator_ticket_mode', true) = 'revoke' OR (current_setting('app.context_run_operator_ticket_mode', true) = 'read' AND context_run_operator_read_ticket.organization_id = NULLIF(current_setting('app.context_run_operator_ticket_organization_id', true), '')::uuid AND context_run_operator_read_ticket.decision_ref = current_setting('app.context_run_operator_ticket_decision_ref', true))) AND context_run_operator_read_ticket.ticket_digest = pg_catalog.decode(NULLIF(current_setting('app.context_run_operator_ticket_digest', true), ''), 'hex')" }, { "name": "context_run_operator_read_ticket_context_run_reader_definer_sel", "command": "SELECT", - "roles": ["context_engine_context_run_reader_definer"], + "roles": [ + "context_engine_context_run_reader_definer" + ], "using": "(current_setting('app.context_run_operator_ticket_mode', true) = 'revoke' OR (current_setting('app.context_run_operator_ticket_mode', true) = 'read' AND context_run_operator_read_ticket.organization_id = NULLIF(current_setting('app.context_run_operator_ticket_organization_id', true), '')::uuid AND context_run_operator_read_ticket.decision_ref = current_setting('app.context_run_operator_ticket_decision_ref', true))) AND context_run_operator_read_ticket.ticket_digest = pg_catalog.decode(NULLIF(current_setting('app.context_run_operator_ticket_digest', true), ''), 'hex')" }, { "name": "context_run_operator_read_ticket_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" } @@ -1471,7 +2138,10 @@ "readFunction": "read_context_run_by_operator_ticket", "functionOwner": "context_engine_context_run_reader_definer", "securityDefiner": true, - "searchPath": ["pg_catalog", "pg_temp"], + "searchPath": [ + "pg_catalog", + "pg_temp" + ], "rowSecurity": true, "issueSessionUser": "context_engine_control", "readSessionUser": "context_engine_security_operator", @@ -1479,10 +2149,19 @@ }, "permittedOperations": { "context_engine_runtime": [], - "context_engine_security_operator": ["EXECUTE read_context_run_by_operator_ticket"], - "context_engine_context_run_reader_definer": ["SELECT", "INSERT", "DELETE"], + "context_engine_security_operator": [ + "EXECUTE read_context_run_by_operator_ticket" + ], + "context_engine_context_run_reader_definer": [ + "SELECT", + "INSERT", + "DELETE" + ], "context_engine_worker": [], - "context_engine_control": ["EXECUTE issue_context_run_operator_read_ticket", "EXECUTE revoke_context_run_operator_read_ticket"] + "context_engine_control": [ + "EXECUTE issue_context_run_operator_read_ticket", + "EXECUTE revoke_context_run_operator_read_ticket" + ] }, "partitions": [], "securityInvariantIds": [ @@ -1508,7 +2187,9 @@ "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-TRACE-REDACTION-012", - "selector": {"table": "decision_audit"} + "selector": { + "table": "decision_audit" + } }, "purpose": "Restricted generic security lineage for a delivered-empty decision; never tenant-visible and structurally unable to retain denied detail", "organizationColumn": "organization_id", @@ -1516,16 +2197,27 @@ { "name": "pk_decision_audit", "kind": "primary_key", - "columns": ["organization_id", "decision_ref"] + "columns": [ + "organization_id", + "decision_ref" + ] } ], "foreignKeys": [ { "name": "fk_decision_audit_context_run_same_organization", - "columns": ["organization_id", "run_ref", "decision_ref"], + "columns": [ + "organization_id", + "run_ref", + "decision_ref" + ], "references": { "table": "context_run", - "columns": ["organization_id", "run_ref", "decision_ref"] + "columns": [ + "organization_id", + "run_ref", + "decision_ref" + ] } } ], @@ -1550,19 +2242,25 @@ { "name": "decision_audit_current_user_actor_insert", "command": "INSERT", - "roles": ["context_engine_runtime"], + "roles": [ + "context_engine_runtime" + ], "withCheck": "decision_audit.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'user' AND EXISTS (SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = decision_audit.organization_id AND actor_membership.user_id = NULLIF(current_setting('app.user_id', true), '')::uuid AND actor_membership.membership_id = NULLIF(current_setting('app.membership_id', true), '')::uuid AND actor_membership.membership_version = NULLIF(current_setting('app.membership_version', true), '')::bigint AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL AND NULLIF(current_setting('app.authentication_binding_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL AND actor_membership.status = 'active' AND actor_membership.valid_from <= NULLIF(current_setting('app.checked_at', true), '')::timestamptz AND (actor_membership.valid_until IS NULL OR actor_membership.valid_until > NULLIF(current_setting('app.checked_at', true), '')::timestamptz))" }, { "name": "decision_audit_context_run_reader_definer_read", "command": "SELECT", - "roles": ["context_engine_context_run_reader_definer"], + "roles": [ + "context_engine_context_run_reader_definer" + ], "using": "decision_audit.organization_id = NULLIF(current_setting('app.context_run_operator_ticket_organization_id', true), '')::uuid AND decision_audit.decision_ref = current_setting('app.context_run_operator_ticket_decision_ref', true) AND current_setting('app.context_run_operator_ticket_mode', true) = 'read'" }, { "name": "decision_audit_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" } @@ -1573,21 +2271,35 @@ "function": "decision_audit_require_exact_empty_parent", "timing": "BEFORE", "orientation": "ROW", - "events": ["INSERT"], + "events": [ + "INSERT" + ], "sqlstate": "42501", "securityDefiner": true, - "searchPath": ["pg_catalog", "pg_temp"], + "searchPath": [ + "pg_catalog", + "pg_temp" + ], "requiredParentOutcome": "delivered_empty", "bindsCurrentUserActor": true, "bindsParentPolicy": true, "bindsParentFinalizedAt": true }, "permittedOperations": { - "context_engine_runtime": ["INSERT"], - "context_engine_security_operator": ["EXECUTE read_context_run_by_operator_ticket"], - "context_engine_context_run_reader_definer": ["SELECT"], + "context_engine_runtime": [ + "INSERT" + ], + "context_engine_security_operator": [ + "EXECUTE read_context_run_by_operator_ticket" + ], + "context_engine_context_run_reader_definer": [ + "SELECT" + ], "context_engine_worker": [], - "context_engine_control": ["EXECUTE issue_context_run_operator_read_ticket", "EXECUTE revoke_context_run_operator_read_ticket"] + "context_engine_control": [ + "EXECUTE issue_context_run_operator_read_ticket", + "EXECUTE revoke_context_run_operator_read_ticket" + ] }, "partitions": [], "securityInvariantIds": [ @@ -1615,98 +2327,288 @@ "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-EGRESS-011", - "selector": {"table": "egress_grant"} + "selector": { + "table": "egress_grant" + } }, "purpose": "Digest-only exact one-hop grant state with atomic replay prevention", "organizationColumn": "organization_id", "organizationInclusiveKeys": [ - {"name": "pk_egress_grant", "kind": "primary_key", "columns": ["organization_id", "grant_digest"]} + { + "name": "pk_egress_grant", + "kind": "primary_key", + "columns": [ + "organization_id", + "grant_digest" + ] + } ], "capabilityUniqueKeys": [ - {"name": "uq_egress_grant_digest_global", "kind": "unique", "columns": ["grant_digest"], "rationale": "one opaque locator digest identifies at most one Organization-bound hop"} + { + "name": "uq_egress_grant_digest_global", + "kind": "unique", + "columns": [ + "grant_digest" + ], + "rationale": "one opaque locator digest identifies at most one Organization-bound hop" + } ], "foreignKeys": [ - {"name": "fk_egress_grant_organization", "columns": ["organization_id"], "references": {"table": "organization", "columns": ["organization_id"]}, "onDelete": "CASCADE"} + { + "name": "fk_egress_grant_organization", + "columns": [ + "organization_id" + ], + "references": { + "table": "organization", + "columns": [ + "organization_id" + ] + }, + "onDelete": "CASCADE" + } ], "checkConstraints": [ - {"name": "ck_egress_grant_sha256_digests", "expression": "grant, Package, payload, and audience digests are 32-byte SHA-256"}, - {"name": "ck_egress_grant_profiles", "expression": "locator and grant profile lineage are exact active versions"}, - {"name": "ck_egress_grant_positive_epoch", "expression": "policy_epoch > 0"}, - {"name": "ck_egress_grant_timestamp_order", "expression": "issued_at < expires_at and consumption, when present, is inside the grant lifetime"}, - {"name": "ck_egress_grant_exact_hop_variant", "expression": "exactly one model or channel hop variant is populated"}, - {"name": "ck_egress_grant_bindings_nonblank", "expression": "all common egress bindings are nonblank"} + { + "name": "ck_egress_grant_sha256_digests", + "expression": "grant, Package, payload, and audience digests are 32-byte SHA-256" + }, + { + "name": "ck_egress_grant_profiles", + "expression": "locator and grant profile lineage are exact active versions" + }, + { + "name": "ck_egress_grant_positive_epoch", + "expression": "policy_epoch > 0" + }, + { + "name": "ck_egress_grant_timestamp_order", + "expression": "issued_at < expires_at and consumption, when present, is inside the grant lifetime" + }, + { + "name": "ck_egress_grant_exact_hop_variant", + "expression": "exactly one model or channel hop variant is populated" + }, + { + "name": "ck_egress_grant_bindings_nonblank", + "expression": "all common egress bindings are nonblank" + } ], "rowLevelSecurity": { "enabled": true, "forced": true, "policies": [ - {"name": "egress_grant_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "egress_grant_definer_all", "command": "ALL", "roles": ["context_engine_egress_grant_definer"], "using": "true", "withCheck": "true"} + { + "name": "egress_grant_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "egress_grant_definer_all", + "command": "ALL", + "roles": [ + "context_engine_egress_grant_definer" + ], + "using": "true", + "withCheck": "true" + } ] }, - "functionOnlyMutation": {"databaseFunctions": ["context_runtime_issue_egress_grant", "context_egress_redeem_grant"], "definerRole": "context_engine_egress_grant_definer", "directTableMutationAllowed": false}, - "retention": {"class": "short_lived_digest_only", "bearerStored": false, "payloadStored": false, "expirySource": "versioned egress profile"}, + "functionOnlyMutation": { + "databaseFunctions": [ + "context_runtime_issue_egress_grant", + "context_egress_redeem_grant" + ], + "definerRole": "context_engine_egress_grant_definer", + "directTableMutationAllowed": false + }, + "retention": { + "class": "short_lived_digest_only", + "bearerStored": false, + "payloadStored": false, + "expirySource": "versioned egress profile" + }, "permittedOperations": { - "context_engine_runtime": ["EXECUTE context_runtime_issue_egress_grant"], - "context_engine_egress": ["EXECUTE context_egress_redeem_grant"], - "context_engine_egress_grant_definer": ["SELECT", "INSERT", "UPDATE", "DELETE"], + "context_engine_runtime": [ + "EXECUTE context_runtime_issue_egress_grant" + ], + "context_engine_egress": [ + "EXECUTE context_egress_redeem_grant" + ], + "context_engine_egress_grant_definer": [ + "SELECT", + "INSERT", + "UPDATE", + "DELETE" + ], "context_engine_control": [], "context_engine_worker": [], "context_engine_learning": [], "context_engine_security_operator": [] }, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "REVOCATION-006", "EGRESS-011", "NON-ENUMERATION-009", "TRACE-REDACTION-012", "ACTION-SEPARATION-014"], - "negativeTestIds": ["EGR-001", "EGR-004", "RUN-013", "DB-001", "DB-002", "DB-004", "DB-008", "DB-009", "DB-010", "OBS-004", "OBS-005"] - }, - { - "name": "egress_audit", - "classification": "tenant_owned", - "nonOwnerEvidence": { - "evidenceId": "PG-EGRESS-011", - "selector": {"table": "egress_audit"} - }, - "purpose": "Restricted digest-only issued, consumed, or not-available egress decisions", - "organizationColumn": "organization_id", + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "REVOCATION-006", + "EGRESS-011", + "NON-ENUMERATION-009", + "TRACE-REDACTION-012", + "ACTION-SEPARATION-014" + ], + "negativeTestIds": [ + "EGR-001", + "EGR-004", + "RUN-013", + "DB-001", + "DB-002", + "DB-004", + "DB-008", + "DB-009", + "DB-010", + "OBS-004", + "OBS-005" + ] + }, + { + "name": "egress_audit", + "classification": "tenant_owned", + "nonOwnerEvidence": { + "evidenceId": "PG-EGRESS-011", + "selector": { + "table": "egress_audit" + } + }, + "purpose": "Restricted digest-only issued, consumed, or not-available egress decisions", + "organizationColumn": "organization_id", "organizationInclusiveKeys": [ - {"name": "pk_egress_audit", "kind": "primary_key", "columns": ["organization_id", "audit_id"]} + { + "name": "pk_egress_audit", + "kind": "primary_key", + "columns": [ + "organization_id", + "audit_id" + ] + } ], "foreignKeys": [ - {"name": "fk_egress_audit_exact_grant", "columns": ["organization_id", "grant_digest"], "references": {"table": "egress_grant", "columns": ["organization_id", "grant_digest"]}, "onDelete": "CASCADE"} + { + "name": "fk_egress_audit_exact_grant", + "columns": [ + "organization_id", + "grant_digest" + ], + "references": { + "table": "egress_grant", + "columns": [ + "organization_id", + "grant_digest" + ] + }, + "onDelete": "CASCADE" + } ], "checkConstraints": [ - {"name": "ck_egress_audit_sha256_digests", "expression": "grant and payload digests are 32-byte SHA-256"}, - {"name": "ck_egress_audit_restricted_category", "expression": "category is issued, consumed, or not_available"} + { + "name": "ck_egress_audit_sha256_digests", + "expression": "grant and payload digests are 32-byte SHA-256" + }, + { + "name": "ck_egress_audit_restricted_category", + "expression": "category is issued, consumed, or not_available" + } ], "rowLevelSecurity": { "enabled": true, "forced": true, "policies": [ - {"name": "egress_audit_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "egress_audit_definer_all", "command": "ALL", "roles": ["context_engine_egress_grant_definer"], "using": "true", "withCheck": "true"} + { + "name": "egress_audit_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "egress_audit_definer_all", + "command": "ALL", + "roles": [ + "context_engine_egress_grant_definer" + ], + "using": "true", + "withCheck": "true" + } ] }, - "functionOnlyMutation": {"databaseFunctions": ["context_runtime_issue_egress_grant", "context_egress_redeem_grant"], "definerRole": "context_engine_egress_grant_definer", "directTableMutationAllowed": false}, - "retention": {"class": "restricted_digest_audit", "bearerStored": false, "payloadStored": false, "deniedContentStored": false}, + "functionOnlyMutation": { + "databaseFunctions": [ + "context_runtime_issue_egress_grant", + "context_egress_redeem_grant" + ], + "definerRole": "context_engine_egress_grant_definer", + "directTableMutationAllowed": false + }, + "retention": { + "class": "restricted_digest_audit", + "bearerStored": false, + "payloadStored": false, + "deniedContentStored": false + }, "permittedOperations": { - "context_engine_runtime": ["EXECUTE context_runtime_issue_egress_grant"], - "context_engine_egress": ["EXECUTE context_egress_redeem_grant"], - "context_engine_egress_grant_definer": ["SELECT", "INSERT", "UPDATE", "DELETE"], + "context_engine_runtime": [ + "EXECUTE context_runtime_issue_egress_grant" + ], + "context_engine_egress": [ + "EXECUTE context_egress_redeem_grant" + ], + "context_engine_egress_grant_definer": [ + "SELECT", + "INSERT", + "UPDATE", + "DELETE" + ], "context_engine_control": [], "context_engine_worker": [], "context_engine_learning": [], "context_engine_security_operator": [] }, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "EGRESS-011", "NON-ENUMERATION-009", "TRACE-REDACTION-012"], - "negativeTestIds": ["EGR-001", "EGR-004", "DB-001", "DB-002", "DB-004", "DB-008", "DB-009", "DB-010", "OBS-004", "OBS-005"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "EGRESS-011", + "NON-ENUMERATION-009", + "TRACE-REDACTION-012" + ], + "negativeTestIds": [ + "EGR-001", + "EGR-004", + "DB-001", + "DB-002", + "DB-004", + "DB-008", + "DB-009", + "DB-010", + "OBS-004", + "OBS-005" + ] }, { "name": "service_principal", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-WORKER-LEASE-007", - "selector": {"table": "service_principal"} + "selector": { + "table": "service_principal" + } }, "purpose": "Bounded registered receiver principal for exact no-op and File import WorkerLease operations; not the full canonical ServiceActor", "organizationColumn": "organization_id", @@ -1714,21 +2616,34 @@ { "name": "pk_service_principal", "kind": "primary_key", - "columns": ["organization_id", "service_principal_id"] + "columns": [ + "organization_id", + "service_principal_id" + ] }, { "name": "uq_service_principal_worker_binding", "kind": "unique", - "columns": ["organization_id", "service_principal_id", "workload", "worker_audience", "operation"] + "columns": [ + "organization_id", + "service_principal_id", + "workload", + "worker_audience", + "operation" + ] } ], "foreignKeys": [ { "name": "fk_service_principal_organization", - "columns": ["organization_id"], + "columns": [ + "organization_id" + ], "references": { "table": "organization", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] }, "onDelete": "CASCADE" } @@ -1766,20 +2681,26 @@ { "name": "service_principal_worker_lease_definer_select", "command": "SELECT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "using": "service_principal.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'service' AND current_setting('app.workload', true) = 'supply.noop' AND current_setting('app.worker_audience', true) = 'context-engine-worker' AND current_setting('app.operation', true) = 'noop.complete' AND service_principal.workload = 'supply.noop' AND service_principal.worker_audience = 'context-engine-worker' AND service_principal.operation = 'noop.complete' AND service_principal.enabled IS TRUE" }, { "name": "service_principal_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" }, { "name": "service_principal_file_import_definer_select", "command": "SELECT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND workload = 'supply.file-import' AND worker_audience = 'context-engine-worker' AND operation = 'file.import' AND enabled IS TRUE" } ] @@ -1787,7 +2708,9 @@ "permittedOperations": { "context_engine_runtime": [], "context_engine_worker": [], - "context_engine_worker_lease_definer": ["SELECT"] + "context_engine_worker_lease_definer": [ + "SELECT" + ] }, "partitions": [], "securityInvariantIds": [ @@ -1813,7 +2736,9 @@ "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-WORKER-LEASE-007", - "selector": {"table": "worker_noop_job"} + "selector": { + "table": "worker_noop_job" + } }, "purpose": "Exact-job durable state and one-shot receipt for the bounded no-op WorkerLease", "organizationColumn": "organization_id", @@ -1821,25 +2746,44 @@ { "name": "pk_worker_noop_job", "kind": "primary_key", - "columns": ["organization_id", "job_id"] + "columns": [ + "organization_id", + "job_id" + ] } ], "foreignKeys": [ { "name": "fk_worker_noop_job_organization", - "columns": ["organization_id"], + "columns": [ + "organization_id" + ], "references": { "table": "organization", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] }, "onDelete": "CASCADE" }, { "name": "fk_worker_noop_job_service_principal_binding", - "columns": ["organization_id", "service_principal_id", "workload", "worker_audience", "operation"], + "columns": [ + "organization_id", + "service_principal_id", + "workload", + "worker_audience", + "operation" + ], "references": { "table": "service_principal", - "columns": ["organization_id", "service_principal_id", "workload", "worker_audience", "operation"] + "columns": [ + "organization_id", + "service_principal_id", + "workload", + "worker_audience", + "operation" + ] } } ], @@ -1892,30 +2836,43 @@ { "name": "worker_noop_job_worker_lease_definer_select", "command": "SELECT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "using": "worker_noop_job.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'service' AND current_setting('app.workload', true) = 'supply.noop' AND current_setting('app.worker_audience', true) = 'context-engine-worker' AND current_setting('app.operation', true) = 'noop.complete' AND worker_noop_job.workload = 'supply.noop' AND worker_noop_job.worker_audience = 'context-engine-worker' AND worker_noop_job.operation = 'noop.complete' AND worker_noop_job.job_id = NULLIF(current_setting('app.worker_job_id', true), '')::uuid AND EXISTS (SELECT 1 FROM public.service_principal AS active_service_principal WHERE active_service_principal.organization_id = worker_noop_job.organization_id AND active_service_principal.service_principal_id = worker_noop_job.service_principal_id AND active_service_principal.workload = worker_noop_job.workload AND active_service_principal.worker_audience = worker_noop_job.worker_audience AND active_service_principal.operation = worker_noop_job.operation AND active_service_principal.enabled IS TRUE)" }, { "name": "worker_noop_job_worker_lease_definer_update", "command": "UPDATE", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "using": "worker_noop_job.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'service' AND current_setting('app.workload', true) = 'supply.noop' AND current_setting('app.worker_audience', true) = 'context-engine-worker' AND current_setting('app.operation', true) = 'noop.complete' AND worker_noop_job.workload = 'supply.noop' AND worker_noop_job.worker_audience = 'context-engine-worker' AND worker_noop_job.operation = 'noop.complete' AND worker_noop_job.job_id = NULLIF(current_setting('app.worker_job_id', true), '')::uuid AND EXISTS (SELECT 1 FROM public.service_principal AS active_service_principal WHERE active_service_principal.organization_id = worker_noop_job.organization_id AND active_service_principal.service_principal_id = worker_noop_job.service_principal_id AND active_service_principal.workload = worker_noop_job.workload AND active_service_principal.worker_audience = worker_noop_job.worker_audience AND active_service_principal.operation = worker_noop_job.operation AND active_service_principal.enabled IS TRUE)", "withCheck": "worker_noop_job.organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'service' AND current_setting('app.workload', true) = 'supply.noop' AND current_setting('app.worker_audience', true) = 'context-engine-worker' AND current_setting('app.operation', true) = 'noop.complete' AND worker_noop_job.workload = 'supply.noop' AND worker_noop_job.worker_audience = 'context-engine-worker' AND worker_noop_job.operation = 'noop.complete' AND worker_noop_job.job_id = NULLIF(current_setting('app.worker_job_id', true), '')::uuid AND EXISTS (SELECT 1 FROM public.service_principal AS active_service_principal WHERE active_service_principal.organization_id = worker_noop_job.organization_id AND active_service_principal.service_principal_id = worker_noop_job.service_principal_id AND active_service_principal.workload = worker_noop_job.workload AND active_service_principal.worker_audience = worker_noop_job.worker_audience AND active_service_principal.operation = worker_noop_job.operation AND active_service_principal.enabled IS TRUE)" }, { "name": "worker_noop_job_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" } ] }, "permittedOperations": { - "context_engine_control": ["EXECUTE issue_noop_worker_lease"], + "context_engine_control": [ + "EXECUTE issue_noop_worker_lease" + ], "context_engine_runtime": [], - "context_engine_worker": ["EXECUTE complete_noop_worker_job"], - "context_engine_worker_lease_definer": ["SELECT", "UPDATE"] + "context_engine_worker": [ + "EXECUTE complete_noop_worker_job" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "UPDATE" + ] }, "partitions": [], "securityInvariantIds": [ @@ -1942,7 +2899,9 @@ "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-INDEX-NOT-AUTHORITY-005", - "selector": {"table": "context_fragment"} + "selector": { + "table": "context_fragment" + } }, "purpose": "Immutable active-Revision logical Markdown unit with same-Fragment heading ancestry; persistent rows are never Evidence", "organizationColumn": "organization_id", @@ -1950,29 +2909,51 @@ { "name": "pk_context_fragment", "kind": "primary_key", - "columns": ["organization_id", "resource_ref", "revision_id", "fragment_ref"] + "columns": [ + "organization_id", + "resource_ref", + "revision_id", + "fragment_ref" + ] }, { "name": "uq_context_fragment_revision_ordinal", "kind": "unique", - "columns": ["organization_id", "resource_ref", "revision_id", "ordinal"] + "columns": [ + "organization_id", + "resource_ref", + "revision_id", + "ordinal" + ] } ], "foreignKeys": [ { "name": "fk_context_fragment_organization", - "columns": ["organization_id"], + "columns": [ + "organization_id" + ], "references": { "table": "organization", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] } }, { "name": "fk_context_fragment_revision_same_organization", - "columns": ["organization_id", "resource_ref", "revision_id"], + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ], "references": { "table": "context_revision", - "columns": ["organization_id", "resource_ref", "revision_id"] + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ] } } ], @@ -2007,26 +2988,34 @@ { "name": "context_fragment_current_user_actor", "command": "SELECT", - "roles": ["context_engine_runtime"], + "roles": [ + "context_engine_runtime" + ], "using": "context_fragment.organization_id = NULLIF( current_setting('app.organization_id', true), '' )::uuid AND current_setting('app.actor_kind', true) = 'user' AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL AND NULLIF( current_setting('app.authentication_binding_ref', true), '' ) IS NOT NULL AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL AND EXISTS ( SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = context_fragment.organization_id AND actor_membership.organization_id = NULLIF( current_setting('app.organization_id', true), '' )::uuid AND actor_membership.user_id = NULLIF( current_setting('app.user_id', true), '' )::uuid AND actor_membership.membership_id = NULLIF( current_setting('app.membership_id', true), '' )::uuid AND actor_membership.membership_version = NULLIF( current_setting('app.membership_version', true), '' )::bigint AND actor_membership.status = 'active' AND actor_membership.valid_from <= NULLIF( current_setting('app.checked_at', true), '' )::timestamptz AND ( actor_membership.valid_until IS NULL OR actor_membership.valid_until > NULLIF( current_setting('app.checked_at', true), '' )::timestamptz ) ) AND EXISTS ( SELECT 1 FROM public.context_resource AS active_resource WHERE active_resource.organization_id = context_fragment.organization_id AND active_resource.resource_ref = context_fragment.resource_ref AND active_resource.active_revision_id = context_fragment.revision_id AND active_resource.tombstoned IS FALSE ) AND EXISTS ( SELECT 1 FROM public.resource_access_policy AS current_access WHERE current_access.organization_id = context_fragment.organization_id AND current_access.resource_ref = context_fragment.resource_ref AND current_access.principal_ref = current_setting( 'app.principal_ref', true ) AND current_access.access_state = 'allowed' ) AND ( context_fragment.projection_kind = 'fields' OR ( context_fragment.projection_kind = 'body' AND EXISTS ( SELECT 1 FROM public.membership_resource_field_right AS field_right WHERE field_right.organization_id = context_fragment.organization_id AND field_right.membership_id = NULLIF( current_setting('app.membership_id', true), '' )::uuid AND field_right.membership_version = NULLIF( current_setting('app.membership_version', true), '' )::bigint AND field_right.resource_ref = context_fragment.resource_ref AND field_right.field_ref = 'body' ) ) )" }, { "name": "context_fragment_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" }, { "name": "context_fragment_file_import_definer_insert", "command": "INSERT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "context_fragment_file_noop_definer_select", "command": "SELECT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" } ] @@ -2034,14 +3023,28 @@ "immutableRows": { "trigger": "context_fragment_reject_mutation", "function": "context_content_reject_mutation", - "events": ["UPDATE", "DELETE"], + "events": [ + "UPDATE", + "DELETE" + ], "sqlstate": "55000" }, - "functionOnlyMutation": {"databaseFunction": "context_worker_prepare_file_publication", "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, + "functionOnlyMutation": { + "databaseFunction": "context_worker_prepare_file_publication", + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, "permittedOperations": { - "context_engine_runtime": ["SELECT"], - "context_engine_worker": ["EXECUTE context_worker_prepare_file_publication"], - "context_engine_worker_lease_definer": ["SELECT", "INSERT"] + "context_engine_runtime": [ + "SELECT" + ], + "context_engine_worker": [ + "EXECUTE context_worker_prepare_file_publication" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT" + ] }, "partitions": [], "securityInvariantIds": [ @@ -2049,14 +3052,22 @@ "TENANT-FK-002", "RLS-FAIL-CLOSED-003" ], - "negativeTestIds": ["DB-001", "DB-002", "DB-004", "DB-009", "DB-010"] + "negativeTestIds": [ + "DB-001", + "DB-002", + "DB-004", + "DB-009", + "DB-010" + ] }, { "name": "context_fragment_field", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-FIELD-PROJECTION-RLS-048", - "selector": {"table": "context_fragment_field"} + "selector": { + "table": "context_fragment_field" + } }, "purpose": "Immutable structured Fragment fields filtered by exact current Membership Resource rights before Runtime can read values", "organizationColumn": "organization_id", @@ -2064,21 +3075,43 @@ { "name": "pk_context_fragment_field", "kind": "primary_key", - "columns": ["organization_id", "resource_ref", "revision_id", "fragment_ref", "field_ref"] + "columns": [ + "organization_id", + "resource_ref", + "revision_id", + "fragment_ref", + "field_ref" + ] }, { "name": "uq_context_fragment_field_parent_ordinal", "kind": "unique", - "columns": ["organization_id", "resource_ref", "revision_id", "fragment_ref", "ordinal"] + "columns": [ + "organization_id", + "resource_ref", + "revision_id", + "fragment_ref", + "ordinal" + ] } ], "foreignKeys": [ { "name": "fk_context_fragment_field_parent_same_organization", - "columns": ["organization_id", "resource_ref", "revision_id", "fragment_ref"], + "columns": [ + "organization_id", + "resource_ref", + "revision_id", + "fragment_ref" + ], "references": { "table": "context_fragment", - "columns": ["organization_id", "resource_ref", "revision_id", "fragment_ref"] + "columns": [ + "organization_id", + "resource_ref", + "revision_id", + "fragment_ref" + ] } } ], @@ -2109,13 +3142,17 @@ { "name": "context_fragment_field_current_user_actor", "command": "SELECT", - "roles": ["context_engine_runtime"], + "roles": [ + "context_engine_runtime" + ], "using": "context_fragment_field.organization_id = NULLIF( current_setting('app.organization_id', true), '' )::uuid AND current_setting('app.actor_kind', true) = 'user' AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL AND NULLIF( current_setting('app.authentication_binding_ref', true), '' ) IS NOT NULL AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL AND EXISTS ( SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = context_fragment_field.organization_id AND actor_membership.organization_id = NULLIF( current_setting('app.organization_id', true), '' )::uuid AND actor_membership.user_id = NULLIF( current_setting('app.user_id', true), '' )::uuid AND actor_membership.membership_id = NULLIF( current_setting('app.membership_id', true), '' )::uuid AND actor_membership.membership_version = NULLIF( current_setting('app.membership_version', true), '' )::bigint AND actor_membership.status = 'active' AND actor_membership.valid_from <= NULLIF( current_setting('app.checked_at', true), '' )::timestamptz AND ( actor_membership.valid_until IS NULL OR actor_membership.valid_until > NULLIF( current_setting('app.checked_at', true), '' )::timestamptz ) ) AND EXISTS ( SELECT 1 FROM public.context_resource AS active_resource WHERE active_resource.organization_id = context_fragment_field.organization_id AND active_resource.resource_ref = context_fragment_field.resource_ref AND active_resource.active_revision_id = context_fragment_field.revision_id AND active_resource.tombstoned IS FALSE ) AND EXISTS ( SELECT 1 FROM public.membership_resource_field_right AS field_right WHERE field_right.organization_id = context_fragment_field.organization_id AND field_right.membership_id = NULLIF( current_setting('app.membership_id', true), '' )::uuid AND field_right.membership_version = NULLIF( current_setting('app.membership_version', true), '' )::bigint AND field_right.resource_ref = context_fragment_field.resource_ref AND field_right.field_ref = context_fragment_field.field_ref ) AND EXISTS ( SELECT 1 FROM public.resource_access_policy AS current_access WHERE current_access.organization_id = context_fragment_field.organization_id AND current_access.resource_ref = context_fragment_field.resource_ref AND current_access.principal_ref = current_setting( 'app.principal_ref', true ) AND current_access.access_state = 'allowed' )" }, { "name": "context_fragment_field_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" } @@ -2124,23 +3161,44 @@ "immutableRows": { "trigger": "context_fragment_field_reject_mutation", "function": "context_content_reject_mutation", - "events": ["UPDATE", "DELETE"], + "events": [ + "UPDATE", + "DELETE" + ], "sqlstate": "55000" }, "permittedOperations": { - "context_engine_runtime": ["SELECT"], + "context_engine_runtime": [ + "SELECT" + ], "context_engine_worker": [] }, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "SCOPE-INTERSECTION-004", "INDEX-NOT-AUTHORITY-005"], - "negativeTestIds": ["DB-001", "DB-002", "DB-004", "DB-009", "DB-010", "PG-SCOPE-INTERSECTION-004", "PG-INDEX-NOT-AUTHORITY-005"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "SCOPE-INTERSECTION-004", + "INDEX-NOT-AUTHORITY-005" + ], + "negativeTestIds": [ + "DB-001", + "DB-002", + "DB-004", + "DB-009", + "DB-010", + "PG-SCOPE-INTERSECTION-004", + "PG-INDEX-NOT-AUTHORITY-005" + ] }, { "name": "membership_resource_field_right", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-FIELD-PROJECTION-RLS-048", - "selector": {"table": "membership_resource_field_right"} + "selector": { + "table": "membership_resource_field_right" + } }, "purpose": "Closed allowlist binding one exact Membership version to readable fields of one same-Organization Resource; absence denies", "organizationColumn": "organization_id", @@ -2148,24 +3206,44 @@ { "name": "pk_membership_resource_field_right", "kind": "primary_key", - "columns": ["organization_id", "membership_id", "membership_version", "resource_ref", "field_ref"] + "columns": [ + "organization_id", + "membership_id", + "membership_version", + "resource_ref", + "field_ref" + ] } ], "foreignKeys": [ { "name": "fk_membership_field_right_membership_version", - "columns": ["organization_id", "membership_id", "membership_version"], + "columns": [ + "organization_id", + "membership_id", + "membership_version" + ], "references": { "table": "membership", - "columns": ["organization_id", "membership_id", "membership_version"] + "columns": [ + "organization_id", + "membership_id", + "membership_version" + ] } }, { "name": "fk_membership_field_right_resource_same_organization", - "columns": ["organization_id", "resource_ref"], + "columns": [ + "organization_id", + "resource_ref" + ], "references": { "table": "context_resource", - "columns": ["organization_id", "resource_ref"] + "columns": [ + "organization_id", + "resource_ref" + ] } } ], @@ -2193,46 +3271,81 @@ { "name": "membership_resource_field_right_current_user_actor", "command": "SELECT", - "roles": ["context_engine_runtime"], + "roles": [ + "context_engine_runtime" + ], "using": "membership_resource_field_right.organization_id = NULLIF( current_setting('app.organization_id', true), '' )::uuid AND current_setting('app.actor_kind', true) = 'user' AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL AND NULLIF( current_setting('app.authentication_binding_ref', true), '' ) IS NOT NULL AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL AND EXISTS ( SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = membership_resource_field_right.organization_id AND actor_membership.organization_id = NULLIF( current_setting('app.organization_id', true), '' )::uuid AND actor_membership.user_id = NULLIF( current_setting('app.user_id', true), '' )::uuid AND actor_membership.membership_id = NULLIF( current_setting('app.membership_id', true), '' )::uuid AND actor_membership.membership_version = NULLIF( current_setting('app.membership_version', true), '' )::bigint AND actor_membership.status = 'active' AND actor_membership.valid_from <= NULLIF( current_setting('app.checked_at', true), '' )::timestamptz AND ( actor_membership.valid_until IS NULL OR actor_membership.valid_until > NULLIF( current_setting('app.checked_at', true), '' )::timestamptz ) ) AND membership_resource_field_right.membership_id = NULLIF( current_setting('app.membership_id', true), '' )::uuid AND membership_resource_field_right.membership_version = NULLIF( current_setting('app.membership_version', true), '' )::bigint AND EXISTS ( SELECT 1 FROM public.context_resource AS live_resource WHERE live_resource.organization_id = membership_resource_field_right.organization_id AND live_resource.resource_ref = membership_resource_field_right.resource_ref AND live_resource.tombstoned IS FALSE ) AND EXISTS ( SELECT 1 FROM public.resource_access_policy AS current_access WHERE current_access.organization_id = membership_resource_field_right.organization_id AND current_access.resource_ref = membership_resource_field_right.resource_ref AND current_access.principal_ref = current_setting( 'app.principal_ref', true ) AND current_access.access_state = 'allowed' )" }, { "name": "membership_resource_field_right_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" }, { "name": "membership_resource_field_right_file_import_definer_insert", "command": "INSERT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "membership_resource_field_right_file_noop_definer_select", "command": "SELECT", - "roles": ["context_engine_worker_lease_definer"], + "roles": [ + "context_engine_worker_lease_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" } ] }, - "functionOnlyMutation": {"databaseFunction": "context_worker_prepare_file_publication", "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, + "functionOnlyMutation": { + "databaseFunction": "context_worker_prepare_file_publication", + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, "permittedOperations": { - "context_engine_runtime": ["SELECT"], - "context_engine_worker": ["EXECUTE context_worker_prepare_file_publication"], - "context_engine_worker_lease_definer": ["SELECT", "INSERT"] + "context_engine_runtime": [ + "SELECT" + ], + "context_engine_worker": [ + "EXECUTE context_worker_prepare_file_publication" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT" + ] }, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "SCOPE-INTERSECTION-004", "INDEX-NOT-AUTHORITY-005"], - "negativeTestIds": ["DB-001", "DB-002", "DB-004", "DB-009", "DB-010", "PG-SCOPE-INTERSECTION-004", "PG-INDEX-NOT-AUTHORITY-005"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "SCOPE-INTERSECTION-004", + "INDEX-NOT-AUTHORITY-005" + ], + "negativeTestIds": [ + "DB-001", + "DB-002", + "DB-004", + "DB-009", + "DB-010", + "PG-SCOPE-INTERSECTION-004", + "PG-INDEX-NOT-AUTHORITY-005" + ] }, { "name": "release_manifest", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-RELEASE-OWNER-019", - "selector": {"table": "release_manifest"} + "selector": { + "table": "release_manifest" + } }, "purpose": "Immutable Organization-owned release profile composition and curation compatibility lineage", "organizationColumn": "organization_id", @@ -2240,21 +3353,32 @@ { "name": "pk_release_manifest", "kind": "primary_key", - "columns": ["organization_id", "manifest_ref"] + "columns": [ + "organization_id", + "manifest_ref" + ] }, { "name": "uq_release_manifest_exact_digest", "kind": "unique", - "columns": ["organization_id", "manifest_ref", "manifest_digest"] + "columns": [ + "organization_id", + "manifest_ref", + "manifest_digest" + ] } ], "foreignKeys": [ { "name": "fk_release_manifest_organization", - "columns": ["organization_id"], + "columns": [ + "organization_id" + ], "references": { "table": "organization", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] }, "onDelete": "CASCADE" } @@ -2288,26 +3412,42 @@ { "name": "release_manifest_learning_insert", "command": "INSERT", - "roles": ["context_engine_learning"], + "roles": [ + "context_engine_learning" + ], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "release_manifest_learning_select", "command": "SELECT", - "roles": ["context_engine_learning"], + "roles": [ + "context_engine_learning" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, + { + "name": "release_manifest_runtime_select", + "command": "SELECT", + "roles": [ + "context_engine_runtime" + ], + "using": "release_manifest.organization_id = NULLIF(\n current_setting('app.organization_id', true), ''\n)::uuid\nAND current_setting('app.actor_kind', true) = 'user'\nAND EXISTS (\n SELECT 1\n FROM public.membership AS actor_membership\n WHERE actor_membership.organization_id = release_manifest.organization_id\n AND actor_membership.user_id = NULLIF(\n current_setting('app.user_id', true), ''\n )::uuid\n AND actor_membership.membership_id = NULLIF(\n current_setting('app.membership_id', true), ''\n )::uuid\n AND actor_membership.membership_version = NULLIF(\n current_setting('app.membership_version', true), ''\n )::bigint\n AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL\n AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL\n AND NULLIF(\n current_setting('app.authentication_binding_ref', true), ''\n ) IS NOT NULL\n AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL\n AND actor_membership.status = 'active'\n AND actor_membership.valid_from <= NULLIF(\n current_setting('app.checked_at', true), ''\n )::timestamptz\n AND (\n actor_membership.valid_until IS NULL\n OR actor_membership.valid_until > NULLIF(\n current_setting('app.checked_at', true), ''\n )::timestamptz\n )\n)" + }, { "name": "release_manifest_release_definer", "command": "ALL", - "roles": ["context_engine_release_definer"], + "roles": [ + "context_engine_release_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "release_manifest_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" } @@ -2316,27 +3456,55 @@ "immutableRows": { "trigger": "release_manifest_reject_mutation", "function": "release_lineage_reject_mutation", - "events": ["UPDATE", "DELETE"], + "events": [ + "UPDATE", + "DELETE" + ], "sqlstate": "55000" }, "permittedOperations": { "context_engine_control": [], - "context_engine_learning": ["SELECT", "INSERT"], - "context_engine_release_definer": ["SELECT"], - "context_engine_runtime": [], + "context_engine_learning": [ + "SELECT", + "INSERT" + ], + "context_engine_release_definer": [ + "SELECT" + ], + "context_engine_runtime": [ + "SELECT" + ], "context_engine_security_operator": [], "context_engine_worker": [] }, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "RELEASE-OWNER-019"], - "negativeTestIds": ["DB-001", "DB-003", "DB-004", "DB-005", "DB-008", "LEARN-004", "LEARN-006", "LEARN-007", "LEARN-008", "LEARN-009"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "RELEASE-OWNER-019" + ], + "negativeTestIds": [ + "DB-001", + "DB-003", + "DB-004", + "DB-005", + "DB-008", + "LEARN-004", + "LEARN-006", + "LEARN-007", + "LEARN-008", + "LEARN-009" + ] }, { "name": "release_candidate", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-RELEASE-OWNER-019", - "selector": {"table": "release_candidate"} + "selector": { + "table": "release_candidate" + } }, "purpose": "Immutable Organization-owned candidate binding an exact manifest and generation-bound expected active state", "organizationColumn": "organization_id", @@ -2344,21 +3512,36 @@ { "name": "pk_release_candidate", "kind": "primary_key", - "columns": ["organization_id", "candidate_ref"] + "columns": [ + "organization_id", + "candidate_ref" + ] }, { "name": "uq_release_candidate_exact_digest", "kind": "unique", - "columns": ["organization_id", "candidate_ref", "candidate_digest"] + "columns": [ + "organization_id", + "candidate_ref", + "candidate_digest" + ] } ], "foreignKeys": [ { "name": "fk_release_candidate_manifest_exact", - "columns": ["organization_id", "manifest_ref", "manifest_digest"], + "columns": [ + "organization_id", + "manifest_ref", + "manifest_digest" + ], "references": { "table": "release_manifest", - "columns": ["organization_id", "manifest_ref", "manifest_digest"] + "columns": [ + "organization_id", + "manifest_ref", + "manifest_digest" + ] } } ], @@ -2395,26 +3578,34 @@ { "name": "release_candidate_learning_insert", "command": "INSERT", - "roles": ["context_engine_learning"], + "roles": [ + "context_engine_learning" + ], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "release_candidate_learning_select", "command": "SELECT", - "roles": ["context_engine_learning"], + "roles": [ + "context_engine_learning" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "release_candidate_release_definer", "command": "ALL", - "roles": ["context_engine_release_definer"], + "roles": [ + "context_engine_release_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "release_candidate_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" } @@ -2423,27 +3614,53 @@ "immutableRows": { "trigger": "release_candidate_reject_mutation", "function": "release_lineage_reject_mutation", - "events": ["UPDATE", "DELETE"], + "events": [ + "UPDATE", + "DELETE" + ], "sqlstate": "55000" }, "permittedOperations": { "context_engine_control": [], - "context_engine_learning": ["SELECT", "INSERT"], - "context_engine_release_definer": ["SELECT"], + "context_engine_learning": [ + "SELECT", + "INSERT" + ], + "context_engine_release_definer": [ + "SELECT" + ], "context_engine_runtime": [], "context_engine_security_operator": [], "context_engine_worker": [] }, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "RELEASE-OWNER-019"], - "negativeTestIds": ["DB-001", "DB-003", "DB-004", "DB-005", "DB-008", "LEARN-004", "LEARN-006", "LEARN-007", "LEARN-008", "LEARN-009"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "RELEASE-OWNER-019" + ], + "negativeTestIds": [ + "DB-001", + "DB-003", + "DB-004", + "DB-005", + "DB-008", + "LEARN-004", + "LEARN-006", + "LEARN-007", + "LEARN-008", + "LEARN-009" + ] }, { "name": "release_evaluation", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-RELEASE-OWNER-019", - "selector": {"table": "release_evaluation"} + "selector": { + "table": "release_evaluation" + } }, "purpose": "Immutable signed evaluation evidence binding one exact candidate, manifest, veto gates and compatibility result", "organizationColumn": "organization_id", @@ -2451,29 +3668,52 @@ { "name": "pk_release_evaluation", "kind": "primary_key", - "columns": ["organization_id", "evaluation_ref"] + "columns": [ + "organization_id", + "evaluation_ref" + ] }, { "name": "uq_release_evaluation_exact_digest", "kind": "unique", - "columns": ["organization_id", "evaluation_ref", "evaluation_digest"] + "columns": [ + "organization_id", + "evaluation_ref", + "evaluation_digest" + ] } ], "foreignKeys": [ { "name": "fk_release_evaluation_candidate_exact", - "columns": ["organization_id", "candidate_ref", "candidate_digest"], + "columns": [ + "organization_id", + "candidate_ref", + "candidate_digest" + ], "references": { "table": "release_candidate", - "columns": ["organization_id", "candidate_ref", "candidate_digest"] + "columns": [ + "organization_id", + "candidate_ref", + "candidate_digest" + ] } }, { "name": "fk_release_evaluation_manifest_exact", - "columns": ["organization_id", "manifest_ref", "manifest_digest"], + "columns": [ + "organization_id", + "manifest_ref", + "manifest_digest" + ], "references": { "table": "release_manifest", - "columns": ["organization_id", "manifest_ref", "manifest_digest"] + "columns": [ + "organization_id", + "manifest_ref", + "manifest_digest" + ] } } ], @@ -2514,26 +3754,34 @@ { "name": "release_evaluation_learning_insert", "command": "INSERT", - "roles": ["context_engine_learning"], + "roles": [ + "context_engine_learning" + ], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "release_evaluation_learning_select", "command": "SELECT", - "roles": ["context_engine_learning"], + "roles": [ + "context_engine_learning" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "release_evaluation_release_definer", "command": "ALL", - "roles": ["context_engine_release_definer"], + "roles": [ + "context_engine_release_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "release_evaluation_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" } @@ -2542,27 +3790,53 @@ "immutableRows": { "trigger": "release_evaluation_reject_mutation", "function": "release_lineage_reject_mutation", - "events": ["UPDATE", "DELETE"], + "events": [ + "UPDATE", + "DELETE" + ], "sqlstate": "55000" }, "permittedOperations": { "context_engine_control": [], - "context_engine_learning": ["SELECT", "INSERT"], - "context_engine_release_definer": ["SELECT"], + "context_engine_learning": [ + "SELECT", + "INSERT" + ], + "context_engine_release_definer": [ + "SELECT" + ], "context_engine_runtime": [], "context_engine_security_operator": [], "context_engine_worker": [] }, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "RELEASE-OWNER-019"], - "negativeTestIds": ["DB-001", "DB-003", "DB-004", "DB-005", "DB-008", "LEARN-004", "LEARN-006", "LEARN-007", "LEARN-008", "LEARN-009"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "RELEASE-OWNER-019" + ], + "negativeTestIds": [ + "DB-001", + "DB-003", + "DB-004", + "DB-005", + "DB-008", + "LEARN-004", + "LEARN-006", + "LEARN-007", + "LEARN-008", + "LEARN-009" + ] }, { "name": "release_operator_grant", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-RELEASE-OWNER-019", - "selector": {"table": "release_operator_grant"} + "selector": { + "table": "release_operator_grant" + } }, "purpose": "Current Organization-scoped release-operator authority revalidated only by the promotion definer", "organizationColumn": "organization_id", @@ -2570,21 +3844,32 @@ { "name": "pk_release_operator_grant", "kind": "primary_key", - "columns": ["organization_id", "authority_ref"] + "columns": [ + "organization_id", + "authority_ref" + ] }, { "name": "uq_release_operator_grant_exact_digest", "kind": "unique", - "columns": ["organization_id", "authority_ref", "authority_digest"] + "columns": [ + "organization_id", + "authority_ref", + "authority_digest" + ] } ], "foreignKeys": [ { "name": "fk_release_operator_grant_organization", - "columns": ["organization_id"], + "columns": [ + "organization_id" + ], "references": { "table": "organization", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] }, "onDelete": "CASCADE" } @@ -2610,14 +3895,18 @@ { "name": "release_operator_grant_release_definer", "command": "ALL", - "roles": ["context_engine_release_definer"], + "roles": [ + "context_engine_release_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "release_operator_grant_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" } @@ -2626,21 +3915,37 @@ "permittedOperations": { "context_engine_control": [], "context_engine_learning": [], - "context_engine_release_definer": ["SELECT"], + "context_engine_release_definer": [ + "SELECT" + ], "context_engine_runtime": [], "context_engine_security_operator": [], "context_engine_worker": [] }, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "RELEASE-OWNER-019"], - "negativeTestIds": ["DB-001", "DB-004", "DB-005", "DB-008", "LEARN-006", "LEARN-007"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "RELEASE-OWNER-019" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-005", + "DB-008", + "LEARN-006", + "LEARN-007" + ] }, { "name": "active_release_manifest", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-RELEASE-OWNER-019", - "selector": {"table": "active_release_manifest"} + "selector": { + "table": "active_release_manifest" + } }, "purpose": "Generation-bound Organization active release pointer changed only by the sole promotion function", "organizationColumn": "organization_id", @@ -2648,21 +3953,34 @@ { "name": "pk_active_release_manifest", "kind": "primary_key", - "columns": ["organization_id"] + "columns": [ + "organization_id" + ] }, { "name": "uq_active_release_manifest_promotion", "kind": "unique", - "columns": ["organization_id", "promotion_ref"] + "columns": [ + "organization_id", + "promotion_ref" + ] } ], "foreignKeys": [ { "name": "fk_active_release_manifest_exact", - "columns": ["organization_id", "manifest_ref", "manifest_digest"], + "columns": [ + "organization_id", + "manifest_ref", + "manifest_digest" + ], "references": { "table": "release_manifest", - "columns": ["organization_id", "manifest_ref", "manifest_digest"] + "columns": [ + "organization_id", + "manifest_ref", + "manifest_digest" + ] } } ], @@ -2683,14 +4001,26 @@ { "name": "active_release_manifest_release_definer", "command": "ALL", - "roles": ["context_engine_release_definer"], + "roles": [ + "context_engine_release_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, + { + "name": "active_release_manifest_runtime_select", + "command": "SELECT", + "roles": [ + "context_engine_runtime" + ], + "using": "active_release_manifest.organization_id = NULLIF(\n current_setting('app.organization_id', true), ''\n)::uuid\nAND current_setting('app.actor_kind', true) = 'user'\nAND EXISTS (\n SELECT 1\n FROM public.membership AS actor_membership\n WHERE actor_membership.organization_id = active_release_manifest.organization_id\n AND actor_membership.user_id = NULLIF(\n current_setting('app.user_id', true), ''\n )::uuid\n AND actor_membership.membership_id = NULLIF(\n current_setting('app.membership_id', true), ''\n )::uuid\n AND actor_membership.membership_version = NULLIF(\n current_setting('app.membership_version', true), ''\n )::bigint\n AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL\n AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL\n AND NULLIF(\n current_setting('app.authentication_binding_ref', true), ''\n ) IS NOT NULL\n AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL\n AND actor_membership.status = 'active'\n AND actor_membership.valid_from <= NULLIF(\n current_setting('app.checked_at', true), ''\n )::timestamptz\n AND (\n actor_membership.valid_until IS NULL\n OR actor_membership.valid_until > NULLIF(\n current_setting('app.checked_at', true), ''\n )::timestamptz\n )\n)" + }, { "name": "active_release_manifest_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" } @@ -2704,288 +4034,1151 @@ }, "permittedOperations": { "context_engine_control": [], - "context_engine_learning": ["EXECUTE context_learning_promote_release"], - "context_engine_release_definer": ["SELECT", "INSERT", "UPDATE"], - "context_engine_runtime": [], + "context_engine_learning": [ + "EXECUTE context_learning_promote_release" + ], + "context_engine_release_definer": [ + "SELECT", + "INSERT", + "UPDATE" + ], + "context_engine_runtime": [ + "SELECT" + ], "context_engine_security_operator": [], "context_engine_worker": [] }, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "RELEASE-OWNER-019"], - "negativeTestIds": ["DB-001", "DB-004", "DB-005", "DB-008", "LEARN-004", "LEARN-006", "LEARN-007"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "RELEASE-OWNER-019" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-005", + "DB-008", + "LEARN-004", + "LEARN-006", + "LEARN-007" + ] }, { "name": "file_acquisition", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-FILE-IMPORT-023", - "selector": {"table": "file_acquisition"} + "selector": { + "table": "file_acquisition" + } }, "purpose": "Immutable trusted request to acquire one Markdown filename from one registered File Source version", "organizationColumn": "organization_id", "organizationInclusiveKeys": [ - {"name": "pk_file_acquisition", "kind": "primary_key", "columns": ["organization_id", "acquisition_id"]}, - {"name": "uq_file_acquisition_source_idempotency", "kind": "unique", "columns": ["organization_id", "source_id", "idempotency_key"]}, - {"name": "uq_file_acquisition_identity_source", "kind": "unique", "columns": ["organization_id", "acquisition_id", "source_id"]} + { + "name": "pk_file_acquisition", + "kind": "primary_key", + "columns": [ + "organization_id", + "acquisition_id" + ] + }, + { + "name": "uq_file_acquisition_source_idempotency", + "kind": "unique", + "columns": [ + "organization_id", + "source_id", + "idempotency_key" + ] + }, + { + "name": "uq_file_acquisition_identity_source", + "kind": "unique", + "columns": [ + "organization_id", + "acquisition_id", + "source_id" + ] + } ], "foreignKeys": [ { "name": "fk_file_acquisition_source_version_same_organization", - "columns": ["organization_id", "source_id", "source_version_id"], - "references": {"table": "source_version", "columns": ["organization_id", "source_id", "version_id"]} + "columns": [ + "organization_id", + "source_id", + "source_version_id" + ], + "references": { + "table": "source_version", + "columns": [ + "organization_id", + "source_id", + "version_id" + ] + } }, { "name": "fk_file_acquisition_membership_version_same_organization", - "columns": ["organization_id", "audience_membership_id", "audience_membership_version"], - "references": {"table": "membership", "columns": ["organization_id", "membership_id", "membership_version"]} + "columns": [ + "organization_id", + "audience_membership_id", + "audience_membership_version" + ], + "references": { + "table": "membership", + "columns": [ + "organization_id", + "membership_id", + "membership_version" + ] + } } ], "checkConstraints": [ - {"name": "ck_file_acquisition_one_markdown_filename", "expression": "relative_path ~ '^[^/\\\\]+\\.[mM][dD]$' AND relative_path NOT IN ('.', '..')"}, - {"name": "ck_file_acquisition_principal_nonblank", "expression": "btrim(audience_principal_ref) <> ''"}, - {"name": "ck_file_acquisition_membership_version_positive", "expression": "audience_membership_version > 0"}, - {"name": "ck_file_acquisition_idempotency_key", "expression": "idempotency_key ~ '^[^[:space:]]{1,255}$'"}, - {"name": "ck_file_acquisition_request_digest", "expression": "request_digest ~ '^[0-9a-f]{64}$'"} + { + "name": "ck_file_acquisition_one_markdown_filename", + "expression": "relative_path ~ '^[^/\\\\]+\\.[mM][dD]$' AND relative_path NOT IN ('.', '..')" + }, + { + "name": "ck_file_acquisition_principal_nonblank", + "expression": "btrim(audience_principal_ref) <> ''" + }, + { + "name": "ck_file_acquisition_membership_version_positive", + "expression": "audience_membership_version > 0" + }, + { + "name": "ck_file_acquisition_idempotency_key", + "expression": "idempotency_key ~ '^[^[:space:]]{1,255}$'" + }, + { + "name": "ck_file_acquisition_request_digest", + "expression": "request_digest ~ '^[0-9a-f]{64}$'" + } ], "rowLevelSecurity": { "enabled": true, "forced": true, "policies": [ - {"name": "file_acquisition_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "file_acquisition_file_import_definer_select", "command": "SELECT", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_acquisition_file_import_definer_insert", "command": "INSERT", "roles": ["context_engine_worker_lease_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"} + { + "name": "file_acquisition_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "file_acquisition_file_import_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_acquisition_file_import_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + } ] }, - "immutableRows": {"trigger": "file_acquisition_immutable", "function": "context_content_reject_mutation", "events": ["UPDATE", "DELETE"], "sqlstate": "55000"}, - "functionOnlyMutation": {"databaseFunction": "context_control_prepare_file_import", "role": "context_engine_control", "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_control": ["EXECUTE context_control_prepare_file_import"], "context_engine_runtime": [], "context_engine_worker": [], "context_engine_worker_lease_definer": ["SELECT", "INSERT"]}, - "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "WORKER-LEASE-007"], - "negativeTestIds": ["DB-001", "DB-004", "DB-008", "JOB-001", "WORKER-LEASE-007"] - }, - { - "name": "file_resource_ingestion_guard", - "classification": "tenant_owned", - "nonOwnerEvidence": { - "evidenceId": "PG-FILE-IMPORT-023", - "selector": {"table": "file_resource_ingestion_guard"} + "immutableRows": { + "trigger": "file_acquisition_immutable", + "function": "context_content_reject_mutation", + "events": [ + "UPDATE", + "DELETE" + ], + "sqlstate": "55000" }, - "purpose": "Organization, Source and stable Resource scoped transaction lock for concurrent File content classification", - "organizationColumn": "organization_id", + "functionOnlyMutation": { + "databaseFunction": "context_control_prepare_file_import", + "role": "context_engine_control", + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, + "permittedOperations": { + "context_engine_control": [ + "EXECUTE context_control_prepare_file_import" + ], + "context_engine_runtime": [], + "context_engine_worker": [], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT" + ] + }, + "partitions": [], + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "WORKER-LEASE-007" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-008", + "JOB-001", + "WORKER-LEASE-007" + ] + }, + { + "name": "file_resource_ingestion_guard", + "classification": "tenant_owned", + "nonOwnerEvidence": { + "evidenceId": "PG-FILE-IMPORT-023", + "selector": { + "table": "file_resource_ingestion_guard" + } + }, + "purpose": "Organization, Source and stable Resource scoped transaction lock for concurrent File content classification", + "organizationColumn": "organization_id", "organizationInclusiveKeys": [ - {"name": "pk_file_resource_ingestion_guard", "kind": "primary_key", "columns": ["organization_id", "source_id", "resource_ref"]}, - {"name": "uq_file_resource_ingestion_guard_resource", "kind": "unique", "columns": ["organization_id", "resource_ref"]} + { + "name": "pk_file_resource_ingestion_guard", + "kind": "primary_key", + "columns": [ + "organization_id", + "source_id", + "resource_ref" + ] + }, + { + "name": "uq_file_resource_ingestion_guard_resource", + "kind": "unique", + "columns": [ + "organization_id", + "resource_ref" + ] + } ], "foreignKeys": [ - {"name": "fk_file_resource_ingestion_guard_source_same_organization", "columns": ["organization_id", "source_id"], "references": {"table": "context_source", "columns": ["organization_id", "source_id"]}} + { + "name": "fk_file_resource_ingestion_guard_source_same_organization", + "columns": [ + "organization_id", + "source_id" + ], + "references": { + "table": "context_source", + "columns": [ + "organization_id", + "source_id" + ] + } + } ], "checkConstraints": [ - {"name": "ck_file_resource_ingestion_guard_resource_nonblank", "expression": "btrim(resource_ref) <> ''"} + { + "name": "ck_file_resource_ingestion_guard_resource_nonblank", + "expression": "btrim(resource_ref) <> ''" + } ], "rowLevelSecurity": { "enabled": true, "forced": true, "policies": [ - {"name": "file_resource_ingestion_guard_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "file_resource_ingestion_guard_file_import_definer_select", "command": "SELECT", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_resource_ingestion_guard_file_import_definer_insert", "command": "INSERT", "roles": ["context_engine_worker_lease_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_resource_ingestion_guard_file_import_definer_update", "command": "UPDATE", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"} + { + "name": "file_resource_ingestion_guard_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "file_resource_ingestion_guard_file_import_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_resource_ingestion_guard_file_import_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_resource_ingestion_guard_file_import_definer_update", + "command": "UPDATE", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + } + ] + }, + "immutableRows": { + "trigger": "file_resource_ingestion_guard_immutable", + "function": "context_content_reject_mutation", + "events": [ + "UPDATE", + "DELETE" + ], + "sqlstate": "55000" + }, + "functionOnlyMutation": { + "databaseFunctions": [ + "context_worker_publish_file_import_v2", + "context_worker_publish_structural_file_import_v2", + "context_worker_stage_file_replacement", + "context_worker_stage_structural_file_replacement", + "context_worker_acquire_file_publication" + ], + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, + "permittedOperations": { + "context_engine_control": [], + "context_engine_runtime": [], + "context_engine_worker": [ + "EXECUTE context_worker_publish_file_import_v2", + "EXECUTE context_worker_publish_structural_file_import_v2", + "EXECUTE context_worker_stage_file_replacement", + "EXECUTE context_worker_stage_structural_file_replacement", + "EXECUTE context_worker_acquire_file_publication" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT", + "UPDATE resource_ref" ] }, - "immutableRows": {"trigger": "file_resource_ingestion_guard_immutable", "function": "context_content_reject_mutation", "events": ["UPDATE", "DELETE"], "sqlstate": "55000"}, - "functionOnlyMutation": {"databaseFunctions": ["context_worker_publish_file_import_v2", "context_worker_publish_structural_file_import_v2", "context_worker_stage_file_replacement", "context_worker_stage_structural_file_replacement", "context_worker_acquire_file_publication"], "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_control": [], "context_engine_runtime": [], "context_engine_worker": ["EXECUTE context_worker_publish_file_import_v2", "EXECUTE context_worker_publish_structural_file_import_v2", "EXECUTE context_worker_stage_file_replacement", "EXECUTE context_worker_stage_structural_file_replacement", "EXECUTE context_worker_acquire_file_publication"], "context_engine_worker_lease_definer": ["SELECT", "INSERT", "UPDATE resource_ref"]}, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "WORKER-LEASE-007"], - "negativeTestIds": ["DB-001", "DB-004", "DB-008", "PG-FILE-IMPORT-023"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "WORKER-LEASE-007" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-008", + "PG-FILE-IMPORT-023" + ] }, { "name": "file_acquisition_result", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-FILE-IMPORT-023", - "selector": {"table": "file_acquisition_result"} + "selector": { + "table": "file_acquisition_result" + } }, "purpose": "Immutable unchanged-acquisition outcome binding one deduplicated observation to an Organization-owned active Revision", "organizationColumn": "organization_id", "organizationInclusiveKeys": [ - {"name": "pk_file_acquisition_result", "kind": "primary_key", "columns": ["organization_id", "acquisition_id"]} + { + "name": "pk_file_acquisition_result", + "kind": "primary_key", + "columns": [ + "organization_id", + "acquisition_id" + ] + } ], "foreignKeys": [ - {"name": "fk_file_acquisition_result_acquisition_source_same_organization", "columns": ["organization_id", "acquisition_id", "source_id"], "references": {"table": "file_acquisition", "columns": ["organization_id", "acquisition_id", "source_id"]}}, - {"name": "fk_file_acquisition_result_guard_same_organization", "columns": ["organization_id", "source_id", "resource_ref"], "references": {"table": "file_resource_ingestion_guard", "columns": ["organization_id", "source_id", "resource_ref"]}}, - {"name": "fk_file_acquisition_result_revision_same_organization", "columns": ["organization_id", "resource_ref", "active_revision_id"], "references": {"table": "context_revision", "columns": ["organization_id", "resource_ref", "revision_id"]}} + { + "name": "fk_file_acquisition_result_acquisition_source_same_organization", + "columns": [ + "organization_id", + "acquisition_id", + "source_id" + ], + "references": { + "table": "file_acquisition", + "columns": [ + "organization_id", + "acquisition_id", + "source_id" + ] + } + }, + { + "name": "fk_file_acquisition_result_guard_same_organization", + "columns": [ + "organization_id", + "source_id", + "resource_ref" + ], + "references": { + "table": "file_resource_ingestion_guard", + "columns": [ + "organization_id", + "source_id", + "resource_ref" + ] + } + }, + { + "name": "fk_file_acquisition_result_revision_same_organization", + "columns": [ + "organization_id", + "resource_ref", + "active_revision_id" + ], + "references": { + "table": "context_revision", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ] + } + } ], "checkConstraints": [ - {"name": "ck_file_acquisition_result_identity_digest", "expression": "content_identity_digest ~ '^[0-9a-f]{64}$'"}, - {"name": "ck_file_acquisition_result_outcome", "expression": "outcome is unchanged with active-content-identity-match and one SHA-256 reason_digest"} + { + "name": "ck_file_acquisition_result_identity_digest", + "expression": "content_identity_digest ~ '^[0-9a-f]{64}$'" + }, + { + "name": "ck_file_acquisition_result_outcome", + "expression": "outcome is unchanged with active-content-identity-match and one SHA-256 reason_digest" + } ], "rowLevelSecurity": { "enabled": true, "forced": true, "policies": [ - {"name": "file_acquisition_result_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "file_acquisition_result_file_import_definer_select", "command": "SELECT", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_acquisition_result_file_import_definer_insert", "command": "INSERT", "roles": ["context_engine_worker_lease_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"} + { + "name": "file_acquisition_result_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "file_acquisition_result_file_import_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_acquisition_result_file_import_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + } + ] + }, + "immutableRows": { + "trigger": "file_acquisition_result_immutable", + "function": "context_content_reject_mutation", + "events": [ + "UPDATE", + "DELETE" + ], + "sqlstate": "55000" + }, + "functionOnlyMutation": { + "databaseFunctions": [ + "context_worker_publish_file_import_v2", + "context_worker_publish_structural_file_import_v2", + "context_worker_stage_file_replacement", + "context_worker_stage_structural_file_replacement", + "context_worker_acquire_file_publication" + ], + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, + "permittedOperations": { + "context_engine_control": [], + "context_engine_runtime": [], + "context_engine_worker": [ + "EXECUTE context_worker_publish_file_import_v2", + "EXECUTE context_worker_publish_structural_file_import_v2", + "EXECUTE context_worker_stage_file_replacement", + "EXECUTE context_worker_stage_structural_file_replacement", + "EXECUTE context_worker_acquire_file_publication" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT" ] }, - "immutableRows": {"trigger": "file_acquisition_result_immutable", "function": "context_content_reject_mutation", "events": ["UPDATE", "DELETE"], "sqlstate": "55000"}, - "functionOnlyMutation": {"databaseFunctions": ["context_worker_publish_file_import_v2", "context_worker_publish_structural_file_import_v2", "context_worker_stage_file_replacement", "context_worker_stage_structural_file_replacement", "context_worker_acquire_file_publication"], "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_control": [], "context_engine_runtime": [], "context_engine_worker": ["EXECUTE context_worker_publish_file_import_v2", "EXECUTE context_worker_publish_structural_file_import_v2", "EXECUTE context_worker_stage_file_replacement", "EXECUTE context_worker_stage_structural_file_replacement", "EXECUTE context_worker_acquire_file_publication"], "context_engine_worker_lease_definer": ["SELECT", "INSERT"]}, - "retention": {"sourceContent": "none", "reason": "fixed code plus organization-scoped digest only"}, + "retention": { + "sourceContent": "none", + "reason": "fixed code plus organization-scoped digest only" + }, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "WORKER-LEASE-007", "TRACE-REDACTION-012"], - "negativeTestIds": ["DB-001", "DB-004", "DB-008", "PG-FILE-IMPORT-023"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "WORKER-LEASE-007", + "TRACE-REDACTION-012" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-008", + "PG-FILE-IMPORT-023" + ] }, { "name": "file_import_job", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-FILE-IMPORT-023", - "selector": {"table": "file_import_job"} + "selector": { + "table": "file_import_job" + } }, "purpose": "Durable one-shot File import job, exact WorkerLease redemption state, and terminal source-offboarding cancellation", "organizationColumn": "organization_id", "organizationInclusiveKeys": [ - {"name": "pk_file_import_job", "kind": "primary_key", "columns": ["organization_id", "job_id"]}, - {"name": "uq_file_import_job_acquisition", "kind": "unique", "columns": ["organization_id", "acquisition_id"]}, - {"name": "uq_file_import_job_progress_lineage", "kind": "unique", "columns": ["organization_id", "job_id", "acquisition_id", "source_id"]} + { + "name": "pk_file_import_job", + "kind": "primary_key", + "columns": [ + "organization_id", + "job_id" + ] + }, + { + "name": "uq_file_import_job_acquisition", + "kind": "unique", + "columns": [ + "organization_id", + "acquisition_id" + ] + }, + { + "name": "uq_file_import_job_progress_lineage", + "kind": "unique", + "columns": [ + "organization_id", + "job_id", + "acquisition_id", + "source_id" + ] + } ], "foreignKeys": [ { "name": "fk_file_import_job_acquisition_same_organization", - "columns": ["organization_id", "acquisition_id"], - "references": {"table": "file_acquisition", "columns": ["organization_id", "acquisition_id"]} + "columns": [ + "organization_id", + "acquisition_id" + ], + "references": { + "table": "file_acquisition", + "columns": [ + "organization_id", + "acquisition_id" + ] + } }, { "name": "fk_file_import_job_service_principal_binding", - "columns": ["organization_id", "service_principal_id", "workload", "worker_audience", "operation"], - "references": {"table": "service_principal", "columns": ["organization_id", "service_principal_id", "workload", "worker_audience", "operation"]} + "columns": [ + "organization_id", + "service_principal_id", + "workload", + "worker_audience", + "operation" + ], + "references": { + "table": "service_principal", + "columns": [ + "organization_id", + "service_principal_id", + "workload", + "worker_audience", + "operation" + ] + } }, { "name": "fk_file_import_job_source_cancellation_intent", - "columns": ["organization_id", "cancellation_intent_id"], - "references": {"table": "file_source_cleanup_intent", "columns": ["organization_id", "cleanup_intent_id"]} + "columns": [ + "organization_id", + "cancellation_intent_id" + ], + "references": { + "table": "file_source_cleanup_intent", + "columns": [ + "organization_id", + "cleanup_intent_id" + ] + } } ], "checkConstraints": [ - {"name": "ck_file_import_job_workload", "expression": "workload = 'supply.file-import'"}, - {"name": "ck_file_import_job_worker_audience", "expression": "worker_audience = 'context-engine-worker'"}, - {"name": "ck_file_import_job_actor_kind", "expression": "actor_kind = 'service'"}, - {"name": "ck_file_import_job_operation", "expression": "operation = 'file.import'"}, - {"name": "ck_file_import_job_state", "expression": "state IN ('available', 'leased', 'running', 'prepared', 'ready', 'failed', 'completed', 'cancelled')"}, - {"name": "ck_file_import_job_state_consistency", "expression": "active transitions bind one current lease generation and nonce; cancelled preserves its prior state and exact source cleanup intent with effect_count = 0"}, - {"name": "ck_file_import_job_recovery_from_state", "expression": "recovery_from_state IS NULL OR recovery_from_state IN ('running', 'prepared', 'ready')"} + { + "name": "ck_file_import_job_workload", + "expression": "workload = 'supply.file-import'" + }, + { + "name": "ck_file_import_job_worker_audience", + "expression": "worker_audience = 'context-engine-worker'" + }, + { + "name": "ck_file_import_job_actor_kind", + "expression": "actor_kind = 'service'" + }, + { + "name": "ck_file_import_job_operation", + "expression": "operation = 'file.import'" + }, + { + "name": "ck_file_import_job_state", + "expression": "state IN ('available', 'leased', 'running', 'prepared', 'ready', 'failed', 'completed', 'cancelled')" + }, + { + "name": "ck_file_import_job_state_consistency", + "expression": "active transitions bind one current lease generation and nonce; cancelled preserves its prior state and exact source cleanup intent with effect_count = 0" + }, + { + "name": "ck_file_import_job_recovery_from_state", + "expression": "recovery_from_state IS NULL OR recovery_from_state IN ('running', 'prepared', 'ready')" + } ], "rowLevelSecurity": { "enabled": true, "forced": true, "policies": [ - {"name": "file_import_job_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "file_import_job_definer_select", "command": "SELECT", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND (job_id = NULLIF(current_setting('app.worker_job_id', true), '')::uuid OR acquisition_id = NULLIF(current_setting('app.file_acquisition_id', true), '')::uuid) AND workload = 'supply.file-import' AND worker_audience = 'context-engine-worker' AND operation = 'file.import' AND EXISTS (SELECT 1 FROM public.context_source AS active_source WHERE active_source.organization_id = file_import_job.organization_id AND active_source.source_id = file_import_job.source_id AND active_source.lifecycle_state = 'active')"}, - {"name": "file_import_job_definer_insert", "command": "INSERT", "roles": ["context_engine_worker_lease_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND job_id = NULLIF(current_setting('app.worker_job_id', true), '')::uuid AND workload = 'supply.file-import' AND worker_audience = 'context-engine-worker' AND operation = 'file.import'"}, - {"name": "file_import_job_definer_update", "command": "UPDATE", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND job_id = NULLIF(current_setting('app.worker_job_id', true), '')::uuid AND workload = 'supply.file-import' AND worker_audience = 'context-engine-worker' AND operation = 'file.import' AND EXISTS (SELECT 1 FROM public.context_source AS active_source WHERE active_source.organization_id = file_import_job.organization_id AND active_source.source_id = file_import_job.source_id AND active_source.lifecycle_state = 'active')", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND job_id = NULLIF(current_setting('app.worker_job_id', true), '')::uuid AND workload = 'supply.file-import' AND worker_audience = 'context-engine-worker' AND operation = 'file.import' AND EXISTS (SELECT 1 FROM public.context_source AS active_source WHERE active_source.organization_id = file_import_job.organization_id AND active_source.source_id = file_import_job.source_id AND active_source.lifecycle_state = 'active')"}, - {"name": "file_import_job_access_policy_definer_select", "command": "SELECT", "roles": ["context_engine_access_policy_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_import_job_access_policy_definer_update", "command": "UPDATE", "roles": ["context_engine_access_policy_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"} + { + "name": "file_import_job_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "file_import_job_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND (job_id = NULLIF(current_setting('app.worker_job_id', true), '')::uuid OR acquisition_id = NULLIF(current_setting('app.file_acquisition_id', true), '')::uuid) AND workload = 'supply.file-import' AND worker_audience = 'context-engine-worker' AND operation = 'file.import' AND EXISTS (SELECT 1 FROM public.context_source AS active_source WHERE active_source.organization_id = file_import_job.organization_id AND active_source.source_id = file_import_job.source_id AND active_source.lifecycle_state = 'active')" + }, + { + "name": "file_import_job_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND job_id = NULLIF(current_setting('app.worker_job_id', true), '')::uuid AND workload = 'supply.file-import' AND worker_audience = 'context-engine-worker' AND operation = 'file.import'" + }, + { + "name": "file_import_job_definer_update", + "command": "UPDATE", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND job_id = NULLIF(current_setting('app.worker_job_id', true), '')::uuid AND workload = 'supply.file-import' AND worker_audience = 'context-engine-worker' AND operation = 'file.import' AND EXISTS (SELECT 1 FROM public.context_source AS active_source WHERE active_source.organization_id = file_import_job.organization_id AND active_source.source_id = file_import_job.source_id AND active_source.lifecycle_state = 'active')", + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND job_id = NULLIF(current_setting('app.worker_job_id', true), '')::uuid AND workload = 'supply.file-import' AND worker_audience = 'context-engine-worker' AND operation = 'file.import' AND EXISTS (SELECT 1 FROM public.context_source AS active_source WHERE active_source.organization_id = file_import_job.organization_id AND active_source.source_id = file_import_job.source_id AND active_source.lifecycle_state = 'active')" + }, + { + "name": "file_import_job_access_policy_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_access_policy_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_import_job_access_policy_definer_update", + "command": "UPDATE", + "roles": [ + "context_engine_access_policy_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + } + ] + }, + "functionOnlyMutation": { + "databaseFunctions": [ + "context_control_prepare_file_import", + "context_control_offboard_file_source", + "context_worker_issue_file_import_lease", + "context_worker_redeem_file_import", + "context_worker_fail_file_import", + "context_worker_publish_file_import_v2", + "context_worker_publish_structural_file_import_v2", + "context_worker_stage_file_replacement", + "context_worker_stage_structural_file_replacement", + "context_worker_activate_file_replacement", + "context_worker_acquire_file_publication", + "context_worker_prepare_file_publication", + "context_worker_index_file_publication", + "context_worker_activate_recoverable_file_publication", + "context_worker_record_file_import_interruption" + ], + "definerRoles": [ + "context_engine_worker_lease_definer", + "context_engine_access_policy_definer" + ], + "directTableMutationAllowed": false + }, + "permittedOperations": { + "context_engine_access_policy_definer": [ + "SELECT", + "UPDATE state, cancelled_from_state, cancelled_at, cancellation_intent_id" + ], + "context_engine_control": [ + "EXECUTE context_control_prepare_file_import", + "EXECUTE context_control_offboard_file_source", + "EXECUTE context_worker_issue_file_import_lease" + ], + "context_engine_runtime": [], + "context_engine_worker": [ + "EXECUTE context_worker_redeem_file_import", + "EXECUTE context_worker_fail_file_import", + "EXECUTE context_worker_publish_file_import_v2", + "EXECUTE context_worker_publish_structural_file_import_v2", + "EXECUTE context_worker_stage_file_replacement", + "EXECUTE context_worker_stage_structural_file_replacement", + "EXECUTE context_worker_activate_file_replacement", + "EXECUTE context_worker_acquire_file_publication", + "EXECUTE context_worker_prepare_file_publication", + "EXECUTE context_worker_index_file_publication", + "EXECUTE context_worker_activate_recoverable_file_publication", + "EXECUTE context_worker_record_file_import_interruption" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT", + "UPDATE" ] }, - "functionOnlyMutation": {"databaseFunctions": ["context_control_prepare_file_import", "context_control_offboard_file_source", "context_worker_issue_file_import_lease", "context_worker_redeem_file_import", "context_worker_fail_file_import", "context_worker_publish_file_import_v2", "context_worker_publish_structural_file_import_v2", "context_worker_stage_file_replacement", "context_worker_stage_structural_file_replacement", "context_worker_activate_file_replacement", "context_worker_acquire_file_publication", "context_worker_prepare_file_publication", "context_worker_index_file_publication", "context_worker_activate_recoverable_file_publication", "context_worker_record_file_import_interruption"], "definerRoles": ["context_engine_worker_lease_definer", "context_engine_access_policy_definer"], "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_access_policy_definer": ["SELECT", "UPDATE state, cancelled_from_state, cancelled_at, cancellation_intent_id"], "context_engine_control": ["EXECUTE context_control_prepare_file_import", "EXECUTE context_control_offboard_file_source", "EXECUTE context_worker_issue_file_import_lease"], "context_engine_runtime": [], "context_engine_worker": ["EXECUTE context_worker_redeem_file_import", "EXECUTE context_worker_fail_file_import", "EXECUTE context_worker_publish_file_import_v2", "EXECUTE context_worker_publish_structural_file_import_v2", "EXECUTE context_worker_stage_file_replacement", "EXECUTE context_worker_stage_structural_file_replacement", "EXECUTE context_worker_activate_file_replacement", "EXECUTE context_worker_acquire_file_publication", "EXECUTE context_worker_prepare_file_publication", "EXECUTE context_worker_index_file_publication", "EXECUTE context_worker_activate_recoverable_file_publication", "EXECUTE context_worker_record_file_import_interruption"], "context_engine_worker_lease_definer": ["SELECT", "INSERT", "UPDATE"]}, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "WORKER-LEASE-007"], - "negativeTestIds": ["DB-001", "DB-004", "DB-008", "JOB-001", "JOB-005", "WORKER-LEASE-007", "PG-FILE-SOURCE-OFFBOARD-030"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "WORKER-LEASE-007" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-008", + "JOB-001", + "JOB-005", + "WORKER-LEASE-007", + "PG-FILE-SOURCE-OFFBOARD-030" + ] }, { "name": "file_publication_recovery", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-FILE-RECOVERY-027", - "selector": {"table": "file_publication_recovery"} + "selector": { + "table": "file_publication_recovery" + } }, "purpose": "Mutable Organization/job checkpoint binding one File publication to one stable Resource and Revision identity across lease generations", "organizationColumn": "organization_id", "organizationInclusiveKeys": [ - {"name": "pk_file_publication_recovery", "kind": "primary_key", "columns": ["organization_id", "job_id"]}, - {"name": "uq_file_publication_recovery_revision", "kind": "unique", "columns": ["organization_id", "resource_ref", "revision_id"]} + { + "name": "pk_file_publication_recovery", + "kind": "primary_key", + "columns": [ + "organization_id", + "job_id" + ] + }, + { + "name": "uq_file_publication_recovery_revision", + "kind": "unique", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ] + } ], "foreignKeys": [ - {"name": "fk_file_publication_recovery_job_same_organization", "columns": ["organization_id", "job_id"], "references": {"table": "file_import_job", "columns": ["organization_id", "job_id"]}}, - {"name": "fk_file_publication_recovery_guard_same_organization", "columns": ["organization_id", "source_id", "resource_ref"], "references": {"table": "file_resource_ingestion_guard", "columns": ["organization_id", "source_id", "resource_ref"]}}, - {"name": "fk_file_publication_recovery_previous_same_organization", "columns": ["organization_id", "resource_ref", "previous_revision_id"], "references": {"table": "context_revision", "columns": ["organization_id", "resource_ref", "revision_id"]}} + { + "name": "fk_file_publication_recovery_job_same_organization", + "columns": [ + "organization_id", + "job_id" + ], + "references": { + "table": "file_import_job", + "columns": [ + "organization_id", + "job_id" + ] + } + }, + { + "name": "fk_file_publication_recovery_guard_same_organization", + "columns": [ + "organization_id", + "source_id", + "resource_ref" + ], + "references": { + "table": "file_resource_ingestion_guard", + "columns": [ + "organization_id", + "source_id", + "resource_ref" + ] + } + }, + { + "name": "fk_file_publication_recovery_previous_same_organization", + "columns": [ + "organization_id", + "resource_ref", + "previous_revision_id" + ], + "references": { + "table": "context_revision", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ] + } + } ], "checkConstraints": [ - {"name": "ck_file_publication_recovery_kind", "expression": "initial has no previous Revision; replacement has one distinct previous Revision"}, - {"name": "ck_file_publication_recovery_checkpoint", "expression": "checkpoint IN ('acquired', 'prepared', 'ready', 'completed')"}, - {"name": "ck_file_publication_recovery_digests", "expression": "content identity, content, compilation and exact publication-payload digests are SHA-256 hex"}, - {"name": "ck_file_publication_recovery_compiler", "expression": "only the accepted Markdown v1 and v2 compiler/config pairs are recoverable"} - ], - "rowLevelSecurity": {"enabled": true, "forced": true, "policies": [ - {"name": "file_publication_recovery_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "file_publication_recovery_file_import_definer_select", "command": "SELECT", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_publication_recovery_file_import_definer_insert", "command": "INSERT", "roles": ["context_engine_worker_lease_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_publication_recovery_file_import_definer_update", "command": "UPDATE", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"} - ]}, - "functionOnlyMutation": {"databaseFunctions": ["context_worker_acquire_file_publication", "context_worker_prepare_file_publication", "context_worker_index_file_publication", "context_worker_activate_recoverable_file_publication"], "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_control": [], "context_engine_runtime": [], "context_engine_worker": ["EXECUTE context_worker_acquire_file_publication", "EXECUTE context_worker_prepare_file_publication", "EXECUTE context_worker_index_file_publication", "EXECUTE context_worker_activate_recoverable_file_publication"], "context_engine_worker_lease_definer": ["SELECT", "INSERT", "UPDATE"]}, - "retention": {"sourceContent": "none", "state": "retained with its publication job; cleanup authority is not active in Issue #27"}, - "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "WORKER-LEASE-007", "TRACE-REDACTION-012"], - "negativeTestIds": ["DB-001", "DB-004", "DB-008", "PG-FILE-RECOVERY-027"] - }, - { + { + "name": "ck_file_publication_recovery_kind", + "expression": "initial has no previous Revision; replacement has one distinct previous Revision" + }, + { + "name": "ck_file_publication_recovery_checkpoint", + "expression": "checkpoint IN ('acquired', 'prepared', 'ready', 'completed')" + }, + { + "name": "ck_file_publication_recovery_digests", + "expression": "content identity, content, compilation and exact publication-payload digests are SHA-256 hex" + }, + { + "name": "ck_file_publication_recovery_compiler", + "expression": "only the accepted Markdown v1 and v2 compiler/config pairs are recoverable" + } + ], + "rowLevelSecurity": { + "enabled": true, + "forced": true, + "policies": [ + { + "name": "file_publication_recovery_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "file_publication_recovery_file_import_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_publication_recovery_file_import_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_publication_recovery_file_import_definer_update", + "command": "UPDATE", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + } + ] + }, + "functionOnlyMutation": { + "databaseFunctions": [ + "context_worker_acquire_file_publication", + "context_worker_prepare_file_publication", + "context_worker_index_file_publication", + "context_worker_activate_recoverable_file_publication" + ], + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, + "permittedOperations": { + "context_engine_control": [], + "context_engine_runtime": [], + "context_engine_worker": [ + "EXECUTE context_worker_acquire_file_publication", + "EXECUTE context_worker_prepare_file_publication", + "EXECUTE context_worker_index_file_publication", + "EXECUTE context_worker_activate_recoverable_file_publication" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT", + "UPDATE" + ] + }, + "retention": { + "sourceContent": "none", + "state": "retained with its publication job; cleanup authority is not active in Issue #27" + }, + "partitions": [], + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "WORKER-LEASE-007", + "TRACE-REDACTION-012" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-008", + "PG-FILE-RECOVERY-027" + ] + }, + { "name": "file_import_job_event", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-FILE-RECOVERY-027", - "selector": {"table": "file_import_job_event"} + "selector": { + "table": "file_import_job_event" + } }, "purpose": "Immutable ordered audit of durable publication boundaries, explicit interruption, lease reclaim and activation", "organizationColumn": "organization_id", "organizationInclusiveKeys": [ - {"name": "pk_file_import_job_event", "kind": "primary_key", "columns": ["organization_id", "job_id", "ordinal"]} + { + "name": "pk_file_import_job_event", + "kind": "primary_key", + "columns": [ + "organization_id", + "job_id", + "ordinal" + ] + } ], "foreignKeys": [ - {"name": "fk_file_import_job_event_job_same_organization", "columns": ["organization_id", "job_id"], "references": {"table": "file_import_job", "columns": ["organization_id", "job_id"]}} + { + "name": "fk_file_import_job_event_job_same_organization", + "columns": [ + "organization_id", + "job_id" + ], + "references": { + "table": "file_import_job", + "columns": [ + "organization_id", + "job_id" + ] + } + } ], "checkConstraints": [ - {"name": "ck_file_import_job_event_type", "expression": "event_type is acquired, prepared, indexed, interrupted, reclaimed, active or unchanged"}, - {"name": "ck_file_import_job_event_boundary", "expression": "boundary is acquired, prepared, indexed or active"}, - {"name": "ck_file_import_job_event_generation", "expression": "lease_generation > 0"}, - {"name": "ck_file_import_job_event_reason_digest", "expression": "interrupted, reclaimed and unchanged events require a SHA-256 reason digest; other events forbid it"} - ], - "rowLevelSecurity": {"enabled": true, "forced": true, "policies": [ - {"name": "file_import_job_event_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "file_import_job_event_file_import_definer_select", "command": "SELECT", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_import_job_event_file_import_definer_insert", "command": "INSERT", "roles": ["context_engine_worker_lease_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"} - ]}, - "immutableRows": {"trigger": "file_import_job_event_immutable", "function": "context_content_reject_mutation", "events": ["UPDATE", "DELETE"], "sqlstate": "55000"}, - "functionOnlyMutation": {"databaseFunctions": ["context_worker_issue_file_import_lease", "context_worker_acquire_file_publication", "context_worker_prepare_file_publication", "context_worker_index_file_publication", "context_worker_activate_recoverable_file_publication", "context_worker_record_file_import_interruption"], "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_control": ["EXECUTE context_worker_issue_file_import_lease"], "context_engine_runtime": [], "context_engine_worker": ["EXECUTE context_worker_acquire_file_publication", "EXECUTE context_worker_prepare_file_publication", "EXECUTE context_worker_index_file_publication", "EXECUTE context_worker_activate_recoverable_file_publication", "EXECUTE context_worker_record_file_import_interruption"], "context_engine_worker_lease_definer": ["SELECT", "INSERT"]}, - "retention": {"sourceContent": "none", "reason": "fixed categories plus Organization/job/revision and digests only"}, + { + "name": "ck_file_import_job_event_type", + "expression": "event_type is acquired, prepared, indexed, interrupted, reclaimed, active or unchanged" + }, + { + "name": "ck_file_import_job_event_boundary", + "expression": "boundary is acquired, prepared, indexed or active" + }, + { + "name": "ck_file_import_job_event_generation", + "expression": "lease_generation > 0" + }, + { + "name": "ck_file_import_job_event_reason_digest", + "expression": "interrupted, reclaimed and unchanged events require a SHA-256 reason digest; other events forbid it" + } + ], + "rowLevelSecurity": { + "enabled": true, + "forced": true, + "policies": [ + { + "name": "file_import_job_event_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "file_import_job_event_file_import_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_import_job_event_file_import_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + } + ] + }, + "immutableRows": { + "trigger": "file_import_job_event_immutable", + "function": "context_content_reject_mutation", + "events": [ + "UPDATE", + "DELETE" + ], + "sqlstate": "55000" + }, + "functionOnlyMutation": { + "databaseFunctions": [ + "context_worker_issue_file_import_lease", + "context_worker_acquire_file_publication", + "context_worker_prepare_file_publication", + "context_worker_index_file_publication", + "context_worker_activate_recoverable_file_publication", + "context_worker_record_file_import_interruption" + ], + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, + "permittedOperations": { + "context_engine_control": [ + "EXECUTE context_worker_issue_file_import_lease" + ], + "context_engine_runtime": [], + "context_engine_worker": [ + "EXECUTE context_worker_acquire_file_publication", + "EXECUTE context_worker_prepare_file_publication", + "EXECUTE context_worker_index_file_publication", + "EXECUTE context_worker_activate_recoverable_file_publication", + "EXECUTE context_worker_record_file_import_interruption" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT" + ] + }, + "retention": { + "sourceContent": "none", + "reason": "fixed categories plus Organization/job/revision and digests only" + }, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "WORKER-LEASE-007", "TRACE-REDACTION-012"], - "negativeTestIds": ["DB-001", "DB-004", "DB-008", "PG-FILE-RECOVERY-027"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "WORKER-LEASE-007", + "TRACE-REDACTION-012" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-008", + "PG-FILE-RECOVERY-027" + ] }, { "name": "file_revision_snapshot", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-FILE-IMPORT-023", - "selector": {"table": "file_revision_snapshot"} + "selector": { + "table": "file_revision_snapshot" + } }, "purpose": "Immutable canonical Markdown compilation payload and digest lineage for one Revision", "organizationColumn": "organization_id", "organizationInclusiveKeys": [ - {"name": "pk_file_revision_snapshot", "kind": "primary_key", "columns": ["organization_id", "resource_ref", "revision_id"]} + { + "name": "pk_file_revision_snapshot", + "kind": "primary_key", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ] + } ], "foreignKeys": [ - {"name": "fk_file_revision_snapshot_revision_same_organization", "columns": ["organization_id", "resource_ref", "revision_id"], "references": {"table": "context_revision", "columns": ["organization_id", "resource_ref", "revision_id"]}}, - {"name": "fk_file_revision_snapshot_acquisition_same_organization", "columns": ["organization_id", "acquisition_id"], "references": {"table": "file_acquisition", "columns": ["organization_id", "acquisition_id"]}} + { + "name": "fk_file_revision_snapshot_revision_same_organization", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ], + "references": { + "table": "context_revision", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ] + } + }, + { + "name": "fk_file_revision_snapshot_acquisition_same_organization", + "columns": [ + "organization_id", + "acquisition_id" + ], + "references": { + "table": "file_acquisition", + "columns": [ + "organization_id", + "acquisition_id" + ] + } + } ], "checkConstraints": [ - {"name": "ck_file_revision_snapshot_content_hash", "expression": "content_hash ~ '^[0-9a-f]{64}$'"}, - {"name": "ck_file_revision_snapshot_compilation_digest", "expression": "compilation_digest ~ '^[0-9a-f]{64}$'"}, - {"name": "ck_file_revision_snapshot_structural_document", "expression": "(compilation_document IS NULL AND compiler_version = 'context-engine-markdown-v1' AND config_version = 'markdown-config-v1') OR (compilation_document IS NOT NULL AND compiler_version = 'context-engine-markdown-v2' AND config_version = 'markdown-config-v2' AND null-safe compilation_document bindings require canonical_text, content_hash, compilation_digest, compiler/config versions, markdown-structural-units-v2, and rfc8785-sha256-v2)"} + { + "name": "ck_file_revision_snapshot_content_hash", + "expression": "content_hash ~ '^[0-9a-f]{64}$'" + }, + { + "name": "ck_file_revision_snapshot_compilation_digest", + "expression": "compilation_digest ~ '^[0-9a-f]{64}$'" + }, + { + "name": "ck_file_revision_snapshot_structural_document", + "expression": "(compilation_document IS NULL AND compiler_version = 'context-engine-markdown-v1' AND config_version = 'markdown-config-v1') OR (compilation_document IS NOT NULL AND compiler_version = 'context-engine-markdown-v2' AND config_version = 'markdown-config-v2' AND null-safe compilation_document bindings require canonical_text, content_hash, compilation_digest, compiler/config versions, markdown-structural-units-v2, and rfc8785-sha256-v2)" + } ], "versionedCompilationContract": { "markdown-config-v1": { @@ -2994,308 +5187,1483 @@ }, "markdown-config-v2": { "compilationDocument": "required immutable JSONB", - "logicalUnits": ["heading", "paragraph", "list", "fenced_code", "table"], + "logicalUnits": [ + "heading", + "paragraph", + "list", + "fenced_code", + "table" + ], "fragmentBoundary": "one Fragment per logical unit", "contextBoundary": "parent heading ancestry is copied into the same authorized Fragment; no parent expansion is performed", - "provenance": ["stable structural path", "exact source position", "source text", "compiler/config profiles"] + "provenance": [ + "stable structural path", + "exact source position", + "source text", + "compiler/config profiles" + ] + } + }, + "rowLevelSecurity": { + "enabled": true, + "forced": true, + "policies": [ + { + "name": "file_revision_snapshot_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "file_revision_snapshot_file_import_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_revision_snapshot_file_noop_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + } + ] + }, + "immutableRows": { + "trigger": "file_revision_snapshot_immutable", + "function": "context_content_reject_mutation", + "events": [ + "UPDATE", + "DELETE" + ], + "sqlstate": "55000" + }, + "functionOnlyMutation": { + "databaseFunction": "context_worker_prepare_file_publication", + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, + "permittedOperations": { + "context_engine_control": [], + "context_engine_runtime": [], + "context_engine_worker": [ + "EXECUTE context_worker_publish_file_import_v2", + "EXECUTE context_worker_publish_structural_file_import_v2", + "EXECUTE context_worker_prepare_file_publication" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT" + ] + }, + "partitions": [], + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "TRACE-REDACTION-012" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-008", + "WORKER-LEASE-007" + ] + }, + { + "name": "revision_publication_event", + "classification": "tenant_owned", + "nonOwnerEvidence": { + "evidenceId": "PG-FILE-IMPORT-023", + "selector": { + "table": "revision_publication_event" + } + }, + "purpose": "Immutable ordered prepared-indexed-active publication evidence for one Revision", + "organizationColumn": "organization_id", + "organizationInclusiveKeys": [ + { + "name": "pk_revision_publication_event", + "kind": "primary_key", + "columns": [ + "organization_id", + "resource_ref", + "revision_id", + "ordinal" + ] + }, + { + "name": "uq_revision_publication_event_state", + "kind": "unique", + "columns": [ + "organization_id", + "resource_ref", + "revision_id", + "state" + ] + } + ], + "foreignKeys": [ + { + "name": "fk_revision_publication_event_revision_same_organization", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ], + "references": { + "table": "context_revision", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ] + } + } + ], + "checkConstraints": [ + { + "name": "ck_revision_publication_event_order", + "expression": "(ordinal, state) IN ((0, 'prepared'), (1, 'indexed'), (2, 'active'))" } + ], + "rowLevelSecurity": { + "enabled": true, + "forced": true, + "policies": [ + { + "name": "revision_publication_event_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "revision_publication_event_file_import_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "revision_publication_event_file_noop_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "revision_publication_event_current_user_actor", + "command": "SELECT", + "roles": [ + "context_engine_runtime" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'user' AND EXISTS (SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = revision_publication_event.organization_id AND actor_membership.user_id = NULLIF(current_setting('app.user_id', true), '')::uuid AND actor_membership.membership_id = NULLIF(current_setting('app.membership_id', true), '')::uuid AND actor_membership.membership_version = NULLIF(current_setting('app.membership_version', true), '')::bigint AND actor_membership.status = 'active' AND actor_membership.valid_from <= NULLIF(current_setting('app.checked_at', true), '')::timestamptz AND (actor_membership.valid_until IS NULL OR actor_membership.valid_until > NULLIF(current_setting('app.checked_at', true), '')::timestamptz)) AND EXISTS (SELECT 1 FROM public.resource_access_policy AS access_policy WHERE access_policy.organization_id = revision_publication_event.organization_id AND access_policy.resource_ref = revision_publication_event.resource_ref AND access_policy.principal_ref = current_setting('app.principal_ref', true) AND access_policy.access_state = 'allowed')" + } + ] + }, + "immutableRows": { + "trigger": "revision_publication_event_immutable", + "function": "context_content_reject_mutation", + "events": [ + "UPDATE", + "DELETE" + ], + "sqlstate": "55000" + }, + "functionOnlyMutation": { + "databaseFunctions": [ + "context_worker_prepare_file_publication", + "context_worker_index_file_publication", + "context_worker_activate_recoverable_file_publication" + ], + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, + "permittedOperations": { + "context_engine_control": [], + "context_engine_runtime": [ + "SELECT" + ], + "context_engine_worker": [ + "EXECUTE context_worker_publish_file_import_v2", + "EXECUTE context_worker_publish_structural_file_import_v2", + "EXECUTE context_worker_prepare_file_publication", + "EXECUTE context_worker_index_file_publication", + "EXECUTE context_worker_activate_recoverable_file_publication" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT" + ] + }, + "partitions": [], + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "TRACE-REDACTION-012" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-008", + "WORKER-LEASE-007" + ] + }, + { + "name": "exact_phrase_candidate", + "classification": "tenant_owned", + "nonOwnerEvidence": { + "evidenceId": "PG-FILE-IMPORT-023", + "selector": { + "table": "exact_phrase_candidate" + } + }, + "purpose": "Content-free deterministic exact-phrase CandidateIndex; never an authorization authority", + "organizationColumn": "organization_id", + "organizationInclusiveKeys": [ + { + "name": "pk_exact_phrase_candidate", + "kind": "primary_key", + "columns": [ + "organization_id", + "phrase_digest", + "resource_ref", + "revision_id", + "fragment_ref" + ] + } + ], + "foreignKeys": [ + { + "name": "fk_exact_phrase_candidate_fragment_same_organization", + "columns": [ + "organization_id", + "resource_ref", + "revision_id", + "fragment_ref" + ], + "references": { + "table": "context_fragment", + "columns": [ + "organization_id", + "resource_ref", + "revision_id", + "fragment_ref" + ] + } + } + ], + "checkConstraints": [ + { + "name": "ck_exact_phrase_candidate_digest", + "expression": "phrase_digest ~ '^[0-9a-f]{64}$'" + } + ], + "rowLevelSecurity": { + "enabled": true, + "forced": true, + "policies": [ + { + "name": "exact_phrase_candidate_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "exact_phrase_candidate_file_import_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "exact_phrase_candidate_file_noop_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "exact_phrase_candidate_runtime", + "command": "SELECT", + "roles": [ + "context_engine_runtime" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'user' AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL AND NULLIF(current_setting('app.authentication_binding_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL AND EXISTS (SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = exact_phrase_candidate.organization_id AND actor_membership.user_id = NULLIF(current_setting('app.user_id', true), '')::uuid AND actor_membership.membership_id = NULLIF(current_setting('app.membership_id', true), '')::uuid AND actor_membership.membership_version = NULLIF(current_setting('app.membership_version', true), '')::bigint AND actor_membership.status = 'active' AND actor_membership.valid_from <= NULLIF(current_setting('app.checked_at', true), '')::timestamptz AND (actor_membership.valid_until IS NULL OR actor_membership.valid_until > NULLIF(current_setting('app.checked_at', true), '')::timestamptz))" + } + ] + }, + "immutableRows": { + "trigger": "exact_phrase_candidate_immutable", + "function": "context_content_reject_mutation", + "events": [ + "UPDATE", + "DELETE" + ], + "sqlstate": "55000" + }, + "functionOnlyMutation": { + "databaseFunction": "context_worker_index_file_publication", + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, + "permittedOperations": { + "context_engine_control": [], + "context_engine_runtime": [ + "SELECT" + ], + "context_engine_worker": [ + "EXECUTE context_worker_publish_file_import_v2", + "EXECUTE context_worker_publish_structural_file_import_v2", + "EXECUTE context_worker_index_file_publication" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT" + ] + }, + "partitions": [], + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "INDEX-NOT-AUTHORITY-005" + ], + "negativeTestIds": [ + "DB-001", + "DB-002", + "DB-004", + "DB-008", + "DB-009", + "DB-010", + "PG-INDEX-NOT-AUTHORITY-005" + ] + }, + { + "name": "file_revision_replacement_plan", + "classification": "tenant_owned", + "nonOwnerEvidence": { + "evidenceId": "PG-FILE-REPLACEMENT-026", + "selector": { + "table": "file_revision_replacement_plan" + } + }, + "purpose": "Immutable durable ready boundary binding one complete replacement Revision to the exact old active Revision and File import job", + "organizationColumn": "organization_id", + "organizationInclusiveKeys": [ + { + "name": "pk_file_revision_replacement_plan", + "kind": "primary_key", + "columns": [ + "organization_id", + "resource_ref", + "replacement_revision_id" + ] + }, + { + "name": "uq_file_revision_replacement_plan_job", + "kind": "unique", + "columns": [ + "organization_id", + "job_id" + ] + }, + { + "name": "uq_file_revision_replacement_plan_previous", + "kind": "unique", + "columns": [ + "organization_id", + "resource_ref", + "previous_revision_id" + ] + } + ], + "foreignKeys": [ + { + "name": "fk_file_revision_replacement_plan_guard_same_organization", + "columns": [ + "organization_id", + "source_id", + "resource_ref" + ], + "references": { + "table": "file_resource_ingestion_guard", + "columns": [ + "organization_id", + "source_id", + "resource_ref" + ] + } + }, + { + "name": "fk_file_revision_replacement_plan_previous_same_organization", + "columns": [ + "organization_id", + "resource_ref", + "previous_revision_id" + ], + "references": { + "table": "context_revision", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ] + } + }, + { + "name": "fk_file_revision_replacement_plan_replacement_same_organization", + "columns": [ + "organization_id", + "resource_ref", + "replacement_revision_id" + ], + "references": { + "table": "context_revision", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ] + } + }, + { + "name": "fk_file_revision_replacement_plan_acquisition_same_organization", + "columns": [ + "organization_id", + "acquisition_id", + "source_id" + ], + "references": { + "table": "file_acquisition", + "columns": [ + "organization_id", + "acquisition_id", + "source_id" + ] + } + }, + { + "name": "fk_file_revision_replacement_plan_job_same_organization", + "columns": [ + "organization_id", + "job_id" + ], + "references": { + "table": "file_import_job", + "columns": [ + "organization_id", + "job_id" + ] + } + } + ], + "checkConstraints": [ + { + "name": "ck_file_revision_replacement_plan_distinct_revisions", + "expression": "previous_revision_id <> replacement_revision_id" + }, + { + "name": "ck_file_revision_replacement_plan_identity_digest", + "expression": "content_identity_digest ~ '^[0-9a-f]{64}$'" + } + ], + "rowLevelSecurity": { + "enabled": true, + "forced": true, + "policies": [ + { + "name": "file_revision_replacement_plan_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "file_revision_replacement_plan_file_import_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_revision_replacement_plan_file_import_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + } + ] + }, + "immutableRows": { + "trigger": "file_revision_replacement_plan_immutable", + "function": "context_content_reject_mutation", + "events": [ + "UPDATE", + "DELETE" + ], + "sqlstate": "55000" + }, + "functionOnlyMutation": { + "databaseFunctions": [ + "context_worker_stage_file_replacement", + "context_worker_stage_structural_file_replacement", + "context_worker_index_file_publication" + ], + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, + "permittedOperations": { + "context_engine_control": [], + "context_engine_runtime": [], + "context_engine_worker": [ + "EXECUTE context_worker_stage_file_replacement", + "EXECUTE context_worker_stage_structural_file_replacement", + "EXECUTE context_worker_index_file_publication" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT" + ] + }, + "partitions": [], + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "WORKER-LEASE-007" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-008", + "PG-FILE-REPLACEMENT-026" + ] + }, + { + "name": "file_revision_supersession", + "classification": "tenant_owned", + "nonOwnerEvidence": { + "evidenceId": "PG-FILE-REPLACEMENT-026", + "selector": { + "table": "file_revision_supersession" + } + }, + "purpose": "Immutable activation lineage retaining each superseded Revision until an explicit future cleanup policy", + "organizationColumn": "organization_id", + "organizationInclusiveKeys": [ + { + "name": "pk_file_revision_supersession", + "kind": "primary_key", + "columns": [ + "organization_id", + "resource_ref", + "superseded_revision_id" + ] + }, + { + "name": "uq_file_revision_supersession_replacement", + "kind": "unique", + "columns": [ + "organization_id", + "resource_ref", + "replacement_revision_id" + ] + } + ], + "foreignKeys": [ + { + "name": "fk_file_revision_supersession_plan_same_organization", + "columns": [ + "organization_id", + "resource_ref", + "replacement_revision_id" + ], + "references": { + "table": "file_revision_replacement_plan", + "columns": [ + "organization_id", + "resource_ref", + "replacement_revision_id" + ] + } + }, + { + "name": "fk_file_revision_supersession_previous_same_organization", + "columns": [ + "organization_id", + "resource_ref", + "superseded_revision_id" + ], + "references": { + "table": "context_revision", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ] + } + }, + { + "name": "fk_file_revision_supersession_acquisition_same_organization", + "columns": [ + "organization_id", + "acquisition_id" + ], + "references": { + "table": "file_acquisition", + "columns": [ + "organization_id", + "acquisition_id" + ] + } + }, + { + "name": "fk_file_revision_supersession_job_same_organization", + "columns": [ + "organization_id", + "job_id" + ], + "references": { + "table": "file_import_job", + "columns": [ + "organization_id", + "job_id" + ] + } + } + ], + "checkConstraints": [ + { + "name": "ck_file_revision_supersession_distinct_revisions", + "expression": "superseded_revision_id <> replacement_revision_id" + }, + { + "name": "ck_file_revision_supersession_retention_state", + "expression": "retention_state = 'retained_until_explicit_cleanup'" + } + ], + "rowLevelSecurity": { + "enabled": true, + "forced": true, + "policies": [ + { + "name": "file_revision_supersession_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "file_revision_supersession_file_import_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_revision_supersession_file_import_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + } + ] + }, + "immutableRows": { + "trigger": "file_revision_supersession_immutable", + "function": "context_content_reject_mutation", + "events": [ + "UPDATE", + "DELETE" + ], + "sqlstate": "55000" + }, + "functionOnlyMutation": { + "databaseFunctions": [ + "context_worker_activate_file_replacement", + "context_worker_activate_recoverable_file_publication" + ], + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, + "permittedOperations": { + "context_engine_control": [], + "context_engine_runtime": [], + "context_engine_worker": [ + "EXECUTE context_worker_activate_file_replacement", + "EXECUTE context_worker_activate_recoverable_file_publication" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT" + ] + }, + "retention": { + "supersededRevision": "retained_until_explicit_cleanup", + "cleanupAuthority": "not active in Issue #26" + }, + "partitions": [], + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "WORKER-LEASE-007" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-008", + "PG-FILE-REPLACEMENT-026" + ] + }, + { + "name": "file_resource_cleanup_intent", + "classification": "tenant_owned", + "nonOwnerEvidence": { + "evidenceId": "PG-FILE-TOMBSTONE-028", + "selector": { + "table": "file_resource_cleanup_intent" + } + }, + "purpose": "Immutable pending physical-cleanup obligation committed atomically with one File Resource tombstone and Organization Policy Epoch", + "organizationColumn": "organization_id", + "organizationInclusiveKeys": [ + { + "name": "pk_file_resource_cleanup_intent", + "kind": "primary_key", + "columns": [ + "organization_id", + "cleanup_intent_id" + ] + }, + { + "name": "uq_file_resource_cleanup_intent_resource", + "kind": "unique", + "columns": [ + "organization_id", + "resource_ref" + ] + }, + { + "name": "uq_file_resource_cleanup_intent_event", + "kind": "unique", + "columns": [ + "organization_id", + "event_ref" + ] + }, + { + "name": "uq_file_resource_cleanup_intent_progress_lineage", + "kind": "unique", + "columns": [ + "organization_id", + "cleanup_intent_id", + "source_id", + "resource_ref", + "revision_id" + ] + } + ], + "foreignKeys": [ + { + "name": "fk_file_resource_cleanup_intent_source_same_organization", + "columns": [ + "organization_id", + "source_id" + ], + "references": { + "table": "context_source", + "columns": [ + "organization_id", + "source_id" + ] + } + }, + { + "name": "fk_file_resource_cleanup_intent_revision_same_organization", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ], + "references": { + "table": "context_revision", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ] + } + } + ], + "checkConstraints": [ + { + "name": "ck_file_resource_cleanup_intent_resource_ref", + "expression": "resource_ref ~ '^resource:file:[0-9a-f]{64}$'" + }, + { + "name": "ck_file_resource_cleanup_intent_event_ref", + "expression": "event_ref ~ '^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$'" + }, + { + "name": "ck_file_resource_cleanup_intent_event_sequence", + "expression": "event_sequence BETWEEN 1 AND 9223372036854775807" + }, + { + "name": "ck_file_resource_cleanup_intent_policy_epoch", + "expression": "policy_epoch BETWEEN 1 AND 9223372036854775807" + }, + { + "name": "ck_file_resource_cleanup_intent_state", + "expression": "state = 'pending'" + } + ], + "rowLevelSecurity": { + "enabled": true, + "forced": true, + "policies": [ + { + "name": "file_resource_cleanup_intent_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "file_resource_cleanup_intent_access_policy_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_access_policy_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_resource_cleanup_intent_access_policy_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_access_policy_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + } + ] + }, + "immutableRows": { + "trigger": "file_resource_cleanup_intent_immutable", + "function": "context_content_reject_mutation", + "events": [ + "UPDATE", + "DELETE" + ], + "sqlstate": "55000" + }, + "functionOnlyMutation": { + "databaseFunction": "context_control_tombstone_file_resource", + "role": "context_engine_control", + "definerRole": "context_engine_access_policy_definer", + "directTableMutationAllowed": false + }, + "permittedOperations": { + "context_engine_access_policy_definer": [ + "SELECT", + "INSERT" + ], + "context_engine_control": [ + "EXECUTE context_control_tombstone_file_resource" + ], + "context_engine_runtime": [], + "context_engine_worker": [] + }, + "retention": { + "state": "pending", + "physicalCleanupCompletion": "not active in Issue #28", + "sourceContent": "none" + }, + "partitions": [], + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "INDEX-NOT-AUTHORITY-005", + "REVOCATION-006" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-008", + "PG-FILE-TOMBSTONE-028" + ] + }, + { + "name": "file_source_cleanup_intent", + "classification": "tenant_owned", + "nonOwnerEvidence": { + "evidenceId": "PG-FILE-SOURCE-OFFBOARD-030", + "selector": { + "table": "file_source_cleanup_intent" + } + }, + "purpose": "Immutable pending physical-cleanup obligation committed atomically with File source disable, Policy Epoch advance, and outstanding-job cancellation", + "organizationColumn": "organization_id", + "organizationInclusiveKeys": [ + { + "name": "pk_file_source_cleanup_intent", + "kind": "primary_key", + "columns": [ + "organization_id", + "cleanup_intent_id" + ] + }, + { + "name": "uq_file_source_cleanup_intent_source", + "kind": "unique", + "columns": [ + "organization_id", + "source_id" + ] + } + ], + "foreignKeys": [ + { + "name": "fk_file_source_cleanup_intent_organization", + "columns": [ + "organization_id" + ], + "references": { + "table": "organization", + "columns": [ + "organization_id" + ] + } + }, + { + "name": "fk_file_source_cleanup_intent_version_exact", + "columns": [ + "organization_id", + "source_id", + "source_version_id" + ], + "references": { + "table": "source_version", + "columns": [ + "organization_id", + "source_id", + "version_id" + ] + } + } + ], + "checkConstraints": [ + { + "name": "ck_file_source_cleanup_intent_epoch", + "expression": "policy_epoch BETWEEN 1 AND 9223372036854775807" + }, + { + "name": "ck_file_source_cleanup_intent_state", + "expression": "cleanup_state = 'pending'" + }, + { + "name": "ck_file_source_cleanup_intent_counts", + "expression": "cancelled_job_count and retained_resource_count fit nonnegative signed bigint" + } + ], + "rowLevelSecurity": { + "enabled": true, + "forced": true, + "policies": [ + { + "name": "file_source_cleanup_intent_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "file_source_cleanup_intent_access_policy_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_access_policy_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_source_cleanup_intent_access_policy_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_access_policy_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + } + ] + }, + "immutableRows": { + "trigger": "file_source_cleanup_intent_immutable", + "function": "context_content_reject_mutation", + "events": [ + "UPDATE", + "DELETE" + ], + "sqlstate": "55000" + }, + "functionOnlyMutation": { + "databaseFunction": "context_control_offboard_file_source", + "role": "context_engine_control", + "definerRole": "context_engine_access_policy_definer", + "directTableMutationAllowed": false + }, + "permittedOperations": { + "context_engine_access_policy_definer": [ + "SELECT", + "INSERT" + ], + "context_engine_control": [ + "EXECUTE context_control_offboard_file_source" + ], + "context_engine_runtime": [], + "context_engine_worker": [] }, - "rowLevelSecurity": {"enabled": true, "forced": true, "policies": [ - {"name": "file_revision_snapshot_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "file_revision_snapshot_file_import_definer_insert", "command": "INSERT", "roles": ["context_engine_worker_lease_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_revision_snapshot_file_noop_definer_select", "command": "SELECT", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"} - ]}, - "immutableRows": {"trigger": "file_revision_snapshot_immutable", "function": "context_content_reject_mutation", "events": ["UPDATE", "DELETE"], "sqlstate": "55000"}, - "functionOnlyMutation": {"databaseFunction": "context_worker_prepare_file_publication", "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_control": [], "context_engine_runtime": [], "context_engine_worker": ["EXECUTE context_worker_publish_file_import_v2", "EXECUTE context_worker_publish_structural_file_import_v2", "EXECUTE context_worker_prepare_file_publication"], "context_engine_worker_lease_definer": ["SELECT", "INSERT"]}, - "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "TRACE-REDACTION-012"], - "negativeTestIds": ["DB-001", "DB-004", "DB-008", "WORKER-LEASE-007"] - }, - { - "name": "revision_publication_event", - "classification": "tenant_owned", - "nonOwnerEvidence": { - "evidenceId": "PG-FILE-IMPORT-023", - "selector": {"table": "revision_publication_event"} + "retention": { + "state": "pending", + "physicalCleanupCompletion": "not active in Issue #30", + "sourceContent": "none" }, - "purpose": "Immutable ordered prepared-indexed-active publication evidence for one Revision", - "organizationColumn": "organization_id", - "organizationInclusiveKeys": [ - {"name": "pk_revision_publication_event", "kind": "primary_key", "columns": ["organization_id", "resource_ref", "revision_id", "ordinal"]}, - {"name": "uq_revision_publication_event_state", "kind": "unique", "columns": ["organization_id", "resource_ref", "revision_id", "state"]} - ], - "foreignKeys": [ - {"name": "fk_revision_publication_event_revision_same_organization", "columns": ["organization_id", "resource_ref", "revision_id"], "references": {"table": "context_revision", "columns": ["organization_id", "resource_ref", "revision_id"]}} - ], - "checkConstraints": [ - {"name": "ck_revision_publication_event_order", "expression": "(ordinal, state) IN ((0, 'prepared'), (1, 'indexed'), (2, 'active'))"} - ], - "rowLevelSecurity": {"enabled": true, "forced": true, "policies": [ - {"name": "revision_publication_event_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "revision_publication_event_file_import_definer_insert", "command": "INSERT", "roles": ["context_engine_worker_lease_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "revision_publication_event_file_noop_definer_select", "command": "SELECT", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "revision_publication_event_current_user_actor", "command": "SELECT", "roles": ["context_engine_runtime"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'user' AND EXISTS (SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = revision_publication_event.organization_id AND actor_membership.user_id = NULLIF(current_setting('app.user_id', true), '')::uuid AND actor_membership.membership_id = NULLIF(current_setting('app.membership_id', true), '')::uuid AND actor_membership.membership_version = NULLIF(current_setting('app.membership_version', true), '')::bigint AND actor_membership.status = 'active' AND actor_membership.valid_from <= NULLIF(current_setting('app.checked_at', true), '')::timestamptz AND (actor_membership.valid_until IS NULL OR actor_membership.valid_until > NULLIF(current_setting('app.checked_at', true), '')::timestamptz)) AND EXISTS (SELECT 1 FROM public.resource_access_policy AS access_policy WHERE access_policy.organization_id = revision_publication_event.organization_id AND access_policy.resource_ref = revision_publication_event.resource_ref AND access_policy.principal_ref = current_setting('app.principal_ref', true) AND access_policy.access_state = 'allowed')"} - ]}, - "immutableRows": {"trigger": "revision_publication_event_immutable", "function": "context_content_reject_mutation", "events": ["UPDATE", "DELETE"], "sqlstate": "55000"}, - "functionOnlyMutation": {"databaseFunctions": ["context_worker_prepare_file_publication", "context_worker_index_file_publication", "context_worker_activate_recoverable_file_publication"], "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_control": [], "context_engine_runtime": ["SELECT"], "context_engine_worker": ["EXECUTE context_worker_publish_file_import_v2", "EXECUTE context_worker_publish_structural_file_import_v2", "EXECUTE context_worker_prepare_file_publication", "EXECUTE context_worker_index_file_publication", "EXECUTE context_worker_activate_recoverable_file_publication"], "context_engine_worker_lease_definer": ["SELECT", "INSERT"]}, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "TRACE-REDACTION-012"], - "negativeTestIds": ["DB-001", "DB-004", "DB-008", "WORKER-LEASE-007"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "INDEX-NOT-AUTHORITY-005", + "REVOCATION-006", + "WORKER-LEASE-007" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-008", + "PG-FILE-SOURCE-OFFBOARD-030" + ] }, { - "name": "exact_phrase_candidate", + "name": "file_source_acquisition_checkpoint", "classification": "tenant_owned", "nonOwnerEvidence": { - "evidenceId": "PG-FILE-IMPORT-023", - "selector": {"table": "exact_phrase_candidate"} + "evidenceId": "PG-FILE-PROGRESS-029", + "selector": { + "table": "file_source_acquisition_checkpoint" + } }, - "purpose": "Content-free deterministic exact-phrase CandidateIndex; never an authorization authority", + "purpose": "Immutable Organization/Source sequence for each durably accepted File import or tombstone change", "organizationColumn": "organization_id", "organizationInclusiveKeys": [ - {"name": "pk_exact_phrase_candidate", "kind": "primary_key", "columns": ["organization_id", "phrase_digest", "resource_ref", "revision_id", "fragment_ref"]} + { + "name": "pk_file_source_acquisition_checkpoint", + "kind": "primary_key", + "columns": [ + "organization_id", + "source_id", + "sequence" + ] + }, + { + "name": "uq_file_source_acquisition_checkpoint_exact", + "kind": "unique", + "columns": [ + "organization_id", + "source_id", + "sequence", + "checkpoint_ref", + "change_kind" + ] + }, + { + "name": "uq_file_source_acquisition_checkpoint_ref", + "kind": "unique", + "columns": [ + "organization_id", + "checkpoint_ref" + ] + }, + { + "name": "uq_file_source_acquisition_checkpoint_acquisition", + "kind": "unique", + "columns": [ + "organization_id", + "acquisition_id" + ] + }, + { + "name": "uq_file_source_acquisition_checkpoint_cleanup", + "kind": "unique", + "columns": [ + "organization_id", + "cleanup_intent_id" + ] + } ], "foreignKeys": [ - {"name": "fk_exact_phrase_candidate_fragment_same_organization", "columns": ["organization_id", "resource_ref", "revision_id", "fragment_ref"], "references": {"table": "context_fragment", "columns": ["organization_id", "resource_ref", "revision_id", "fragment_ref"]}} + { + "name": "fk_file_source_acquisition_checkpoint_source_same_organization", + "columns": [ + "organization_id", + "source_id" + ], + "references": { + "table": "context_source", + "columns": [ + "organization_id", + "source_id" + ] + } + }, + { + "name": "fk_file_source_acquisition_checkpoint_job_exact", + "columns": [ + "organization_id", + "job_id", + "acquisition_id", + "source_id" + ], + "references": { + "table": "file_import_job", + "columns": [ + "organization_id", + "job_id", + "acquisition_id", + "source_id" + ] + } + }, + { + "name": "fk_file_source_acquisition_checkpoint_cleanup_exact", + "columns": [ + "organization_id", + "cleanup_intent_id", + "source_id", + "resource_ref", + "revision_id" + ], + "references": { + "table": "file_resource_cleanup_intent", + "columns": [ + "organization_id", + "cleanup_intent_id", + "source_id", + "resource_ref", + "revision_id" + ] + } + } ], "checkConstraints": [ - {"name": "ck_exact_phrase_candidate_digest", "expression": "phrase_digest ~ '^[0-9a-f]{64}$'"} + { + "name": "ck_file_source_acquisition_checkpoint_sequence", + "expression": "sequence BETWEEN 1 AND 9223372036854775807" + }, + { + "name": "ck_file_source_acquisition_checkpoint_ref", + "expression": "checkpoint_ref is facp_ plus one SHA-256 hex digest" + }, + { + "name": "ck_file_source_acquisition_checkpoint_lineage", + "expression": "exactly one complete file_import or file_tombstone durable lineage is present" + } ], "rowLevelSecurity": { "enabled": true, "forced": true, "policies": [ - {"name": "exact_phrase_candidate_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "exact_phrase_candidate_file_import_definer_insert", "command": "INSERT", "roles": ["context_engine_worker_lease_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "exact_phrase_candidate_file_noop_definer_select", "command": "SELECT", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "exact_phrase_candidate_runtime", "command": "SELECT", "roles": ["context_engine_runtime"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid AND current_setting('app.actor_kind', true) = 'user' AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL AND NULLIF(current_setting('app.authentication_binding_ref', true), '') IS NOT NULL AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL AND EXISTS (SELECT 1 FROM public.membership AS actor_membership WHERE actor_membership.organization_id = exact_phrase_candidate.organization_id AND actor_membership.user_id = NULLIF(current_setting('app.user_id', true), '')::uuid AND actor_membership.membership_id = NULLIF(current_setting('app.membership_id', true), '')::uuid AND actor_membership.membership_version = NULLIF(current_setting('app.membership_version', true), '')::bigint AND actor_membership.status = 'active' AND actor_membership.valid_from <= NULLIF(current_setting('app.checked_at', true), '')::timestamptz AND (actor_membership.valid_until IS NULL OR actor_membership.valid_until > NULLIF(current_setting('app.checked_at', true), '')::timestamptz))"} + { + "name": "file_source_acquisition_checkpoint_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "file_source_acquisition_checkpoint_file_progress_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_source_acquisition_checkpoint_file_progress_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + } ] }, - "immutableRows": {"trigger": "exact_phrase_candidate_immutable", "function": "context_content_reject_mutation", "events": ["UPDATE", "DELETE"], "sqlstate": "55000"}, - "functionOnlyMutation": {"databaseFunction": "context_worker_index_file_publication", "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_control": [], "context_engine_runtime": ["SELECT"], "context_engine_worker": ["EXECUTE context_worker_publish_file_import_v2", "EXECUTE context_worker_publish_structural_file_import_v2", "EXECUTE context_worker_index_file_publication"], "context_engine_worker_lease_definer": ["SELECT", "INSERT"]}, - "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "INDEX-NOT-AUTHORITY-005"], - "negativeTestIds": ["DB-001", "DB-002", "DB-004", "DB-008", "DB-009", "DB-010", "PG-INDEX-NOT-AUTHORITY-005"] - }, - { - "name": "file_revision_replacement_plan", - "classification": "tenant_owned", - "nonOwnerEvidence": { - "evidenceId": "PG-FILE-REPLACEMENT-026", - "selector": {"table": "file_revision_replacement_plan"} + "immutableRows": { + "trigger": "file_source_acquisition_checkpoint_immutable", + "function": "context_content_reject_mutation", + "events": [ + "UPDATE", + "DELETE" + ], + "sqlstate": "55000" }, - "purpose": "Immutable durable ready boundary binding one complete replacement Revision to the exact old active Revision and File import job", - "organizationColumn": "organization_id", - "organizationInclusiveKeys": [ - {"name": "pk_file_revision_replacement_plan", "kind": "primary_key", "columns": ["organization_id", "resource_ref", "replacement_revision_id"]}, - {"name": "uq_file_revision_replacement_plan_job", "kind": "unique", "columns": ["organization_id", "job_id"]}, - {"name": "uq_file_revision_replacement_plan_previous", "kind": "unique", "columns": ["organization_id", "resource_ref", "previous_revision_id"]} - ], - "foreignKeys": [ - {"name": "fk_file_revision_replacement_plan_guard_same_organization", "columns": ["organization_id", "source_id", "resource_ref"], "references": {"table": "file_resource_ingestion_guard", "columns": ["organization_id", "source_id", "resource_ref"]}}, - {"name": "fk_file_revision_replacement_plan_previous_same_organization", "columns": ["organization_id", "resource_ref", "previous_revision_id"], "references": {"table": "context_revision", "columns": ["organization_id", "resource_ref", "revision_id"]}}, - {"name": "fk_file_revision_replacement_plan_replacement_same_organization", "columns": ["organization_id", "resource_ref", "replacement_revision_id"], "references": {"table": "context_revision", "columns": ["organization_id", "resource_ref", "revision_id"]}}, - {"name": "fk_file_revision_replacement_plan_acquisition_same_organization", "columns": ["organization_id", "acquisition_id", "source_id"], "references": {"table": "file_acquisition", "columns": ["organization_id", "acquisition_id", "source_id"]}}, - {"name": "fk_file_revision_replacement_plan_job_same_organization", "columns": ["organization_id", "job_id"], "references": {"table": "file_import_job", "columns": ["organization_id", "job_id"]}} - ], - "checkConstraints": [ - {"name": "ck_file_revision_replacement_plan_distinct_revisions", "expression": "previous_revision_id <> replacement_revision_id"}, - {"name": "ck_file_revision_replacement_plan_identity_digest", "expression": "content_identity_digest ~ '^[0-9a-f]{64}$'"} - ], - "rowLevelSecurity": {"enabled": true, "forced": true, "policies": [ - {"name": "file_revision_replacement_plan_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "file_revision_replacement_plan_file_import_definer_select", "command": "SELECT", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_revision_replacement_plan_file_import_definer_insert", "command": "INSERT", "roles": ["context_engine_worker_lease_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"} - ]}, - "immutableRows": {"trigger": "file_revision_replacement_plan_immutable", "function": "context_content_reject_mutation", "events": ["UPDATE", "DELETE"], "sqlstate": "55000"}, - "functionOnlyMutation": {"databaseFunctions": ["context_worker_stage_file_replacement", "context_worker_stage_structural_file_replacement", "context_worker_index_file_publication"], "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_control": [], "context_engine_runtime": [], "context_engine_worker": ["EXECUTE context_worker_stage_file_replacement", "EXECUTE context_worker_stage_structural_file_replacement", "EXECUTE context_worker_index_file_publication"], "context_engine_worker_lease_definer": ["SELECT", "INSERT"]}, - "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "WORKER-LEASE-007"], - "negativeTestIds": ["DB-001", "DB-004", "DB-008", "PG-FILE-REPLACEMENT-026"] - }, - { - "name": "file_revision_supersession", - "classification": "tenant_owned", - "nonOwnerEvidence": { - "evidenceId": "PG-FILE-REPLACEMENT-026", - "selector": {"table": "file_revision_supersession"} + "functionOnlyMutation": { + "databaseFunctions": [ + "context_file_source_checkpoint_import_job", + "context_file_source_checkpoint_tombstone" + ], + "causalDatabaseFunctions": [ + "context_control_prepare_file_import", + "context_control_tombstone_file_resource" + ], + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false }, - "purpose": "Immutable activation lineage retaining each superseded Revision until an explicit future cleanup policy", - "organizationColumn": "organization_id", - "organizationInclusiveKeys": [ - {"name": "pk_file_revision_supersession", "kind": "primary_key", "columns": ["organization_id", "resource_ref", "superseded_revision_id"]}, - {"name": "uq_file_revision_supersession_replacement", "kind": "unique", "columns": ["organization_id", "resource_ref", "replacement_revision_id"]} - ], - "foreignKeys": [ - {"name": "fk_file_revision_supersession_plan_same_organization", "columns": ["organization_id", "resource_ref", "replacement_revision_id"], "references": {"table": "file_revision_replacement_plan", "columns": ["organization_id", "resource_ref", "replacement_revision_id"]}}, - {"name": "fk_file_revision_supersession_previous_same_organization", "columns": ["organization_id", "resource_ref", "superseded_revision_id"], "references": {"table": "context_revision", "columns": ["organization_id", "resource_ref", "revision_id"]}}, - {"name": "fk_file_revision_supersession_acquisition_same_organization", "columns": ["organization_id", "acquisition_id"], "references": {"table": "file_acquisition", "columns": ["organization_id", "acquisition_id"]}}, - {"name": "fk_file_revision_supersession_job_same_organization", "columns": ["organization_id", "job_id"], "references": {"table": "file_import_job", "columns": ["organization_id", "job_id"]}} - ], - "checkConstraints": [ - {"name": "ck_file_revision_supersession_distinct_revisions", "expression": "superseded_revision_id <> replacement_revision_id"}, - {"name": "ck_file_revision_supersession_retention_state", "expression": "retention_state = 'retained_until_explicit_cleanup'"} - ], - "rowLevelSecurity": {"enabled": true, "forced": true, "policies": [ - {"name": "file_revision_supersession_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "file_revision_supersession_file_import_definer_select", "command": "SELECT", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_revision_supersession_file_import_definer_insert", "command": "INSERT", "roles": ["context_engine_worker_lease_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"} - ]}, - "immutableRows": {"trigger": "file_revision_supersession_immutable", "function": "context_content_reject_mutation", "events": ["UPDATE", "DELETE"], "sqlstate": "55000"}, - "functionOnlyMutation": {"databaseFunctions": ["context_worker_activate_file_replacement", "context_worker_activate_recoverable_file_publication"], "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_control": [], "context_engine_runtime": [], "context_engine_worker": ["EXECUTE context_worker_activate_file_replacement", "EXECUTE context_worker_activate_recoverable_file_publication"], "context_engine_worker_lease_definer": ["SELECT", "INSERT"]}, - "retention": {"supersededRevision": "retained_until_explicit_cleanup", "cleanupAuthority": "not active in Issue #26"}, - "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "WORKER-LEASE-007"], - "negativeTestIds": ["DB-001", "DB-004", "DB-008", "PG-FILE-REPLACEMENT-026"] - }, - { - "name": "file_resource_cleanup_intent", - "classification": "tenant_owned", - "nonOwnerEvidence": { - "evidenceId": "PG-FILE-TOMBSTONE-028", - "selector": {"table": "file_resource_cleanup_intent"} + "permittedOperations": { + "context_engine_control": [ + "EXECUTE context_control_prepare_file_import", + "EXECUTE context_control_read_file_source_progress", + "EXECUTE context_control_tombstone_file_resource" + ], + "context_engine_runtime": [], + "context_engine_worker": [], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT" + ] }, - "purpose": "Immutable pending physical-cleanup obligation committed atomically with one File Resource tombstone and Organization Policy Epoch", - "organizationColumn": "organization_id", - "organizationInclusiveKeys": [ - {"name": "pk_file_resource_cleanup_intent", "kind": "primary_key", "columns": ["organization_id", "cleanup_intent_id"]}, - {"name": "uq_file_resource_cleanup_intent_resource", "kind": "unique", "columns": ["organization_id", "resource_ref"]}, - {"name": "uq_file_resource_cleanup_intent_event", "kind": "unique", "columns": ["organization_id", "event_ref"]}, - {"name": "uq_file_resource_cleanup_intent_progress_lineage", "kind": "unique", "columns": ["organization_id", "cleanup_intent_id", "source_id", "resource_ref", "revision_id"]} - ], - "foreignKeys": [ - {"name": "fk_file_resource_cleanup_intent_source_same_organization", "columns": ["organization_id", "source_id"], "references": {"table": "context_source", "columns": ["organization_id", "source_id"]}}, - {"name": "fk_file_resource_cleanup_intent_revision_same_organization", "columns": ["organization_id", "resource_ref", "revision_id"], "references": {"table": "context_revision", "columns": ["organization_id", "resource_ref", "revision_id"]}} - ], - "checkConstraints": [ - {"name": "ck_file_resource_cleanup_intent_resource_ref", "expression": "resource_ref ~ '^resource:file:[0-9a-f]{64}$'"}, - {"name": "ck_file_resource_cleanup_intent_event_ref", "expression": "event_ref ~ '^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$'"}, - {"name": "ck_file_resource_cleanup_intent_event_sequence", "expression": "event_sequence BETWEEN 1 AND 9223372036854775807"}, - {"name": "ck_file_resource_cleanup_intent_policy_epoch", "expression": "policy_epoch BETWEEN 1 AND 9223372036854775807"}, - {"name": "ck_file_resource_cleanup_intent_state", "expression": "state = 'pending'"} - ], - "rowLevelSecurity": {"enabled": true, "forced": true, "policies": [ - {"name": "file_resource_cleanup_intent_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "file_resource_cleanup_intent_access_policy_definer_select", "command": "SELECT", "roles": ["context_engine_access_policy_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_resource_cleanup_intent_access_policy_definer_insert", "command": "INSERT", "roles": ["context_engine_access_policy_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"} - ]}, - "immutableRows": {"trigger": "file_resource_cleanup_intent_immutable", "function": "context_content_reject_mutation", "events": ["UPDATE", "DELETE"], "sqlstate": "55000"}, - "functionOnlyMutation": {"databaseFunction": "context_control_tombstone_file_resource", "role": "context_engine_control", "definerRole": "context_engine_access_policy_definer", "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_access_policy_definer": ["SELECT", "INSERT"], "context_engine_control": ["EXECUTE context_control_tombstone_file_resource"], "context_engine_runtime": [], "context_engine_worker": []}, - "retention": {"state": "pending", "physicalCleanupCompletion": "not active in Issue #28", "sourceContent": "none"}, - "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "INDEX-NOT-AUTHORITY-005", "REVOCATION-006"], - "negativeTestIds": ["DB-001", "DB-004", "DB-008", "PG-FILE-TOMBSTONE-028"] - }, - { - "name": "file_source_cleanup_intent", - "classification": "tenant_owned", - "nonOwnerEvidence": {"evidenceId": "PG-FILE-SOURCE-OFFBOARD-030", "selector": {"table": "file_source_cleanup_intent"}}, - "purpose": "Immutable pending physical-cleanup obligation committed atomically with File source disable, Policy Epoch advance, and outstanding-job cancellation", - "organizationColumn": "organization_id", - "organizationInclusiveKeys": [ - {"name": "pk_file_source_cleanup_intent", "kind": "primary_key", "columns": ["organization_id", "cleanup_intent_id"]}, - {"name": "uq_file_source_cleanup_intent_source", "kind": "unique", "columns": ["organization_id", "source_id"]} - ], - "foreignKeys": [ - {"name": "fk_file_source_cleanup_intent_organization", "columns": ["organization_id"], "references": {"table": "organization", "columns": ["organization_id"]}}, - {"name": "fk_file_source_cleanup_intent_version_exact", "columns": ["organization_id", "source_id", "source_version_id"], "references": {"table": "source_version", "columns": ["organization_id", "source_id", "version_id"]}} - ], - "checkConstraints": [ - {"name": "ck_file_source_cleanup_intent_epoch", "expression": "policy_epoch BETWEEN 1 AND 9223372036854775807"}, - {"name": "ck_file_source_cleanup_intent_state", "expression": "cleanup_state = 'pending'"}, - {"name": "ck_file_source_cleanup_intent_counts", "expression": "cancelled_job_count and retained_resource_count fit nonnegative signed bigint"} - ], - "rowLevelSecurity": {"enabled": true, "forced": true, "policies": [ - {"name": "file_source_cleanup_intent_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "file_source_cleanup_intent_access_policy_definer_select", "command": "SELECT", "roles": ["context_engine_access_policy_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_source_cleanup_intent_access_policy_definer_insert", "command": "INSERT", "roles": ["context_engine_access_policy_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"} - ]}, - "immutableRows": {"trigger": "file_source_cleanup_intent_immutable", "function": "context_content_reject_mutation", "events": ["UPDATE", "DELETE"], "sqlstate": "55000"}, - "functionOnlyMutation": {"databaseFunction": "context_control_offboard_file_source", "role": "context_engine_control", "definerRole": "context_engine_access_policy_definer", "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_access_policy_definer": ["SELECT", "INSERT"], "context_engine_control": ["EXECUTE context_control_offboard_file_source"], "context_engine_runtime": [], "context_engine_worker": []}, - "retention": {"state": "pending", "physicalCleanupCompletion": "not active in Issue #30", "sourceContent": "none"}, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "INDEX-NOT-AUTHORITY-005", "REVOCATION-006", "WORKER-LEASE-007"], - "negativeTestIds": ["DB-001", "DB-004", "DB-008", "PG-FILE-SOURCE-OFFBOARD-030"] - }, - { - "name": "file_source_acquisition_checkpoint", - "classification": "tenant_owned", - "nonOwnerEvidence": {"evidenceId": "PG-FILE-PROGRESS-029", "selector": {"table": "file_source_acquisition_checkpoint"}}, - "purpose": "Immutable Organization/Source sequence for each durably accepted File import or tombstone change", - "organizationColumn": "organization_id", - "organizationInclusiveKeys": [ - {"name": "pk_file_source_acquisition_checkpoint", "kind": "primary_key", "columns": ["organization_id", "source_id", "sequence"]}, - {"name": "uq_file_source_acquisition_checkpoint_exact", "kind": "unique", "columns": ["organization_id", "source_id", "sequence", "checkpoint_ref", "change_kind"]}, - {"name": "uq_file_source_acquisition_checkpoint_ref", "kind": "unique", "columns": ["organization_id", "checkpoint_ref"]}, - {"name": "uq_file_source_acquisition_checkpoint_acquisition", "kind": "unique", "columns": ["organization_id", "acquisition_id"]}, - {"name": "uq_file_source_acquisition_checkpoint_cleanup", "kind": "unique", "columns": ["organization_id", "cleanup_intent_id"]} - ], - "foreignKeys": [ - {"name": "fk_file_source_acquisition_checkpoint_source_same_organization", "columns": ["organization_id", "source_id"], "references": {"table": "context_source", "columns": ["organization_id", "source_id"]}}, - {"name": "fk_file_source_acquisition_checkpoint_job_exact", "columns": ["organization_id", "job_id", "acquisition_id", "source_id"], "references": {"table": "file_import_job", "columns": ["organization_id", "job_id", "acquisition_id", "source_id"]}}, - {"name": "fk_file_source_acquisition_checkpoint_cleanup_exact", "columns": ["organization_id", "cleanup_intent_id", "source_id", "resource_ref", "revision_id"], "references": {"table": "file_resource_cleanup_intent", "columns": ["organization_id", "cleanup_intent_id", "source_id", "resource_ref", "revision_id"]}} + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "WORKER-LEASE-007" ], - "checkConstraints": [ - {"name": "ck_file_source_acquisition_checkpoint_sequence", "expression": "sequence BETWEEN 1 AND 9223372036854775807"}, - {"name": "ck_file_source_acquisition_checkpoint_ref", "expression": "checkpoint_ref is facp_ plus one SHA-256 hex digest"}, - {"name": "ck_file_source_acquisition_checkpoint_lineage", "expression": "exactly one complete file_import or file_tombstone durable lineage is present"} - ], - "rowLevelSecurity": {"enabled": true, "forced": true, "policies": [ - {"name": "file_source_acquisition_checkpoint_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "file_source_acquisition_checkpoint_file_progress_definer_select", "command": "SELECT", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_source_acquisition_checkpoint_file_progress_definer_insert", "command": "INSERT", "roles": ["context_engine_worker_lease_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"} - ]}, - "immutableRows": {"trigger": "file_source_acquisition_checkpoint_immutable", "function": "context_content_reject_mutation", "events": ["UPDATE", "DELETE"], "sqlstate": "55000"}, - "functionOnlyMutation": {"databaseFunctions": ["context_file_source_checkpoint_import_job", "context_file_source_checkpoint_tombstone"], "causalDatabaseFunctions": ["context_control_prepare_file_import", "context_control_tombstone_file_resource"], "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_control": ["EXECUTE context_control_prepare_file_import", "EXECUTE context_control_read_file_source_progress", "EXECUTE context_control_tombstone_file_resource"], "context_engine_runtime": [], "context_engine_worker": [], "context_engine_worker_lease_definer": ["SELECT", "INSERT"]}, - "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "WORKER-LEASE-007"], - "negativeTestIds": ["DB-001", "DB-004", "DB-008", "PG-FILE-PROGRESS-029"] + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-008", + "PG-FILE-PROGRESS-029" + ] }, { "name": "file_source_publish_watermark", "classification": "tenant_owned", - "nonOwnerEvidence": {"evidenceId": "PG-FILE-PROGRESS-029", "selector": {"table": "file_source_publish_watermark"}}, + "nonOwnerEvidence": { + "evidenceId": "PG-FILE-PROGRESS-029", + "selector": { + "table": "file_source_publish_watermark" + } + }, "purpose": "Immutable per-change visibility completion; the operator watermark is its highest contiguous acquisition sequence", "organizationColumn": "organization_id", "organizationInclusiveKeys": [ - {"name": "pk_file_source_publish_watermark", "kind": "primary_key", "columns": ["organization_id", "source_id", "sequence"]}, - {"name": "uq_file_source_publish_watermark_ref", "kind": "unique", "columns": ["organization_id", "watermark_ref"]} + { + "name": "pk_file_source_publish_watermark", + "kind": "primary_key", + "columns": [ + "organization_id", + "source_id", + "sequence" + ] + }, + { + "name": "uq_file_source_publish_watermark_ref", + "kind": "unique", + "columns": [ + "organization_id", + "watermark_ref" + ] + } ], "foreignKeys": [ - {"name": "fk_file_source_publish_watermark_checkpoint_exact", "columns": ["organization_id", "source_id", "sequence", "checkpoint_ref", "change_kind"], "references": {"table": "file_source_acquisition_checkpoint", "columns": ["organization_id", "source_id", "sequence", "checkpoint_ref", "change_kind"]}}, - {"name": "fk_file_source_publish_watermark_revision_same_organization", "columns": ["organization_id", "resource_ref", "revision_id"], "references": {"table": "context_revision", "columns": ["organization_id", "resource_ref", "revision_id"]}} + { + "name": "fk_file_source_publish_watermark_checkpoint_exact", + "columns": [ + "organization_id", + "source_id", + "sequence", + "checkpoint_ref", + "change_kind" + ], + "references": { + "table": "file_source_acquisition_checkpoint", + "columns": [ + "organization_id", + "source_id", + "sequence", + "checkpoint_ref", + "change_kind" + ] + } + }, + { + "name": "fk_file_source_publish_watermark_revision_same_organization", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ], + "references": { + "table": "context_revision", + "columns": [ + "organization_id", + "resource_ref", + "revision_id" + ] + } + } ], "checkConstraints": [ - {"name": "ck_file_source_publish_watermark_sequence", "expression": "sequence BETWEEN 1 AND 9223372036854775807"}, - {"name": "ck_file_source_publish_watermark_ref", "expression": "watermark_ref is fpwm_ plus one SHA-256 hex digest"}, - {"name": "ck_file_source_publish_watermark_resource", "expression": "resource_ref is bounded nonblank Unicode without control characters"}, - {"name": "ck_file_source_publish_watermark_outcome", "expression": "import outcomes are published, replaced or unchanged; tombstone outcome is tombstoned"} - ], - "rowLevelSecurity": {"enabled": true, "forced": true, "policies": [ - {"name": "file_source_publish_watermark_migrator_administration", "command": "ALL", "roles": ["context_engine_migrator"], "using": "true", "withCheck": "true"}, - {"name": "file_source_publish_watermark_file_progress_definer_select", "command": "SELECT", "roles": ["context_engine_worker_lease_definer"], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"}, - {"name": "file_source_publish_watermark_file_progress_definer_insert", "command": "INSERT", "roles": ["context_engine_worker_lease_definer"], "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid"} - ]}, - "immutableRows": {"trigger": "file_source_publish_watermark_immutable", "function": "context_content_reject_mutation", "events": ["UPDATE", "DELETE"], "sqlstate": "55000"}, - "functionOnlyMutation": {"databaseFunctions": ["context_file_source_append_publish_watermark", "context_file_source_publish_active_revision", "context_file_source_publish_unchanged_acquisition", "context_file_source_checkpoint_tombstone"], "causalDatabaseFunctions": ["context_worker_publish_file_import_v2", "context_worker_publish_structural_file_import_v2", "context_worker_stage_file_replacement", "context_worker_stage_structural_file_replacement", "context_worker_activate_file_replacement", "context_worker_acquire_file_publication", "context_worker_activate_recoverable_file_publication", "context_control_tombstone_file_resource"], "definerRole": "context_engine_worker_lease_definer", "directTableMutationAllowed": false}, - "permittedOperations": {"context_engine_control": ["EXECUTE context_control_read_file_source_progress", "EXECUTE context_control_tombstone_file_resource"], "context_engine_runtime": [], "context_engine_worker": ["EXECUTE context_worker_publish_file_import_v2", "EXECUTE context_worker_publish_structural_file_import_v2", "EXECUTE context_worker_stage_file_replacement", "EXECUTE context_worker_stage_structural_file_replacement", "EXECUTE context_worker_activate_file_replacement", "EXECUTE context_worker_acquire_file_publication", "EXECUTE context_worker_activate_recoverable_file_publication"], "context_engine_worker_lease_definer": ["SELECT", "INSERT"]}, + { + "name": "ck_file_source_publish_watermark_sequence", + "expression": "sequence BETWEEN 1 AND 9223372036854775807" + }, + { + "name": "ck_file_source_publish_watermark_ref", + "expression": "watermark_ref is fpwm_ plus one SHA-256 hex digest" + }, + { + "name": "ck_file_source_publish_watermark_resource", + "expression": "resource_ref is bounded nonblank Unicode without control characters" + }, + { + "name": "ck_file_source_publish_watermark_outcome", + "expression": "import outcomes are published, replaced or unchanged; tombstone outcome is tombstoned" + } + ], + "rowLevelSecurity": { + "enabled": true, + "forced": true, + "policies": [ + { + "name": "file_source_publish_watermark_migrator_administration", + "command": "ALL", + "roles": [ + "context_engine_migrator" + ], + "using": "true", + "withCheck": "true" + }, + { + "name": "file_source_publish_watermark_file_progress_definer_select", + "command": "SELECT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + }, + { + "name": "file_source_publish_watermark_file_progress_definer_insert", + "command": "INSERT", + "roles": [ + "context_engine_worker_lease_definer" + ], + "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" + } + ] + }, + "immutableRows": { + "trigger": "file_source_publish_watermark_immutable", + "function": "context_content_reject_mutation", + "events": [ + "UPDATE", + "DELETE" + ], + "sqlstate": "55000" + }, + "functionOnlyMutation": { + "databaseFunctions": [ + "context_file_source_append_publish_watermark", + "context_file_source_publish_active_revision", + "context_file_source_publish_unchanged_acquisition", + "context_file_source_checkpoint_tombstone" + ], + "causalDatabaseFunctions": [ + "context_worker_publish_file_import_v2", + "context_worker_publish_structural_file_import_v2", + "context_worker_stage_file_replacement", + "context_worker_stage_structural_file_replacement", + "context_worker_activate_file_replacement", + "context_worker_acquire_file_publication", + "context_worker_activate_recoverable_file_publication", + "context_control_tombstone_file_resource" + ], + "definerRole": "context_engine_worker_lease_definer", + "directTableMutationAllowed": false + }, + "permittedOperations": { + "context_engine_control": [ + "EXECUTE context_control_read_file_source_progress", + "EXECUTE context_control_tombstone_file_resource" + ], + "context_engine_runtime": [], + "context_engine_worker": [ + "EXECUTE context_worker_publish_file_import_v2", + "EXECUTE context_worker_publish_structural_file_import_v2", + "EXECUTE context_worker_stage_file_replacement", + "EXECUTE context_worker_stage_structural_file_replacement", + "EXECUTE context_worker_activate_file_replacement", + "EXECUTE context_worker_acquire_file_publication", + "EXECUTE context_worker_activate_recoverable_file_publication" + ], + "context_engine_worker_lease_definer": [ + "SELECT", + "INSERT" + ] + }, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "WORKER-LEASE-007"], - "negativeTestIds": ["DB-001", "DB-004", "DB-008", "PG-FILE-PROGRESS-029"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "WORKER-LEASE-007" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-008", + "PG-FILE-PROGRESS-029" + ] }, { "name": "release_promotion_audit", "classification": "tenant_owned", "nonOwnerEvidence": { "evidenceId": "PG-RELEASE-OWNER-019", - "selector": {"table": "release_promotion_audit"} + "selector": { + "table": "release_promotion_audit" + } }, "purpose": "Immutable append-only success audit paired atomically with each active release generation", "organizationColumn": "organization_id", @@ -3303,37 +6671,67 @@ { "name": "pk_release_promotion_audit", "kind": "primary_key", - "columns": ["organization_id", "active_generation"] + "columns": [ + "organization_id", + "active_generation" + ] }, { "name": "uq_release_promotion_audit_ref", "kind": "unique", - "columns": ["organization_id", "promotion_ref"] + "columns": [ + "organization_id", + "promotion_ref" + ] } ], "foreignKeys": [ { "name": "fk_release_promotion_audit_candidate_exact", - "columns": ["organization_id", "candidate_ref", "candidate_digest"], + "columns": [ + "organization_id", + "candidate_ref", + "candidate_digest" + ], "references": { "table": "release_candidate", - "columns": ["organization_id", "candidate_ref", "candidate_digest"] + "columns": [ + "organization_id", + "candidate_ref", + "candidate_digest" + ] } }, { "name": "fk_release_promotion_audit_manifest_exact", - "columns": ["organization_id", "manifest_ref", "manifest_digest"], + "columns": [ + "organization_id", + "manifest_ref", + "manifest_digest" + ], "references": { "table": "release_manifest", - "columns": ["organization_id", "manifest_ref", "manifest_digest"] + "columns": [ + "organization_id", + "manifest_ref", + "manifest_digest" + ] } }, { "name": "fk_release_promotion_audit_evaluation_exact", - "columns": ["organization_id", "evaluation_ref", "evaluation_digest"], + "columns": [ + "organization_id", + "evaluation_ref", + "evaluation_digest" + ], "references": { "table": "release_evaluation", - "columns": ["organization_id", "evaluation_ref", "evaluation_digest"] + "columns": [ + "organization_id", + "evaluation_ref", + "evaluation_digest" + ] } } ], @@ -3366,14 +6764,18 @@ { "name": "release_promotion_audit_release_definer", "command": "ALL", - "roles": ["context_engine_release_definer"], + "roles": [ + "context_engine_release_definer" + ], "using": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid", "withCheck": "organization_id = NULLIF(current_setting('app.organization_id', true), '')::uuid" }, { "name": "release_promotion_audit_migrator_administration", "command": "ALL", - "roles": ["context_engine_migrator"], + "roles": [ + "context_engine_migrator" + ], "using": "true", "withCheck": "true" } @@ -3382,7 +6784,10 @@ "immutableRows": { "trigger": "release_promotion_audit_reject_mutation", "function": "release_lineage_reject_mutation", - "events": ["UPDATE", "DELETE"], + "events": [ + "UPDATE", + "DELETE" + ], "sqlstate": "55000" }, "functionOnlyMutation": { @@ -3393,15 +6798,33 @@ }, "permittedOperations": { "context_engine_control": [], - "context_engine_learning": ["EXECUTE context_learning_promote_release"], - "context_engine_release_definer": ["SELECT", "INSERT"], + "context_engine_learning": [ + "EXECUTE context_learning_promote_release" + ], + "context_engine_release_definer": [ + "SELECT", + "INSERT" + ], "context_engine_runtime": [], "context_engine_security_operator": [], "context_engine_worker": [] }, "partitions": [], - "securityInvariantIds": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "RELEASE-OWNER-019"], - "negativeTestIds": ["DB-001", "DB-004", "DB-005", "DB-008", "LEARN-004", "LEARN-006", "LEARN-007"] + "securityInvariantIds": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "RELEASE-OWNER-019" + ], + "negativeTestIds": [ + "DB-001", + "DB-004", + "DB-005", + "DB-008", + "LEARN-004", + "LEARN-006", + "LEARN-007" + ] } ] } diff --git a/engine/runtime/actor.py b/engine/runtime/actor.py index 9872407b..d1c49bb8 100644 --- a/engine/runtime/actor.py +++ b/engine/runtime/actor.py @@ -26,6 +26,7 @@ PolicyEpochVerification, _require_active_policy_epoch_verification, ) +from engine.runtime.release_lineage import ActiveRuntimeRelease MAX_MEMBERSHIP_VERSION: Final = (1 << 63) - 1 @@ -109,12 +110,11 @@ class CurrentMembershipVerification: context_run_persistence_session: ContextRunPersistenceSession | None = field( repr=False ) - delivery_evidence_redemption_session: ( - DeliveryEvidenceRedemptionSession | None - ) = field(repr=False) - egress_grant_issuance_session: EgressGrantIssuanceSession | None = field( - repr=False + delivery_evidence_redemption_session: DeliveryEvidenceRedemptionSession | None = ( + field(repr=False) ) + egress_grant_issuance_session: EgressGrantIssuanceSession | None = field(repr=False) + active_runtime_release: ActiveRuntimeRelease | None = field(repr=False) construction_provenance: MembershipVerificationProvenance _authority_scope: _MembershipAuthorityScope = field(repr=False) @@ -146,6 +146,7 @@ def _construct_current_membership_verification( DeliveryEvidenceRedemptionSession | None ) = None, egress_grant_issuance_session: EgressGrantIssuanceSession | None = None, + active_runtime_release: ActiveRuntimeRelease | None = None, ) -> CurrentMembershipVerification: """Construct proof after the trusted authority verifies the durable row.""" @@ -195,9 +196,12 @@ def _construct_current_membership_verification( delivery_evidence_redemption_session ) if egress_grant_issuance_session is not None: - _require_active_egress_grant_issuance_session( - egress_grant_issuance_session - ) + _require_active_egress_grant_issuance_session(egress_grant_issuance_session) + if active_runtime_release is not None: + if type(active_runtime_release) is not ActiveRuntimeRelease: + raise TypeError("current Membership active release has the wrong type") + if active_runtime_release.organization_id != organization_id: + raise ValueError("current Membership active release crossed Organization") _require_active_policy_epoch_verification(policy_epoch_verification) if policy_epoch_verification.organization_id != organization_id: raise ValueError("current Membership Policy Epoch must stay in Organization") @@ -245,6 +249,11 @@ def _construct_current_membership_verification( "egress_grant_issuance_session", egress_grant_issuance_session, ) + object.__setattr__( + verification, + "active_runtime_release", + active_runtime_release, + ) object.__setattr__( verification, "construction_provenance", @@ -319,12 +328,11 @@ class UserActor: context_run_persistence_session: ContextRunPersistenceSession | None = field( repr=False ) - delivery_evidence_redemption_session: ( - DeliveryEvidenceRedemptionSession | None - ) = field(repr=False) - egress_grant_issuance_session: EgressGrantIssuanceSession | None = field( - repr=False + delivery_evidence_redemption_session: DeliveryEvidenceRedemptionSession | None = ( + field(repr=False) ) + egress_grant_issuance_session: EgressGrantIssuanceSession | None = field(repr=False) + active_runtime_release: ActiveRuntimeRelease | None = field(repr=False) current_membership_verification: CurrentMembershipVerification = field(repr=False) construction_provenance: UserActorConstructionProvenance @@ -377,6 +385,7 @@ def _construct_user_actor( "egress_grant_issuance_session", verification.egress_grant_issuance_session, ), + ("active_runtime_release", verification.active_runtime_release), ("current_membership_verification", verification), ( "construction_provenance", @@ -418,5 +427,6 @@ def _require_active_user_actor(actor: UserActor) -> None: is not verification.delivery_evidence_redemption_session or actor.egress_grant_issuance_session is not verification.egress_grant_issuance_session + or actor.active_runtime_release is not verification.active_runtime_release ): raise ValueError("UserActor does not match its current Membership proof") diff --git a/engine/runtime/construction.py b/engine/runtime/construction.py index 97d29dc7..773019ac 100644 --- a/engine/runtime/construction.py +++ b/engine/runtime/construction.py @@ -28,13 +28,14 @@ prohibited_empty_path_content_io, ) from engine.runtime.context_run import ( + PACKAGE_RETENTION_POLICY_REF, ContextRunPersistenceUnavailable, build_context_run_records, persist_context_run, ) from engine.runtime.contracts import ( DECISION_REF_PREFIX, - ORGANIZATION_PACKAGE_REF_PREFIX, + PACKAGE_REF_PREFIX, Acquire, BudgetUsage, CitationNotAvailable, @@ -93,6 +94,7 @@ _policy_epoch_is_current, _require_active_policy_epoch_verification, ) +from engine.runtime.release_lineage import ActiveReleaseUnavailable from engine.runtime.scope import ( OMITTED_REQUEST_NARROWING, EffectiveScope, @@ -124,7 +126,7 @@ class DecisionProvenanceReceipt: """Server-owned request and policy lineage for one decision.""" decision_ref: str - package_organization_ref: str + package_id: str organization_id: UUID = field(repr=False) user_id: UUID = field(repr=False) membership_id: UUID = field(repr=False) @@ -284,12 +286,12 @@ def issue( ) -> DecisionProvenanceReceipt: _require_utc("Runtime clock", as_of) references = reference_issuer.issue() - organization_ref = references.package_organization_ref + package_id = references.package_id decision_ref = references.decision_ref - organization_ref = _require_closed_opaque_ref( - "organization reference", - organization_ref, - prefix=ORGANIZATION_PACKAGE_REF_PREFIX, + package_id = _require_closed_opaque_ref( + "package reference", + package_id, + prefix=PACKAGE_REF_PREFIX, ) decision_ref = _require_closed_opaque_ref( "decision reference", @@ -300,13 +302,13 @@ def issue( invocation.organization_verification.organization_id.hex ) if ( - trusted_organization_hex in organization_ref + trusted_organization_hex in package_id or trusted_organization_hex in decision_ref ): raise ValueError("server references must not embed trusted Organization") return DecisionProvenanceReceipt( decision_ref=decision_ref, - package_organization_ref=organization_ref, + package_id=package_id, organization_id=(invocation.organization_verification.organization_id), user_id=invocation.user_actor.user_id, membership_id=invocation.user_actor.membership_id, @@ -348,18 +350,35 @@ def finalize( raise RuntimeConfigurationError("egress profile has the wrong nominal type") _require_active_user_actor(invocation.user_actor) if ( - package.package_digest != context_package_digest( - context_package_digest_document(package) - ) + package.package_digest + != context_package_digest(context_package_digest_document(package)) or provenance.organization_id != invocation.user_actor.organization_id - or provenance.package_organization_ref != package.organization_ref + or provenance.package_id != package.package_id or provenance.decision_ref != package.decision_ref or provenance.purpose != package.purpose or provenance.purpose != delivery_context.purpose - or provenance.policy_epoch - != invocation.policy_epoch - != invocation.user_actor.policy_epoch + or not ( + provenance.policy_epoch + == invocation.policy_epoch + == invocation.user_actor.policy_epoch + ) or provenance.as_of != package.as_of + or package.audience_digest + != ( + delivery_context.audience_digest + or direct_egress_audience_digest( + organization_id=invocation.user_actor.organization_id, + membership_id=invocation.user_actor.membership_id, + membership_version=invocation.user_actor.membership_version, + authenticated_application_ref=( + delivery_context.authenticated_application_ref + ), + delivery_binding_ref=delivery_context.delivery_binding_ref, + ) + ) + or package.policy_epoch != provenance.policy_epoch + or package.policy_snapshot_ref != provenance.policy_snapshot_ref + or package.run_ref != provenance.run_ref or issued_at != package.as_of or package.expires_at <= issued_at ): @@ -383,17 +402,7 @@ def finalize( raise EgressGrantIssuanceUnavailable( "external egress requires durable one-shot issuance" ) - audience_digest = delivery_context.audience_digest - if audience_digest is None: - audience_digest = direct_egress_audience_digest( - organization_id=invocation.user_actor.organization_id, - membership_id=invocation.user_actor.membership_id, - membership_version=invocation.user_actor.membership_version, - authenticated_application_ref=( - delivery_context.authenticated_application_ref - ), - delivery_binding_ref=delivery_context.delivery_binding_ref, - ) + audience_digest = package.audience_digest expires_at = min( package.expires_at, issued_at + profile.maximum_ttl, @@ -799,9 +808,7 @@ def _authorize_and_assemble( kernel_scope=kernel_scope, candidate_ref=candidate, body=field_projection.rendered_body, - projected_field_refs=( - field_projection.projected_field_refs - ), + projected_field_refs=(field_projection.projected_field_refs), lineage=EvidenceLineage( run_ref=provenance_receipt.run_ref, principal_ref=invocation.principal_ref, @@ -863,7 +870,7 @@ def _require_utc(field_name: str, value: object) -> datetime: @dataclass(frozen=True, slots=True) class _IssuedReferences: - package_organization_ref: str + package_id: str decision_ref: str run_ref: str policy_snapshot_ref: str @@ -889,7 +896,7 @@ def issue(self) -> _IssuedReferences: sha256, ).hexdigest()[:32] for label in ( - "organization", + "package", "decision", "run", "policy", @@ -897,9 +904,7 @@ def issue(self) -> _IssuedReferences: ) } return _IssuedReferences( - package_organization_ref=( - f"{ORGANIZATION_PACKAGE_REF_PREFIX}_{entropies['organization']}" - ), + package_id=(f"{PACKAGE_REF_PREFIX}_{entropies['package']}"), decision_ref=f"{DECISION_REF_PREFIX}_{entropies['decision']}", run_ref=f"run_{entropies['run']}", policy_snapshot_ref=f"policy_{entropies['policy']}", @@ -1067,6 +1072,16 @@ def resolve( assert isinstance(request, Acquire) acquire = request + active_release = invocation.user_actor.active_runtime_release + if active_release is None: + raise ActiveReleaseUnavailable( + "Acquire requires one Learning-published active release" + ) + if active_release.organization_id != invocation.user_actor.organization_id: + raise ActiveReleaseUnavailable( + "active Runtime release crossed Organization" + ) + as_of = _require_utc("Runtime clock", self._clock()) decision = self._kernel.authorize_acquire( invocation, @@ -1085,10 +1100,29 @@ def resolve( content = finalized.content audit_receipt = finalized.audit_receipt provenance = finalized.provenance_receipt + audience_digest = delivery_context.audience_digest + if audience_digest is None: + audience_digest = direct_egress_audience_digest( + organization_id=invocation.user_actor.organization_id, + membership_id=invocation.user_actor.membership_id, + membership_version=invocation.user_actor.membership_version, + authenticated_application_ref=( + delivery_context.authenticated_application_ref + ), + delivery_binding_ref=delivery_context.delivery_binding_ref, + ) package = ContextPackage( - organization_ref=provenance.package_organization_ref, + package_id=provenance.package_id, purpose=policy_receipt.purpose, + audience_digest=audience_digest, + policy_epoch=provenance.policy_epoch, + policy_snapshot_ref=provenance.policy_snapshot_ref, + run_ref=provenance.run_ref, + release_manifest_ref=active_release.manifest_ref, + retention_policy_ref=PACKAGE_RETENTION_POLICY_REF, + tokenizer_ref=active_release.tokenizer_ref, + package_schema_ref=active_release.package_schema_ref, ttl_seconds=self._package_ttl_seconds, as_of=provenance.as_of, expires_at=provenance.as_of + timedelta(seconds=self._package_ttl_seconds), diff --git a/engine/runtime/context_run.py b/engine/runtime/context_run.py index b8dc8e65..1cf790d3 100644 --- a/engine/runtime/context_run.py +++ b/engine/runtime/context_run.py @@ -28,6 +28,7 @@ MAX_SIGNED_BIGINT: Final = (1 << 63) - 1 PACKAGE_RETENTION_MODE: Final = "digest_only" +PACKAGE_RETENTION_POLICY_REF: Final = "package-digest-only-retention-v1" class ContextRunPersistenceUnavailable(RuntimeError): @@ -251,7 +252,7 @@ def persist( class DecisionProvenance(Protocol): - package_organization_ref: str + package_id: str organization_id: UUID user_id: UUID membership_id: UUID @@ -406,6 +407,9 @@ def build_context_run_records( raise TypeError("ContextRun projection requires Acquire") if type(package) is not ContextPackage: raise TypeError("ContextRun projection requires ContextPackage") + active_release = invocation.user_actor.active_runtime_release + if active_release is None: + raise ValueError("ContextRun requires an active Runtime release") if type(final_effective_scope) is not EffectiveScope: raise TypeError("ContextRun projection requires final EffectiveScope") if type(effective_budget) is not PackageBudget: @@ -416,7 +420,7 @@ def build_context_run_records( ): raise ValueError("ContextRun Package digest must match its public document") required_provenance_fields = ( - "package_organization_ref", + "package_id", "organization_id", "user_id", "membership_id", @@ -466,11 +470,18 @@ def build_context_run_records( or decision_provenance.request_id != invocation.request_id or decision_provenance.purpose != invocation.trusted_scope_snapshot.purpose or decision_provenance.as_of != package.as_of - or decision_provenance.package_organization_ref != package.organization_ref + or decision_provenance.package_id != package.package_id or decision_provenance.decision_ref != package.decision_ref or decision_provenance.policy_epoch != invocation.policy_epoch or decision_provenance.effective_scope_digest != final_effective_scope.digest or package.purpose != invocation.trusted_scope_snapshot.purpose + or package.policy_epoch != decision_provenance.policy_epoch + or package.policy_snapshot_ref != decision_provenance.policy_snapshot_ref + or package.run_ref != decision_provenance.run_ref + or package.release_manifest_ref != active_release.manifest_ref + or package.tokenizer_ref != active_release.tokenizer_ref + or package.package_schema_ref != active_release.package_schema_ref + or package.retention_policy_ref != PACKAGE_RETENTION_POLICY_REF or package.as_of < invocation.received_at ): raise ValueError("ContextRun Package and provenance must match invocation") diff --git a/engine/runtime/contracts.py b/engine/runtime/contracts.py index e243e7b9..ad4a2063 100644 --- a/engine/runtime/contracts.py +++ b/engine/runtime/contracts.py @@ -44,9 +44,9 @@ MAX_NARROWING_REFS = 64 MAX_NARROWING_REF_LENGTH = 256 MAX_OPAQUE_CAPABILITY_LENGTH = 4096 -ORGANIZATION_PACKAGE_REF_PREFIX = "orgpkg" +PACKAGE_REF_PREFIX = "pkg" DECISION_REF_PREFIX = "dec" -ORGANIZATION_PACKAGE_REF_PATTERN = r"^orgpkg_[0-9a-f]{32}$" +PACKAGE_REF_PATTERN = r"^pkg_[0-9a-f]{32}$" DECISION_REF_PATTERN = r"^dec_[0-9a-f]{32}$" @@ -262,8 +262,16 @@ def _require_utc(field_name: str, value: object) -> None: class ContextPackage: """Tenant-safe Runtime deliverable with exact authorized Evidence closure.""" - organization_ref: str + package_id: str purpose: str + audience_digest: str + policy_epoch: int + policy_snapshot_ref: str + run_ref: str + release_manifest_ref: str + retention_policy_ref: str + tokenizer_ref: str + package_schema_ref: str ttl_seconds: int as_of: datetime expires_at: datetime @@ -277,11 +285,36 @@ class ContextPackage: def __post_init__(self) -> None: _require_closed_opaque_ref( - "package organization_ref", - self.organization_ref, - prefix=ORGANIZATION_PACKAGE_REF_PREFIX, + "package package_id", + self.package_id, + prefix=PACKAGE_REF_PREFIX, ) _require_nonblank_string("package purpose", self.purpose) + if ( + type(self.audience_digest) is not str + or len(self.audience_digest) != 64 + or any( + character not in "0123456789abcdef" + for character in self.audience_digest + ) + ): + raise ValueError("package audience_digest must be lowercase SHA-256") + if type(self.policy_epoch) is not int or self.policy_epoch < 1: + raise ValueError("package policy_epoch must be a positive integer") + for field_name in ( + "policy_snapshot_ref", + "run_ref", + "release_manifest_ref", + "retention_policy_ref", + "tokenizer_ref", + "package_schema_ref", + ): + value = getattr(self, field_name) + _require_nonblank_string(f"package {field_name}", value) + if value != value.strip() or any( + character.isspace() for character in value + ): + raise ValueError(f"package {field_name} must be an opaque ref") _require_closed_opaque_ref( "package decision_ref", self.decision_ref, @@ -366,13 +399,21 @@ def context_package_digest_document(package: ContextPackage) -> dict[str, object } if package.coverage.reason is not None: coverage_document["reason"] = package.coverage.reason.value - return { - "organizationRef": package.organization_ref, + document: dict[str, object] = { + "packageId": package.package_id, "purpose": package.purpose, + "audienceDigest": package.audience_digest, + "policyEpoch": package.policy_epoch, + "policySnapshotRef": package.policy_snapshot_ref, + "runRef": package.run_ref, + "releaseManifestRef": package.release_manifest_ref, + "retentionPolicyRef": package.retention_policy_ref, "ttlSeconds": package.ttl_seconds, "asOf": _wire_datetime(package.as_of), "expiresAt": _wire_datetime(package.expires_at), "decisionRef": package.decision_ref, + "tokenizerRef": package.tokenizer_ref, + "packageSchemaRef": package.package_schema_ref, "blocks": [ { "blockId": f"block_{block.evidence_ref.removeprefix('ev_')}", @@ -395,7 +436,14 @@ def context_package_digest_document(package: ContextPackage) -> dict[str, object "decisionRef": item.lineage.decision_ref, "policySnapshotRef": item.lineage.policy_snapshot_ref, "policyEpoch": item.lineage.policy_epoch, - "sourceDecisionRef": item.lineage.source_acl_decision_ref, + "sourceAclEvidence": { + "kind": "mirrored", + "projectionRef": item.lineage.source_acl_decision_ref, + "aclAsOf": _wire_datetime(item.lineage.as_of), + "freshnessProfileRef": ( + "file-source-access-current-transaction-v1" + ), + }, } for item in package.evidence ], @@ -408,6 +456,23 @@ def context_package_digest_document(package: ContextPackage) -> dict[str, object }, "coverage": coverage_document, } + return complete_context_package_nullable_fields(document) + + +def complete_context_package_nullable_fields( + document: dict[str, object], +) -> dict[str, object]: + """Include the frozen inactive nullable fields in one canonical location.""" + + evidence = document.get("evidence") + if not isinstance(evidence, list): + raise TypeError("public ContextPackage Evidence must be an array") + for item in evidence: + if not isinstance(item, dict): + raise TypeError("public ContextPackage Evidence must contain objects") + item["citationOpenRef"] = None + document["continuation"] = None + return document def context_package_public_document(package: ContextPackage) -> dict[str, object]: diff --git a/engine/runtime/package_digest.py b/engine/runtime/package_digest.py index 3afad3c0..7906d9b5 100644 --- a/engine/runtime/package_digest.py +++ b/engine/runtime/package_digest.py @@ -13,7 +13,7 @@ import rfc8785 -PACKAGE_DIGEST_PROFILE: Final = "context-package-canonical-json-v2" +PACKAGE_DIGEST_PROFILE: Final = "context-package-canonical-json-v3" QUERY_DIGEST_PROFILE: Final = "context-query-json-hmac-sha256-v1" _QUERY_DIGEST_DOMAIN: Final = b"context-engine.query-digest.v1\x00" _MINIMUM_QUERY_KEY_BYTES: Final = 32 diff --git a/engine/runtime/release_lineage.py b/engine/runtime/release_lineage.py new file mode 100644 index 00000000..e4d527b7 --- /dev/null +++ b/engine/runtime/release_lineage.py @@ -0,0 +1,196 @@ +"""Trusted observation of the active Organization Runtime release lineage.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from hashlib import sha256 +from typing import Final +from uuid import UUID + + +class ActiveReleaseUnavailable(RuntimeError): + """No complete active Runtime release could be observed fail-closed.""" + + +RUNTIME_PROFILE_REF_V0: Final = "runtime-materialized-openapi-v0" +RUNTIME_TOKENIZER_REF_V0: Final = "utf8-byte-budget-v1" +PACKAGE_SCHEMA_REF_V0: Final = "context-package-openapi-v0" +CONTENT_PROFILE_REF_V0: Final = "content-materialized-v0" +CONTENT_SCHEMA_REF_V0: Final = "context-content-schema-v1" +INDEX_PROFILE_REF_V0: Final = "index-exact-phrase-v0" +INDEX_SCHEMA_REF_V0: Final = "context-index-schema-v1" +CONTENT_PROFILE_DIGEST_V0: Final = sha256( + b"context-engine.content-profile.materialized-v0" +).hexdigest() +INDEX_PROFILE_DIGEST_V0: Final = sha256( + b"context-engine.index-profile.exact-phrase-v0" +).hexdigest() +RUNTIME_PROFILE_DIGEST_V0: Final = sha256( + b"context-engine.runtime-profile.materialized-openapi-v0" +).hexdigest() +CURATION_PROFILE_REF_V0: Final = "curation-off-v0" +CURATION_PROFILE_DIGEST_V0: Final = sha256( + b"context-engine.curation-profile.off-v0" +).hexdigest() +_PUBLIC_RELEASE_REF_DOMAIN: Final = b"context-engine.public-release-ref.v1\x00" + + +def _require_ref(field_name: str, value: object) -> str: + if ( + type(value) is not str + or not value + or value.isspace() + or value != value.strip() + or any(character.isspace() for character in value) + ): + raise ValueError(f"active release {field_name} must be an opaque ref") + return value + + +def _require_digest(field_name: str, value: object) -> str: + if ( + type(value) is not str + or len(value) != sha256().digest_size * 2 + or any(character not in "0123456789abcdef" for character in value) + ): + raise ValueError(f"active release {field_name} must be lowercase SHA-256") + return value + + +def public_release_manifest_ref( + manifest_digest: str, + active_generation: int, +) -> str: + """Derive a public opaque activation ref without exposing durable labels.""" + + digest = _require_digest("manifest_digest", manifest_digest) + if ( + type(active_generation) is not int + or not 1 <= active_generation <= (1 << 63) - 1 + ): + raise ValueError("active release generation must be a positive signed bigint") + public_digest = sha256( + _PUBLIC_RELEASE_REF_DOMAIN + + bytes.fromhex(digest) + + active_generation.to_bytes(8, "big", signed=False) + ).hexdigest() + return f"rel_{public_digest}" + + +@dataclass(frozen=True, slots=True) +class ActiveRuntimeRelease: + """Immutable active manifest facts observed by the current UserActor authority.""" + + organization_id: UUID = field(repr=False) + manifest_digest: str = field(repr=False) + active_generation: int + content_profile_ref: str + content_schema_ref: str + index_profile_ref: str + index_schema_ref: str + runtime_profile_ref: str + runtime_profile_digest: str = field(repr=False) + content_profile_digest: str = field(repr=False) + index_profile_digest: str = field(repr=False) + tokenizer_ref: str + package_schema_ref: str + curation_profile_ref: str + curation_profile_digest: str = field(repr=False) + curation_mode: str + curation_snapshot_ref: str | None + curation_evaluation_digest: str | None = field(repr=False) + compatible_revision_refs: tuple[str, ...] + active_revision_refs: tuple[str, ...] + manifest_ref: str = field(init=False) + + def __post_init__(self) -> None: + if type(self.organization_id) is not UUID: + raise TypeError("active release Organization must be UUID") + if ( + type(self.active_generation) is not int + or not 1 <= self.active_generation <= (1 << 63) - 1 + ): + raise ValueError( + "active release generation must be a positive signed bigint" + ) + for field_name in ( + "content_profile_ref", + "content_schema_ref", + "index_profile_ref", + "index_schema_ref", + "runtime_profile_ref", + "tokenizer_ref", + "package_schema_ref", + "curation_profile_ref", + ): + _require_ref(field_name, getattr(self, field_name)) + for field_name in ( + "manifest_digest", + "runtime_profile_digest", + "content_profile_digest", + "index_profile_digest", + "curation_profile_digest", + ): + _require_digest(field_name, getattr(self, field_name)) + if type(self.active_revision_refs) is not tuple: + raise TypeError("active release Revisions must be a tuple") + if type(self.compatible_revision_refs) is not tuple: + raise TypeError("active release compatible Revisions must be a tuple") + for field_name, revision_refs in ( + ("active_revision_ref", self.active_revision_refs), + ("compatible_revision_ref", self.compatible_revision_refs), + ): + for revision_ref in revision_refs: + _require_ref(field_name, revision_ref) + if len(set(revision_refs)) != len( + revision_refs + ) or revision_refs != tuple(sorted(revision_refs)): + raise ValueError( + "active release Revisions must be unique and canonical" + ) + if ( + self.content_profile_ref != CONTENT_PROFILE_REF_V0 + or self.content_schema_ref != CONTENT_SCHEMA_REF_V0 + or self.index_profile_ref != INDEX_PROFILE_REF_V0 + or self.index_schema_ref != INDEX_SCHEMA_REF_V0 + or self.runtime_profile_ref != RUNTIME_PROFILE_REF_V0 + or self.content_profile_digest != CONTENT_PROFILE_DIGEST_V0 + or self.index_profile_digest != INDEX_PROFILE_DIGEST_V0 + or self.runtime_profile_digest != RUNTIME_PROFILE_DIGEST_V0 + or self.tokenizer_ref != RUNTIME_TOKENIZER_REF_V0 + or self.package_schema_ref != PACKAGE_SCHEMA_REF_V0 + or self.curation_profile_ref != CURATION_PROFILE_REF_V0 + or self.curation_profile_digest != CURATION_PROFILE_DIGEST_V0 + or self.curation_mode != "curation_off" + or self.curation_snapshot_ref is not None + or self.curation_evaluation_digest is not None + or self.compatible_revision_refs != () + ): + raise ValueError("active release selects an unsupported Runtime profile") + object.__setattr__( + self, + "manifest_ref", + public_release_manifest_ref( + self.manifest_digest, + self.active_generation, + ), + ) + + +__all__ = [ + "CONTENT_PROFILE_DIGEST_V0", + "CONTENT_PROFILE_REF_V0", + "CONTENT_SCHEMA_REF_V0", + "CURATION_PROFILE_DIGEST_V0", + "CURATION_PROFILE_REF_V0", + "INDEX_PROFILE_DIGEST_V0", + "INDEX_PROFILE_REF_V0", + "INDEX_SCHEMA_REF_V0", + "PACKAGE_SCHEMA_REF_V0", + "RUNTIME_PROFILE_DIGEST_V0", + "RUNTIME_PROFILE_REF_V0", + "RUNTIME_TOKENIZER_REF_V0", + "ActiveReleaseUnavailable", + "ActiveRuntimeRelease", + "public_release_manifest_ref", +] diff --git a/eval/catalogs/security-catalog.schema.json b/eval/catalogs/security-catalog.schema.json index 5f7e50c1..79415adc 100644 --- a/eval/catalogs/security-catalog.schema.json +++ b/eval/catalogs/security-catalog.schema.json @@ -27,31 +27,67 @@ { "type": "object", "additionalProperties": false, - "required": ["name", "requiredValue", "veto"], + "required": [ + "name", + "requiredValue", + "veto" + ], "properties": { - "name": {"const": "Unauthorized Evidence"}, - "requiredValue": {"type": "integer", "const": 0}, - "veto": {"type": "boolean", "const": true} + "name": { + "const": "Unauthorized Evidence" + }, + "requiredValue": { + "type": "integer", + "const": 0 + }, + "veto": { + "type": "boolean", + "const": true + } } }, { "type": "object", "additionalProperties": false, - "required": ["name", "requiredValue", "veto"], + "required": [ + "name", + "requiredValue", + "veto" + ], "properties": { - "name": {"const": "wrong-Organization effect"}, - "requiredValue": {"type": "integer", "const": 0}, - "veto": {"type": "boolean", "const": true} + "name": { + "const": "wrong-Organization effect" + }, + "requiredValue": { + "type": "integer", + "const": 0 + }, + "veto": { + "type": "boolean", + "const": true + } } }, { "type": "object", "additionalProperties": false, - "required": ["name", "requiredValue", "veto"], + "required": [ + "name", + "requiredValue", + "veto" + ], "properties": { - "name": {"const": "missing-context fallback"}, - "requiredValue": {"type": "integer", "const": 0}, - "veto": {"type": "boolean", "const": true} + "name": { + "const": "missing-context fallback" + }, + "requiredValue": { + "type": "integer", + "const": 0 + }, + "veto": { + "type": "boolean", + "const": true + } } } ], @@ -59,8 +95,8 @@ }, "activations": { "type": "array", - "minItems": 8, - "maxItems": 8, + "minItems": 9, + "maxItems": 9, "uniqueItems": true, "prefixItems": [ { @@ -72,13 +108,39 @@ "policyEpochScope": "organization-v0", "controlBoundary": "PostgreSQLAccessPolicyControl.change_access(ResourceAccessRevocation)", "testEvidence": [ - {"id": "PG-REVOCATION-006", "surface": "tests/integration/test_access_policy_revocation.py", "oracle": "The internal non-owner Control transaction atomically revokes exact same-Organization access and advances one monotonic Organization epoch; rollback and overflow expose neither half, concurrent successful changes lose no bump, and Org B remains unchanged."}, - {"id": "RUN-006", "surface": "tests/integration/test_runtime_policy_epoch_integration.py", "oracle": "The same authenticated HTTP Acquire with the same query and unchanged CandidateIndex/Fragment returns authorized Evidence before revoke and zero Evidence on the first request after commit; Org B remains authorized and the persistent Fragment remains present."}, - {"id": "CACHE-002", "surface": "tests/unit/test_runtime_authorized_evidence.py", "oracle": "An injected pre-revocation authorization decision or a mid-resolve epoch change fails the final current-epoch gate and delivers zero stale Evidence without relying on candidate or content removal."} + { + "id": "PG-REVOCATION-006", + "surface": "tests/integration/test_access_policy_revocation.py", + "oracle": "The internal non-owner Control transaction atomically revokes exact same-Organization access and advances one monotonic Organization epoch; rollback and overflow expose neither half, concurrent successful changes lose no bump, and Org B remains unchanged." + }, + { + "id": "RUN-006", + "surface": "tests/integration/test_runtime_policy_epoch_integration.py", + "oracle": "The same authenticated HTTP Acquire with the same query and unchanged CandidateIndex/Fragment returns authorized Evidence before revoke and zero Evidence on the first request after commit; Org B remains authorized and the persistent Fragment remains present." + }, + { + "id": "CACHE-002", + "surface": "tests/unit/test_runtime_authorized_evidence.py", + "oracle": "An injected pre-revocation authorization decision or a mid-resolve epoch change fails the final current-epoch gate and delivers zero stale Evidence without relying on candidate or content removal." + } + ], + "deferredEvidence": [ + "BLOB-002" + ], + "futureCarriers": [ + "Continue", + "OpenCitation", + "Policy-Epoch-bound WorkerLease", + "production ContextAccessTicket", + "production ActionTicket" ], - "deferredEvidence": ["BLOB-002"], - "futureCarriers": ["Continue", "OpenCitation", "Policy-Epoch-bound WorkerLease", "production ContextAccessTicket", "production ActionTicket"], - "notActive": ["DecisionAudit", "outbox", "cleanup", "Source/Resource Policy Epochs", "UI/external admin"] + "notActive": [ + "DecisionAudit", + "outbox", + "cleanup", + "Source/Resource Policy Epochs", + "UI/external admin" + ] } }, { @@ -90,12 +152,33 @@ "policyEpochScope": "organization-v0", "controlBoundary": "RuntimeCapabilityGate.require_available(RuntimeCapability)", "testEvidence": [ - {"id": "RUN-UNAVAILABLE-016", "surface": "tests/unit/test_runtime_unavailable_capabilities.py", "oracle": "Table-driven Runtime cases prove unavailable Continue, OpenCitation, and server-owned Acquire plans traverse the content-free sealed Kernel preflight and stop before Provider, index, or source I/O; the restricted mandatory audit retains only UNSUPPORTED_CAPABILITY."}, - {"id": "HTTP-UNAVAILABLE-016", "surface": "tests/unit/test_http_unavailable_capabilities.py", "oracle": "The closed HTTP and OpenAPI request union admits its declared variants, maps known unavailable capabilities to generic 200 domain outcomes before configured scope-authority or content I/O, rejects unknown fields and every query string with 422, and serializes no internal cause or protected detail."} + { + "id": "RUN-UNAVAILABLE-016", + "surface": "tests/unit/test_runtime_unavailable_capabilities.py", + "oracle": "Table-driven Runtime cases prove unavailable Continue, OpenCitation, and server-owned Acquire plans traverse the content-free sealed Kernel preflight and stop before Provider, index, or source I/O; the restricted mandatory audit retains only UNSUPPORTED_CAPABILITY." + }, + { + "id": "HTTP-UNAVAILABLE-016", + "surface": "tests/unit/test_http_unavailable_capabilities.py", + "oracle": "The closed HTTP and OpenAPI request union admits its declared variants, maps known unavailable capabilities to generic 200 domain outcomes before configured scope-authority or content I/O, rejects unknown fields and every query string with 422, and serializes no internal cause or protected detail." + } + ], + "deferredEvidence": [ + "real-continuation-redemption", + "real-citation-redemption", + "real-federated-source-native-authorization" ], - "deferredEvidence": ["real-continuation-redemption", "real-citation-redemption", "real-federated-source-native-authorization"], - "futureCarriers": ["Continue", "OpenCitation", "federated/source-native ContextProvider"], - "notActive": ["continuation issuance/redemption", "citation locator redemption", "federated Provider/source-native ACL I/O", "File publication"] + "futureCarriers": [ + "Continue", + "OpenCitation", + "federated/source-native ContextProvider" + ], + "notActive": [ + "continuation issuance/redemption", + "citation locator redemption", + "federated Provider/source-native ACL I/O", + "File publication" + ] } }, { @@ -107,13 +190,51 @@ "policyEpochScope": "not-bound-issue-17", "controlBoundary": "complete_persistent_noop_job(PostgreSQLWorkerLeaseAuthority, WorkerLeaseRedemption)", "testEvidence": [ - {"id": "LEASE-SIGNING-017", "surface": "tests/unit/test_worker_lease.py", "oracle": "Versioned domain-separated canonical HMAC-SHA256 signing with an explicit injected keyring accepts one exact no-op lease and generically rejects unknown versions, malformed tokens, tampering, expiry, claim mutation, and UserActor substitution without exposing claims or key material."}, - {"id": "PG-WORKER-LEASE-NOOP-017", "surface": "tests/integration/test_worker_lease.py", "oracle": "The bounded registered ServicePrincipal receiver binding redeems one exact same-Organization persistent no-op job only through the database function's atomic current-row compare-and-set; the worker role has no table SELECT, and rollback, replay, mismatch, expiry, and concurrent losers create zero additional durable transitions and zero wrong-Organization effects. This does not claim the full canonical ServiceActor."}, - {"id": "WORKER-LEASE-REPLAY-007", "surface": "tests/integration/test_worker_lease.py", "oracle": "The real worker application seam completes exactly one persistent no-op job with its server-minted lease; replay returns only generic work-not-available and leaves the completed durable state unchanged."} + { + "id": "LEASE-SIGNING-017", + "surface": "tests/unit/test_worker_lease.py", + "oracle": "Versioned domain-separated canonical HMAC-SHA256 signing with an explicit injected keyring accepts one exact no-op lease and generically rejects unknown versions, malformed tokens, tampering, expiry, claim mutation, and UserActor substitution without exposing claims or key material." + }, + { + "id": "PG-WORKER-LEASE-NOOP-017", + "surface": "tests/integration/test_worker_lease.py", + "oracle": "The bounded registered ServicePrincipal receiver binding redeems one exact same-Organization persistent no-op job only through the database function's atomic current-row compare-and-set; the worker role has no table SELECT, and rollback, replay, mismatch, expiry, and concurrent losers create zero additional durable transitions and zero wrong-Organization effects. This does not claim the full canonical ServiceActor." + }, + { + "id": "WORKER-LEASE-REPLAY-007", + "surface": "tests/integration/test_worker_lease.py", + "oracle": "The real worker application seam completes exactly one persistent no-op job with its server-minted lease; replay returns only generic work-not-available and leaves the completed durable state unchanged." + } ], - "deferredEvidence": ["PROP-WORKER-LEASE-007", "PG-WORKER-LEASE-007", "DB-011", "JOB-001", "JOB-005", "full ACCEPT-008 per-binding matrix"], - "futureCarriers": ["Source-bound acquisition", "Resource/Revision mutation", "Policy-Epoch/end-user-delivery-audience-bound WorkerLease", "idempotency/generation-bound business mutation", "outbox dispatch", "File publication"], - "notActive": ["Source", "Resource", "Revision", "Policy Epoch", "end-user delivery audience", "idempotency", "generation", "content-bearing mutation", "outbox", "File publication", "full ACCEPT-008 PASS"] + "deferredEvidence": [ + "PROP-WORKER-LEASE-007", + "PG-WORKER-LEASE-007", + "DB-011", + "JOB-001", + "JOB-005", + "full ACCEPT-008 per-binding matrix" + ], + "futureCarriers": [ + "Source-bound acquisition", + "Resource/Revision mutation", + "Policy-Epoch/end-user-delivery-audience-bound WorkerLease", + "idempotency/generation-bound business mutation", + "outbox dispatch", + "File publication" + ], + "notActive": [ + "Source", + "Resource", + "Revision", + "Policy Epoch", + "end-user delivery audience", + "idempotency", + "generation", + "content-bearing mutation", + "outbox", + "File publication", + "full ACCEPT-008 PASS" + ] } }, { @@ -125,12 +246,36 @@ "policyEpochScope": "organization-v0", "controlBoundary": "ContextAccessTicketReadHandler.read | ActionTicketNoopHandler.perform", "testEvidence": [ - {"id": "TICKET-AUDIENCE-018", "surface": "tests/unit/test_ticket_audience_separation.py", "oracle": "Distinct nominal signed ContextAccessTicket and ActionTicket types use one explicit versioned keyring while separate signing domains and token types prevent cross-plane authority. They bind a validated AuthenticatedInvocation/TrustedDeliveryContext identity and purpose, trusted Organization, current Organization Policy Epoch, bounded expiry, operation, and provider-specific context-read or channel-specific im-send audiences. Their type-aware deserializers and structurally separate synthetic Provider-read and no-op channel handlers accept only the exact matching ticket; cross-plane, target, audience, identity, freshness, tamper, and malformed-token probes return one generic non-enumerating rejection with zero rejected synthetic calls. This is not production ContextProvider, Sender, or ActionPlane evidence."}, - {"id": "PG-TICKET-EPOCH-018", "surface": "tests/integration/test_ticket_policy_epoch.py", "oracle": "The real PostgreSQL non-owner UserActor transaction exercises both ticket types before a trusted Control transaction commits an Organization epoch bump, then rejects both previously valid tickets before their separate synthetic read and action effect counters increment. This proves current Organization-v0 epoch binding, not durable ticket consumption or a real external effect."} + { + "id": "TICKET-AUDIENCE-018", + "surface": "tests/unit/test_ticket_audience_separation.py", + "oracle": "Distinct nominal signed ContextAccessTicket and ActionTicket types use one explicit versioned keyring while separate signing domains and token types prevent cross-plane authority. They bind a validated AuthenticatedInvocation/TrustedDeliveryContext identity and purpose, trusted Organization, current Organization Policy Epoch, bounded expiry, operation, and provider-specific context-read or channel-specific im-send audiences. Their type-aware deserializers and structurally separate synthetic Provider-read and no-op channel handlers accept only the exact matching ticket; cross-plane, target, audience, identity, freshness, tamper, and malformed-token probes return one generic non-enumerating rejection with zero rejected synthetic calls. This is not production ContextProvider, Sender, or ActionPlane evidence." + }, + { + "id": "PG-TICKET-EPOCH-018", + "surface": "tests/integration/test_ticket_policy_epoch.py", + "oracle": "The real PostgreSQL non-owner UserActor transaction exercises both ticket types before a trusted Control transaction commits an Organization epoch bump, then rejects both previously valid tickets before their separate synthetic read and action effect counters increment. This proves current Organization-v0 epoch binding, not durable ticket consumption or a real external effect." + } + ], + "deferredEvidence": [ + "PROP-ACTION-SEPARATION-014", + "PG-ACTION-SEPARATION-014", + "ACTION-001 through ACTION-009", + "full ACCEPT-012 matrix" ], - "deferredEvidence": ["PROP-ACTION-SEPARATION-014", "PG-ACTION-SEPARATION-014", "ACTION-001 through ACTION-009", "full ACCEPT-012 matrix"], - "futureCarriers": ["production ContextProvider read/projection", "ContextRuntime ticket integration", "BotDelivery", "M2 ActionPlane and real Sender"], - "notActive": ["full M2 ActionPlane.prepare/perform", "real Sender/external effect", "payload/destination/approval/idempotency", "durable one-shot/replay/reconciliation", "full ACCEPT-012 PASS"] + "futureCarriers": [ + "production ContextProvider read/projection", + "ContextRuntime ticket integration", + "BotDelivery", + "M2 ActionPlane and real Sender" + ], + "notActive": [ + "full M2 ActionPlane.prepare/perform", + "real Sender/external effect", + "payload/destination/approval/idempotency", + "durable one-shot/replay/reconciliation", + "full ACCEPT-012 PASS" + ] } }, { @@ -142,14 +287,45 @@ "policyEpochScope": "organization-v0", "controlBoundary": "persist_context_run(ContextRunPersistenceSession, ContextRunRecord, DecisionAuditRecord | None) | PostgreSQLContextRunReader.find_by_decision_ref", "testEvidence": [ - {"id": "DIGEST-019", "surface": "tests/unit/test_package_digest.py", "oracle": "The versioned Package profile hashes the exact active public JSON document without packageDigest using RFC 8785 JSON Canonicalization Scheme (JCS), including recursive UTF-16 code-unit property ordering and ECMAScript number serialization; it rejects non-finite numbers and ambiguous values and detects alteration. The separately domain-separated versioned HMAC binds the exact query to one Organization and retains no raw query or serializable key material."}, - {"id": "RUN-LINEAGE-019", "surface": "tests/integration/test_runtime_empty_package_integration.py", "oracle": "A successful authenticated empty HTTP Acquire returns only after the retained current-UserActor transaction persists a same-Organization digest-only ContextRun and the restricted generic no_authorized_evidence DecisionAudit; raw query, Candidate, Resource, denial identifier, and count fields are absent."}, - {"id": "AUTHORIZED-RUN-019", "surface": "tests/integration/test_runtime_authorized_evidence_integration.py", "oracle": "The public HTTP authorized Package decisionRef resolves through the explicit same-Organization operator seam to exactly one delivered_authorized ContextRun containing only authorized Evidence refs and its matching Package digest, with no denial audit row."}, - {"id": "PG-TRACE-REDACTION-012", "surface": "tests/integration/test_context_run_schema.py", "oracle": "Real PostgreSQL FORCE RLS permits Runtime INSERT only for the exact current UserActor, gives security-operator and Control no direct table reads, and permits one exact safe ContextRun projection when Control issues a digest-only 60-second Organization-and-decision-bound ticket that security-operator deletes before projection; a committed read, arbitrary GUCs, wrong bindings, expiry, and revocation disclose no additional row, while direct-caller rollback is not claimed as durable exactly-once redemption and DecisionAudit remains seven redacted lineage/category columns."} + { + "id": "DIGEST-019", + "surface": "tests/unit/test_package_digest.py", + "oracle": "The versioned Package profile hashes the exact active public JSON document without packageDigest using RFC 8785 JSON Canonicalization Scheme (JCS), including recursive UTF-16 code-unit property ordering and ECMAScript number serialization; it rejects non-finite numbers and ambiguous values and detects alteration. The separately domain-separated versioned HMAC binds the exact query to one Organization and retains no raw query or serializable key material." + }, + { + "id": "RUN-LINEAGE-019", + "surface": "tests/integration/test_runtime_empty_package_integration.py", + "oracle": "A successful authenticated empty HTTP Acquire returns only after the retained current-UserActor transaction persists a same-Organization digest-only ContextRun and the restricted generic no_authorized_evidence DecisionAudit; raw query, Candidate, Resource, denial identifier, and count fields are absent." + }, + { + "id": "AUTHORIZED-RUN-019", + "surface": "tests/integration/test_runtime_authorized_evidence_integration.py", + "oracle": "The public HTTP authorized Package decisionRef resolves through the explicit same-Organization operator seam to exactly one delivered_authorized ContextRun containing only authorized Evidence refs and its matching Package digest, with no denial audit row." + }, + { + "id": "PG-TRACE-REDACTION-012", + "surface": "tests/integration/test_context_run_schema.py", + "oracle": "Real PostgreSQL FORCE RLS permits Runtime INSERT only for the exact current UserActor, gives security-operator and Control no direct table reads, and permits one exact safe ContextRun projection when Control issues a digest-only 60-second Organization-and-decision-bound ticket that security-operator deletes before projection; a committed read, arbitrary GUCs, wrong bindings, expiry, and revocation disclose no additional row, while direct-caller rollback is not claimed as durable exactly-once redemption and DecisionAudit remains seven redacted lineage/category columns." + } + ], + "deferredEvidence": [ + "PROP-TRACE-REDACTION-012 across every future observability carrier", + "OBS-002 secret scanning beyond the activated query/key contracts", + "OBS-003 production debug-endpoint authorization" + ], + "futureCarriers": [ + "Continue and OpenCitation ContextRun lineage", + "full retrieval candidate/ranking traces", + "authorized feedback and golden-set extraction", + "explicitly approved full-Package retention" ], - "deferredEvidence": ["PROP-TRACE-REDACTION-012 across every future observability carrier", "OBS-002 secret scanning beyond the activated query/key contracts", "OBS-003 production debug-endpoint authorization"], - "futureCarriers": ["Continue and OpenCitation ContextRun lineage", "full retrieval candidate/ranking traces", "authorized feedback and golden-set extraction", "explicitly approved full-Package retention"], - "notActive": ["raw query retention", "full ContextPackage body retention", "unauthenticated transport failures as ContextRuns", "cross-Organization analytics", "general logs/metrics/debug/evaluation/Learning redaction coverage"] + "notActive": [ + "raw query retention", + "full ContextPackage body retention", + "unauthenticated transport failures as ContextRuns", + "cross-Organization analytics", + "general logs/metrics/debug/evaluation/Learning redaction coverage" + ] } }, { @@ -161,13 +337,42 @@ "policyEpochScope": "organization-v0", "controlBoundary": "CandidateRef -> same-transaction active-lineage locator -> EffectiveScope -> current Membership/version field ceiling -> PostgreSQL/FORCE-RLS field reduction -> AuthorizationKernel -> AuthorizedProjection", "testEvidence": [ - {"id": "PROP-FIELD-PROJECTION-048", "surface": "tests/unit/test_membership_field_projection.py::test_generated_projection_narrowing_never_expands_or_leaks_denied_values tests/unit/test_membership_field_projection.py::test_missing_or_nonmatching_projection_ceiling_absorbs_content tests/unit/test_evidence_contracts.py::test_authorized_projection_and_evidence_bind_exact_projected_fields", "oracle": "The closed projection value admits only fields inside one trusted finite ceiling, renders their canonical order, absorbs missing or nonmatching ceilings, and binds the exact projected field tuple into AuthorizedProjection and Evidence integrity; no denied field name, value, or count becomes public evidence."}, - {"id": "PG-FIELD-PROJECTION-048", "surface": "tests/integration/test_authorized_field_schema.py::test_runtime_field_rows_and_legacy_body_are_filtered_by_exact_right tests/integration/test_authorized_field_schema.py::test_revoked_resource_acl_filters_every_projection_row_and_right tests/integration/test_authorized_field_schema.py::test_cross_organization_field_authority_and_values_fail_closed tests/integration/test_authorized_field_schema.py::test_stale_or_forged_membership_context_exposes_zero_field_content tests/integration/test_authorized_field_schema.py::test_field_row_requires_a_fields_parent_and_exact_same_org_parents tests/integration/test_authorized_field_schema.py::test_field_authority_tables_have_force_rls_and_least_privilege_grants tests/integration/test_membership_field_projection_integration.py::test_concurrent_field_right_revoke_cannot_commit_before_delivery_transaction tests/integration/test_migrations.py::test_field_projection_downgrade_refuses_populated_content_atomically tests/integration/test_migrations.py::test_field_projection_downgrade_serializes_with_concurrent_fragment_insert", "oracle": "Real PostgreSQL under the non-owner Runtime role exposes status only to the limited current Membership/version and status plus private_note to the full one, exposes zero Fragment, right-name, or field bytes after Resource ACL revocation, serializes concurrent right mutation behind the delivery transaction, refuses populated schema downgrade before DDL, serializes its empty-schema decision with concurrent Fragment publication, exposes zero Fragment or field bytes for stale or forged Membership context, keeps legacy body as an explicit right, requires exact same-Organization parents, and enforces FORCE RLS with least-privilege grants."}, - {"id": "HTTP-ACCEPT-002-048", "surface": "tests/integration/test_membership_field_projection_integration.py::test_accept_002_same_organization_memberships_receive_only_authorized_fields", "oracle": "The authenticated HTTP Acquire seam reuses one content-free CandidateRef for same-Organization limited and full Memberships; the limited Package contains only status=open while the full Package contains both authorized fields, and after the limited right is removed the next resolve returns generic empty coverage. The limited response, ContextRun, and DecisionAudit contain zero private_note or secret bytes and no denied names, identifiers, or counts."} + { + "id": "PROP-FIELD-PROJECTION-048", + "surface": "tests/unit/test_membership_field_projection.py::test_generated_projection_narrowing_never_expands_or_leaks_denied_values tests/unit/test_membership_field_projection.py::test_missing_or_nonmatching_projection_ceiling_absorbs_content tests/unit/test_evidence_contracts.py::test_authorized_projection_and_evidence_bind_exact_projected_fields", + "oracle": "The closed projection value admits only fields inside one trusted finite ceiling, renders their canonical order, absorbs missing or nonmatching ceilings, and binds the exact projected field tuple into AuthorizedProjection and Evidence integrity; no denied field name, value, or count becomes public evidence." + }, + { + "id": "PG-FIELD-PROJECTION-048", + "surface": "tests/integration/test_authorized_field_schema.py::test_runtime_field_rows_and_legacy_body_are_filtered_by_exact_right tests/integration/test_authorized_field_schema.py::test_revoked_resource_acl_filters_every_projection_row_and_right tests/integration/test_authorized_field_schema.py::test_cross_organization_field_authority_and_values_fail_closed tests/integration/test_authorized_field_schema.py::test_stale_or_forged_membership_context_exposes_zero_field_content tests/integration/test_authorized_field_schema.py::test_field_row_requires_a_fields_parent_and_exact_same_org_parents tests/integration/test_authorized_field_schema.py::test_field_authority_tables_have_force_rls_and_least_privilege_grants tests/integration/test_membership_field_projection_integration.py::test_concurrent_field_right_revoke_cannot_commit_before_delivery_transaction tests/integration/test_migrations.py::test_field_projection_downgrade_refuses_populated_content_atomically tests/integration/test_migrations.py::test_field_projection_downgrade_serializes_with_concurrent_fragment_insert", + "oracle": "Real PostgreSQL under the non-owner Runtime role exposes status only to the limited current Membership/version and status plus private_note to the full one, exposes zero Fragment, right-name, or field bytes after Resource ACL revocation, serializes concurrent right mutation behind the delivery transaction, refuses populated schema downgrade before DDL, serializes its empty-schema decision with concurrent Fragment publication, exposes zero Fragment or field bytes for stale or forged Membership context, keeps legacy body as an explicit right, requires exact same-Organization parents, and enforces FORCE RLS with least-privilege grants." + }, + { + "id": "HTTP-ACCEPT-002-048", + "surface": "tests/integration/test_membership_field_projection_integration.py::test_accept_002_same_organization_memberships_receive_only_authorized_fields", + "oracle": "The authenticated HTTP Acquire seam reuses one content-free CandidateRef for same-Organization limited and full Memberships; the limited Package contains only status=open while the full Package contains both authorized fields, and after the limited right is removed the next resolve returns generic empty coverage. The limited response, ContextRun, and DecisionAudit contain zero private_note or secret bytes and no denied names, identifiers, or counts." + } + ], + "deferredEvidence": [ + "production Provider-native field authorization", + "File and Base source-field authorization", + "typed or non-text field projection" ], - "deferredEvidence": ["production Provider-native field authorization", "File and Base source-field authorization", "typed or non-text field projection"], - "futureCarriers": ["production ContextProvider native field projection", "File and Base ingestion field ACL", "Continue and OpenCitation field projection", "field-policy change independent of Membership version"], - "notActive": ["general permission DSL", "caller-authored projection lists", "CandidateRef or index field authority", "Provider capability negotiation or source-native field ACL", "Supply publication and field classification", "ranking or relevance-model field authority", "Issue #20 gate or runner substitution"] + "futureCarriers": [ + "production ContextProvider native field projection", + "File and Base ingestion field ACL", + "Continue and OpenCitation field projection", + "field-policy change independent of Membership version" + ], + "notActive": [ + "general permission DSL", + "caller-authored projection lists", + "CandidateRef or index field authority", + "Provider capability negotiation or source-native field ACL", + "Supply publication and field classification", + "ranking or relevance-model field authority", + "Issue #20 gate or runner substitution" + ] } }, { @@ -179,14 +384,46 @@ "policyEpochScope": "organization-v0", "controlBoundary": "PrivateDeliveryEvidenceIssuer -> PostgreSQL identity function -> authenticated HTTP metadata -> current UserActor transaction redemption -> TrustedDeliveryContext -> sealed ContextRuntime.resolve(Acquire)", "testEvidence": [ - {"id": "PROP-DELIVERY-EVIDENCE-063", "surface": "tests/unit/test_delivery_evidence.py::test_delivery_evidence_values_redact_all_trusted_facts_from_repr", "oracle": "Versioned private issuance returns one opaque random reference while persisting only its SHA-256 digest and exact audience digest; issuance, redemption, and nominal TrustedDeliveryContext carriers redact bearer and raw trusted facts from normal representations."}, - {"id": "PG-DELIVERY-EVIDENCE-063", "surface": "tests/integration/test_delivery_evidence_ref.py::test_identity_issues_digest_only_and_runtime_redeems_one_stable_private_request tests/integration/test_delivery_evidence_ref.py::test_private_evidence_one_field_mutations_are_equivalent_not_available tests/integration/test_delivery_evidence_ref.py::test_same_logical_request_cannot_be_rebound_to_another_private_audience tests/integration/test_delivery_evidence_ref.py::test_expired_private_evidence_cleanup_is_exactly_organization_scoped tests/integration/test_delivery_evidence_ref.py::test_identity_cannot_backdate_issuance_for_a_membership_not_current_now tests/integration/test_delivery_evidence_ref.py::test_delivery_evidence_table_and_functions_enforce_exact_role_split", "oracle": "Real PostgreSQL with FORCE RLS stores no bearer, accepts only the dedicated identity issuer for a database-current Membership, redeems only through Runtime for the exact service/request/Organization/asker/Membership version/destination/consumer/private kind/audience digest/purpose/epoch/lifetime, preserves one stable retry identity, rejects every one-field mutation and audience rebind, restricts expired cleanup to one Organization, blocks populated downgrade, and gives ordinary application roles zero table or cross-capability access."}, - {"id": "HTTP-DELIVERY-EVIDENCE-063", "surface": "tests/unit/test_http_trust_boundary.py::test_private_delivery_evidence_is_redeemed_before_runtime_content_work", "oracle": "Authenticated HTTP metadata carries only the opaque reference; exact redemption constructs private TrustedDeliveryContext, a private route binding without evidence and evidence without a nominal private route binding fail closed, while forged or wrong authenticated-route destination evidence returns the same generic authentication failure before Runtime resolution, index, Provider, source-content, Package, model, or effect work, and response, ordinary authentication/invocation/outcome trace, and captured logs omit bearer, raw Organization/User/Membership/principal/agent/application/binding facts, destination, consumer, and audience digest."}, - {"id": "FILE-DELIVERY-EVIDENCE-063", "surface": "tests/integration/test_file_import_tracer.py::test_registered_file_import_publishes_one_exact_authorized_http_package", "oracle": "The real File-backed authenticated HTTP Acquire redeems private evidence inside the current UserActor transaction and still proves CandidateRef through the sealed AuthorizationKernel to AuthorizedProjection; an identical retry returns authorized content under one stored logical redemption identity, and both private responses plus their ContextRuns omit the bearer and raw private delivery bindings."} + { + "id": "PROP-DELIVERY-EVIDENCE-063", + "surface": "tests/unit/test_delivery_evidence.py::test_delivery_evidence_values_redact_all_trusted_facts_from_repr", + "oracle": "Versioned private issuance returns one opaque random reference while persisting only its SHA-256 digest and exact audience digest; issuance, redemption, and nominal TrustedDeliveryContext carriers redact bearer and raw trusted facts from normal representations." + }, + { + "id": "PG-DELIVERY-EVIDENCE-063", + "surface": "tests/integration/test_delivery_evidence_ref.py::test_identity_issues_digest_only_and_runtime_redeems_one_stable_private_request tests/integration/test_delivery_evidence_ref.py::test_private_evidence_one_field_mutations_are_equivalent_not_available tests/integration/test_delivery_evidence_ref.py::test_same_logical_request_cannot_be_rebound_to_another_private_audience tests/integration/test_delivery_evidence_ref.py::test_expired_private_evidence_cleanup_is_exactly_organization_scoped tests/integration/test_delivery_evidence_ref.py::test_identity_cannot_backdate_issuance_for_a_membership_not_current_now tests/integration/test_delivery_evidence_ref.py::test_delivery_evidence_table_and_functions_enforce_exact_role_split", + "oracle": "Real PostgreSQL with FORCE RLS stores no bearer, accepts only the dedicated identity issuer for a database-current Membership, redeems only through Runtime for the exact service/request/Organization/asker/Membership version/destination/consumer/private kind/audience digest/purpose/epoch/lifetime, preserves one stable retry identity, rejects every one-field mutation and audience rebind, restricts expired cleanup to one Organization, blocks populated downgrade, and gives ordinary application roles zero table or cross-capability access." + }, + { + "id": "HTTP-DELIVERY-EVIDENCE-063", + "surface": "tests/unit/test_http_trust_boundary.py::test_private_delivery_evidence_is_redeemed_before_runtime_content_work", + "oracle": "Authenticated HTTP metadata carries only the opaque reference; exact redemption constructs private TrustedDeliveryContext, a private route binding without evidence and evidence without a nominal private route binding fail closed, while forged or wrong authenticated-route destination evidence returns the same generic authentication failure before Runtime resolution, index, Provider, source-content, Package, model, or effect work, and response, ordinary authentication/invocation/outcome trace, and captured logs omit bearer, raw Organization/User/Membership/principal/agent/application/binding facts, destination, consumer, and audience digest." + }, + { + "id": "FILE-DELIVERY-EVIDENCE-063", + "surface": "tests/integration/test_file_import_tracer.py::test_registered_file_import_publishes_one_exact_authorized_http_package", + "oracle": "The real File-backed authenticated HTTP Acquire redeems private evidence inside the current UserActor transaction and still proves CandidateRef through the sealed AuthorizationKernel to AuthorizedProjection; an identical retry returns authorized content under one stored logical redemption identity, and both private responses plus their ContextRuns omit the bearer and raw private delivery bindings." + } ], - "deferredEvidence": ["group AudienceSnapshot DeliveryEvidenceRef", "frozen OpenAPI and generated TypeScript SDK carrier", "production BotDelivery caller"], - "futureCarriers": ["public group DeliveryEvidenceRef", "OpenCitation delivery evidence", "generated TypeScript SDK", "private BotDelivery application"], - "notActive": ["group delivery", "AudienceSnapshot", "production ModelGateway", "ActionPlane", "BotDelivery application", "OpenAPI compatibility freeze", "generated SDK"] + "deferredEvidence": [ + "group AudienceSnapshot DeliveryEvidenceRef", + "generated TypeScript SDK carrier", + "production BotDelivery caller" + ], + "futureCarriers": [ + "public group DeliveryEvidenceRef", + "OpenCitation delivery evidence", + "generated TypeScript SDK", + "private BotDelivery application" + ], + "notActive": [ + "group delivery", + "AudienceSnapshot", + "production ModelGateway", + "ActionPlane", + "BotDelivery application", + "generated SDK" + ] } }, { @@ -198,13 +435,94 @@ "policyEpochScope": "organization-v0", "controlBoundary": "ContextPackage -> final EgressGate -> digest-only PostgreSQL grant -> AuthorizedModelInput | AuthorizedChannelPayload -> exact one-shot redemption -> ModelGateway | Sender preflight spy", "testEvidence": [ - {"id": "PROP-EGRESS-011", "surface": "tests/unit/test_egress_grant.py::test_each_egress_binding_mutation_and_cross_kind_emits_zero_bytes_effects", "oracle": "Every common and hop-specific model or channel redemption binding mutation, plus cross-kind use, is non-enumerating and emits zero gateway bytes, Sender preflight bytes, or effects."}, - {"id": "PG-EGRESS-011", "surface": "tests/integration/test_egress_grant.py::test_digest_only_grant_is_atomic_one_shot_and_audited", "oracle": "Real PostgreSQL under separate non-owner Runtime and egress roles stores only grant and payload digests, binds the exact Package, Organization, purpose, audience, Policy Epoch, hop, retention, sensitivity, issuer, consumer, provider/model or channel/destination, region, lifetime, and profile, consumes atomically once, and retains only restricted issued, consumed, or not-available audit categories."}, - {"id": "RUNTIME-EGRESS-011", "surface": "tests/integration/test_z_egress_grant_file.py::test_file_http_package_redeems_exact_model_grant_before_gateway_bytes", "oracle": "A real File-backed authenticated HTTP Acquire proves CandidateRef through the sealed AuthorizationKernel to an audience-bound ContextPackage, returns one model grant only after final policy, and the independent egress role permits exactly one deterministic ModelGateway spy request; replay emits zero additional model bytes."} + { + "id": "PROP-EGRESS-011", + "surface": "tests/unit/test_egress_grant.py::test_each_egress_binding_mutation_and_cross_kind_emits_zero_bytes_effects", + "oracle": "Every common and hop-specific model or channel redemption binding mutation, plus cross-kind use, is non-enumerating and emits zero gateway bytes, Sender preflight bytes, or effects." + }, + { + "id": "PG-EGRESS-011", + "surface": "tests/integration/test_egress_grant.py::test_digest_only_grant_is_atomic_one_shot_and_audited", + "oracle": "Real PostgreSQL under separate non-owner Runtime and egress roles stores only grant and payload digests, binds the exact Package, Organization, purpose, audience, Policy Epoch, hop, retention, sensitivity, issuer, consumer, provider/model or channel/destination, region, lifetime, and profile, consumes atomically once, and retains only restricted issued, consumed, or not-available audit categories." + }, + { + "id": "RUNTIME-EGRESS-011", + "surface": "tests/integration/test_z_egress_grant_file.py::test_file_http_package_redeems_exact_model_grant_before_gateway_bytes", + "oracle": "A real File-backed authenticated HTTP Acquire proves CandidateRef through the sealed AuthorizationKernel to an audience-bound ContextPackage, returns one model grant only after final policy, and the independent egress role permits exactly one deterministic ModelGateway spy request; replay emits zero additional model bytes." + } + ], + "deferredEvidence": [ + "production provider ModelGateway conformance", + "production Sender and ActionPlane effect conformance", + "group AudienceSnapshot send-time revalidation" + ], + "futureCarriers": [ + "production ModelGateway", + "production Sender preflight", + "ActionPlane prepare and perform", + "group-public and asker-private delivery" + ], + "notActive": [ + "real model or provider network call", + "real Sender or channel write", + "ActionTicket or external effect", + "group AudienceSnapshot", + "BotDelivery application process", + "generated SDK consumer" + ] + } + }, + { + "const": { + "issueRef": "#66", + "invariantRef": "TRANSPORT-UNTRUSTED-008", + "carrier": "frozen public POST /v0/resolve OpenAPI contract", + "status": "active_fail_closed", + "policyEpochScope": "organization-v0", + "controlBoundary": "authenticated HTTP metadata -> closed ResolveWire -> current UserActor and active release observation -> sealed ContextRuntime.resolve -> closed ResolutionOutcome", + "testEvidence": [ + { + "id": "OPENAPI-CONTRACT-066", + "surface": "tests/unit/test_openapi_v0_contract.py", + "oracle": "The frozen document exposes exactly one public versioned operation with a closed Acquire, Continue, or OpenCitation body, closed outcome union, complete ContextPackage, bounded metadata and payloads, generic failure statuses, and no raw trusted identity or audience fields." + }, + { + "id": "OPENAPI-BREAKING-066", + "surface": "tests/unit/test_openapi_v0_snapshot.py", + "oracle": "The deterministic immutable snapshot and SHA-256 checksum gate reject current drift, base-commit mutation, and overwrite, while deliberate security, response, union, required-field, and type mutations prove the recursive gate rejects contract changes." + }, + { + "id": "HTTP-V0-066", + "surface": "tests/unit/test_http_trust_boundary.py::test_trusted_field_injection_is_closed_before_domain_execution tests/unit/test_http_unavailable_capabilities.py::test_accept_005_continue_is_generic_non_retryable_and_zero_io tests/process/test_processes.py::test_http_acquire_smoke_returns_the_empty_package_contract", + "oracle": "Public v0 rejects trusted-field injection and returns generic inactive-carrier outcomes before content work, while the process returns the frozen empty-package contract; a separate focused test proves the hidden v1 bridge shares the same sealed path." + }, + { + "id": "PG-RUNTIME-RELEASE-066", + "surface": "tests/integration/test_runtime_empty_package_integration.py::test_seeded_existing_organization_reaches_http_empty_package tests/integration/test_runtime_empty_package_integration.py::test_public_v0_resolve_without_supported_active_release_fails_before_content tests/integration/test_runtime_authorized_evidence_integration.py::test_real_postgres_http_delivers_only_exact_authorized_evidence_bidirectionally", + "oracle": "Real PostgreSQL proves the Package carries the exact Learning-promoted active manifest, tokenizer, and package schema observed under the current UserActor transaction with read-only Runtime RLS, while a missing or unsupported release returns one generic unavailable outcome before content I/O and without a ContextRun; the public v0 seam also proves CandidateRef through the sealed Kernel to exact AuthorizedProjection with real PostgreSQL." + } + ], + "deferredEvidence": [ + "generated TypeScript SDK conformance", + "production BotDelivery generated-SDK caller", + "Continue and OpenCitation redemption" ], - "deferredEvidence": ["production provider ModelGateway conformance", "production Sender and ActionPlane effect conformance", "group AudienceSnapshot send-time revalidation"], - "futureCarriers": ["production ModelGateway", "production Sender preflight", "ActionPlane prepare and perform", "group-public and asker-private delivery"], - "notActive": ["real model or provider network call", "real Sender or channel write", "ActionTicket or external effect", "group AudienceSnapshot", "BotDelivery application process", "generated SDK consumer"] + "futureCarriers": [ + "generated TypeScript SDK", + "MCP", + "BotDelivery application", + "Continue redemption", + "OpenCitation redemption" + ], + "notActive": [ + "generated SDK consumer", + "MCP", + "BotDelivery application process", + "continuation issuance or redemption", + "citation persistence or redemption", + "group AudienceSnapshot", + "external effects" + ] } } ], @@ -258,22 +576,26 @@ "authorityRef": { "type": "string", "minLength": 1, - "pattern": "^(#[0-9]+|(?!(?:[A-Za-z]:[/\\\\]|/|https?://|file://))(?!.*(?:^|/)\\.\\.(?:/|$))[A-Za-z0-9._\\-/\u4e00-\u9fff]+(?:#[A-Za-z0-9._\\-/\u4e00-\u9fff]+)?)$" + "pattern": "^(#[0-9]+|(?!(?:[A-Za-z]:[/\\\\]|/|https?://|file://))(?!.*(?:^|/)\\.\\.(?:/|$))[A-Za-z0-9._\\-/一-鿿]+(?:#[A-Za-z0-9._\\-/一-鿿]+)?)$" }, "documentRef": { "type": "string", "minLength": 1, - "pattern": "^(?!(?:[A-Za-z]:[/\\\\]|/|https?://|file://))(?!.*(?:^|/)\\.\\.(?:/|$))[A-Za-z0-9._\\-/\u4e00-\u9fff]+(?:#[A-Za-z0-9._\\-/]+)?$" + "pattern": "^(?!(?:[A-Za-z]:[/\\\\]|/|https?://|file://))(?!.*(?:^|/)\\.\\.(?:/|$))[A-Za-z0-9._\\-/一-鿿]+(?:#[A-Za-z0-9._\\-/]+)?$" }, "pytestSurface": { "type": "string", "minLength": 1, - "pattern": "^(?!(?:[A-Za-z]:[/\\\\]|/|https?://|file://))(?!.*(?:^|/)\\.\\.(?:/|$))tests/(?:unit|integration)/[A-Za-z0-9._\\-/]+\\.py(?:::[A-Za-z_][A-Za-z0-9_]*)?(?: tests/(?:unit|integration)/[A-Za-z0-9._\\-/]+\\.py(?:::[A-Za-z_][A-Za-z0-9_]*)?)*$" + "pattern": "^(?!(?:[A-Za-z]:[/\\\\]|/|https?://|file://))(?!.*(?:^|/)\\.\\.(?:/|$))tests/(?:unit|integration|process)/[A-Za-z0-9._\\-/]+\\.py(?:::[A-Za-z_][A-Za-z0-9_]*)?(?: tests/(?:unit|integration|process)/[A-Za-z0-9._\\-/]+\\.py(?:::[A-Za-z_][A-Za-z0-9_]*)?)*$" }, "authority": { "type": "object", "additionalProperties": false, - "required": ["issueRefs", "documentRefs", "reconciliation"], + "required": [ + "issueRefs", + "documentRefs", + "reconciliation" + ], "properties": { "issueRefs": { "type": "array", @@ -359,96 +681,242 @@ "applicability": { "type": "object", "additionalProperties": false, - "required": ["mode", "applicableFrom", "rationale"], + "required": [ + "mode", + "applicableFrom", + "rationale" + ], "properties": { "mode": { "type": "string", - "enum": ["required", "conditional", "not_applicable"] + "enum": [ + "required", + "conditional", + "not_applicable" + ] }, "applicableFrom": { - "type": ["string", "null"], + "type": [ + "string", + "null" + ], "minLength": 1, "pattern": "\\S" }, "rationale": { - "type": ["string", "null"], + "type": [ + "string", + "null" + ], "minLength": 1, "pattern": "\\S" } }, "if": { "properties": { - "mode": {"const": "not_applicable"} + "mode": { + "const": "not_applicable" + } }, - "required": ["mode"] + "required": [ + "mode" + ] }, "then": { "properties": { - "applicableFrom": {"type": "null"}, - "rationale": {"$ref": "#/$defs/nonEmptyString"} + "applicableFrom": { + "type": "null" + }, + "rationale": { + "$ref": "#/$defs/nonEmptyString" + } } }, "else": { "properties": { - "applicableFrom": {"$ref": "#/$defs/nonEmptyString"} + "applicableFrom": { + "$ref": "#/$defs/nonEmptyString" + } } } }, "expectedEvidence": { "type": "object", "additionalProperties": false, - "required": ["property", "postgres", "runtimeOrDelivery"], + "required": [ + "property", + "postgres", + "runtimeOrDelivery" + ], "properties": { - "property": {"$ref": "#/$defs/stringArray"}, - "postgres": {"$ref": "#/$defs/stringArray"}, - "runtimeOrDelivery": {"$ref": "#/$defs/stringArray"} + "property": { + "$ref": "#/$defs/stringArray" + }, + "postgres": { + "$ref": "#/$defs/stringArray" + }, + "runtimeOrDelivery": { + "$ref": "#/$defs/stringArray" + } } }, "activationTestEvidence": { "type": "object", "additionalProperties": false, - "required": ["id", "surface", "oracle"], + "required": [ + "id", + "surface", + "oracle" + ], "properties": { - "id": {"enum": ["PG-REVOCATION-006", "RUN-006", "CACHE-002", "RUN-UNAVAILABLE-016", "HTTP-UNAVAILABLE-016", "LEASE-SIGNING-017", "PG-WORKER-LEASE-NOOP-017", "WORKER-LEASE-REPLAY-007", "TICKET-AUDIENCE-018", "PG-TICKET-EPOCH-018", "DIGEST-019", "RUN-LINEAGE-019", "AUTHORIZED-RUN-019", "PG-TRACE-REDACTION-012", "PROP-FIELD-PROJECTION-048", "PG-FIELD-PROJECTION-048", "HTTP-ACCEPT-002-048", "PROP-DELIVERY-EVIDENCE-063", "PG-DELIVERY-EVIDENCE-063", "HTTP-DELIVERY-EVIDENCE-063", "FILE-DELIVERY-EVIDENCE-063", "PROP-EGRESS-011", "PG-EGRESS-011", "RUNTIME-EGRESS-011"]}, - "surface": {"$ref": "#/$defs/pytestSurface"}, - "oracle": {"$ref": "#/$defs/nonEmptyString"} + "id": { + "enum": [ + "PG-REVOCATION-006", + "RUN-006", + "CACHE-002", + "RUN-UNAVAILABLE-016", + "HTTP-UNAVAILABLE-016", + "LEASE-SIGNING-017", + "PG-WORKER-LEASE-NOOP-017", + "WORKER-LEASE-REPLAY-007", + "TICKET-AUDIENCE-018", + "PG-TICKET-EPOCH-018", + "DIGEST-019", + "RUN-LINEAGE-019", + "AUTHORIZED-RUN-019", + "PG-TRACE-REDACTION-012", + "PROP-FIELD-PROJECTION-048", + "PG-FIELD-PROJECTION-048", + "HTTP-ACCEPT-002-048", + "PROP-DELIVERY-EVIDENCE-063", + "PG-DELIVERY-EVIDENCE-063", + "HTTP-DELIVERY-EVIDENCE-063", + "FILE-DELIVERY-EVIDENCE-063", + "PROP-EGRESS-011", + "PG-EGRESS-011", + "RUNTIME-EGRESS-011", + "OPENAPI-CONTRACT-066", + "OPENAPI-BREAKING-066", + "HTTP-V0-066", + "PG-RUNTIME-RELEASE-066" + ] + }, + "surface": { + "$ref": "#/$defs/pytestSurface" + }, + "oracle": { + "$ref": "#/$defs/nonEmptyString" + } } }, "activation": { "type": "object", "additionalProperties": false, - "required": ["issueRef", "invariantRef", "carrier", "status", "policyEpochScope", "controlBoundary", "testEvidence", "deferredEvidence", "futureCarriers", "notActive"], + "required": [ + "issueRef", + "invariantRef", + "carrier", + "status", + "policyEpochScope", + "controlBoundary", + "testEvidence", + "deferredEvidence", + "futureCarriers", + "notActive" + ], "properties": { - "issueRef": {"enum": ["#15", "#16", "#17", "#18", "#19", "#48", "#63", "#65"]}, - "invariantRef": {"enum": ["REVOCATION-006", "INDEX-NOT-AUTHORITY-005", "WORKER-LEASE-007", "ACTION-SEPARATION-014", "TRACE-REDACTION-012", "SCOPE-INTERSECTION-004", "TRANSPORT-UNTRUSTED-008", "EGRESS-011"]}, - "carrier": {"enum": ["ContextRuntime.resolve(Acquire)", "ContextRuntime.resolve(Continue | OpenCitation | server-owned unavailable Acquire plan)", "signed one-shot persistent no-op durable-job WorkerLease", "signed synthetic ContextAccessTicket Provider read | signed synthetic ActionTicket no-op channel action", "ContextRuntime.resolve(Acquire) authorized-only ContextRun | restricted delivered-empty DecisionAudit", "ACCEPT-002 ContextRuntime.resolve(Acquire) Membership field projection", "private authenticated HTTP Acquire DeliveryEvidenceRef", "opaque one-shot model or channel EgressGrant with deterministic boundary spies"]}, - "status": {"const": "active_fail_closed"}, - "policyEpochScope": {"enum": ["organization-v0", "not-bound-issue-17"]}, - "controlBoundary": {"enum": ["PostgreSQLAccessPolicyControl.change_access(ResourceAccessRevocation)", "RuntimeCapabilityGate.require_available(RuntimeCapability)", "complete_persistent_noop_job(PostgreSQLWorkerLeaseAuthority, WorkerLeaseRedemption)", "ContextAccessTicketReadHandler.read | ActionTicketNoopHandler.perform", "persist_context_run(ContextRunPersistenceSession, ContextRunRecord, DecisionAuditRecord | None) | PostgreSQLContextRunReader.find_by_decision_ref", "CandidateRef -> same-transaction active-lineage locator -> EffectiveScope -> current Membership/version field ceiling -> PostgreSQL/FORCE-RLS field reduction -> AuthorizationKernel -> AuthorizedProjection", "PrivateDeliveryEvidenceIssuer -> PostgreSQL identity function -> authenticated HTTP metadata -> current UserActor transaction redemption -> TrustedDeliveryContext -> sealed ContextRuntime.resolve(Acquire)", "ContextPackage -> final EgressGate -> digest-only PostgreSQL grant -> AuthorizedModelInput | AuthorizedChannelPayload -> exact one-shot redemption -> ModelGateway | Sender preflight spy"]}, + "issueRef": { + "enum": [ + "#15", + "#16", + "#17", + "#18", + "#19", + "#48", + "#63", + "#65", + "#66" + ] + }, + "invariantRef": { + "enum": [ + "REVOCATION-006", + "INDEX-NOT-AUTHORITY-005", + "WORKER-LEASE-007", + "ACTION-SEPARATION-014", + "TRACE-REDACTION-012", + "SCOPE-INTERSECTION-004", + "TRANSPORT-UNTRUSTED-008", + "EGRESS-011" + ] + }, + "carrier": { + "enum": [ + "ContextRuntime.resolve(Acquire)", + "ContextRuntime.resolve(Continue | OpenCitation | server-owned unavailable Acquire plan)", + "signed one-shot persistent no-op durable-job WorkerLease", + "signed synthetic ContextAccessTicket Provider read | signed synthetic ActionTicket no-op channel action", + "ContextRuntime.resolve(Acquire) authorized-only ContextRun | restricted delivered-empty DecisionAudit", + "ACCEPT-002 ContextRuntime.resolve(Acquire) Membership field projection", + "private authenticated HTTP Acquire DeliveryEvidenceRef", + "opaque one-shot model or channel EgressGrant with deterministic boundary spies", + "frozen public POST /v0/resolve OpenAPI contract" + ] + }, + "status": { + "const": "active_fail_closed" + }, + "policyEpochScope": { + "enum": [ + "organization-v0", + "not-bound-issue-17" + ] + }, + "controlBoundary": { + "enum": [ + "PostgreSQLAccessPolicyControl.change_access(ResourceAccessRevocation)", + "RuntimeCapabilityGate.require_available(RuntimeCapability)", + "complete_persistent_noop_job(PostgreSQLWorkerLeaseAuthority, WorkerLeaseRedemption)", + "ContextAccessTicketReadHandler.read | ActionTicketNoopHandler.perform", + "persist_context_run(ContextRunPersistenceSession, ContextRunRecord, DecisionAuditRecord | None) | PostgreSQLContextRunReader.find_by_decision_ref", + "CandidateRef -> same-transaction active-lineage locator -> EffectiveScope -> current Membership/version field ceiling -> PostgreSQL/FORCE-RLS field reduction -> AuthorizationKernel -> AuthorizedProjection", + "PrivateDeliveryEvidenceIssuer -> PostgreSQL identity function -> authenticated HTTP metadata -> current UserActor transaction redemption -> TrustedDeliveryContext -> sealed ContextRuntime.resolve(Acquire)", + "ContextPackage -> final EgressGate -> digest-only PostgreSQL grant -> AuthorizedModelInput | AuthorizedChannelPayload -> exact one-shot redemption -> ModelGateway | Sender preflight spy", + "authenticated HTTP metadata -> closed ResolveWire -> current UserActor and active release observation -> sealed ContextRuntime.resolve -> closed ResolutionOutcome" + ] + }, "testEvidence": { "type": "array", "minItems": 2, "maxItems": 4, "uniqueItems": true, - "items": {"$ref": "#/$defs/activationTestEvidence"} + "items": { + "$ref": "#/$defs/activationTestEvidence" + } }, "deferredEvidence": { "type": "array", "minItems": 1, "uniqueItems": true, - "items": {"$ref": "#/$defs/nonEmptyString"} + "items": { + "$ref": "#/$defs/nonEmptyString" + } }, "futureCarriers": { "type": "array", "minItems": 3, "uniqueItems": true, - "items": {"$ref": "#/$defs/nonEmptyString"} + "items": { + "$ref": "#/$defs/nonEmptyString" + } }, "notActive": { "type": "array", "minItems": 4, "uniqueItems": true, - "items": {"$ref": "#/$defs/nonEmptyString"} + "items": { + "$ref": "#/$defs/nonEmptyString" + } } } }, @@ -471,78 +939,126 @@ "authorityRefs" ], "properties": { - "id": {"$ref": "#/$defs/invariantId"}, - "title": {"$ref": "#/$defs/nonEmptyString"}, - "purpose": {"$ref": "#/$defs/nonEmptyString"}, + "id": { + "$ref": "#/$defs/invariantId" + }, + "title": { + "$ref": "#/$defs/nonEmptyString" + }, + "purpose": { + "$ref": "#/$defs/nonEmptyString" + }, "threatRefs": { "type": "array", "minItems": 1, "uniqueItems": true, - "items": {"$ref": "#/$defs/threatRef"} + "items": { + "$ref": "#/$defs/threatRef" + } }, "protectedAssets": { "type": "array", "minItems": 1, "uniqueItems": true, - "items": {"$ref": "#/$defs/assetRef"} + "items": { + "$ref": "#/$defs/assetRef" + } + }, + "deterministicOracle": { + "$ref": "#/$defs/nonEmptyString" }, - "deterministicOracle": {"$ref": "#/$defs/nonEmptyString"}, "hardOracleRefs": { "type": "array", "minItems": 1, "uniqueItems": true, - "items": {"$ref": "#/$defs/hardOracleName"} + "items": { + "$ref": "#/$defs/hardOracleName" + } + }, + "applicability": { + "$ref": "#/$defs/applicability" + }, + "capabilityRef": { + "$ref": "#/$defs/nonEmptyString" }, - "applicability": {"$ref": "#/$defs/applicability"}, - "capabilityRef": {"$ref": "#/$defs/nonEmptyString"}, "requiredMilestones": { "type": "array", "minItems": 1, "uniqueItems": true, - "items": {"$ref": "#/$defs/milestone"} + "items": { + "$ref": "#/$defs/milestone" + } }, "evidenceStatus": { "type": "string", - "enum": ["accepted", "future_case"] + "enum": [ + "accepted", + "future_case" + ] + }, + "expectedEvidence": { + "$ref": "#/$defs/expectedEvidence" }, - "expectedEvidence": {"$ref": "#/$defs/expectedEvidence"}, "authorityRefs": { "type": "array", "minItems": 1, "uniqueItems": true, - "items": {"$ref": "#/$defs/authorityRef"} + "items": { + "$ref": "#/$defs/authorityRef" + } } } }, "carrier": { "type": "object", "additionalProperties": false, - "required": ["statusAtM0", "m0Expectation", "upgradeTrigger"], + "required": [ + "statusAtM0", + "m0Expectation", + "upgradeTrigger" + ], "properties": { "statusAtM0": { "type": "string", - "enum": ["available", "unavailable", "future"] + "enum": [ + "available", + "unavailable", + "future" + ] }, "m0Expectation": { "type": "string", - "enum": ["active_fail_closed", "fail_closed"] + "enum": [ + "active_fail_closed", + "fail_closed" + ] }, - "upgradeTrigger": {"$ref": "#/$defs/nonEmptyString"} + "upgradeTrigger": { + "$ref": "#/$defs/nonEmptyString" + } }, "if": { "properties": { - "statusAtM0": {"const": "available"} + "statusAtM0": { + "const": "available" + } }, - "required": ["statusAtM0"] + "required": [ + "statusAtM0" + ] }, "then": { "properties": { - "m0Expectation": {"const": "active_fail_closed"} + "m0Expectation": { + "const": "active_fail_closed" + } } }, "else": { "properties": { - "m0Expectation": {"const": "fail_closed"} + "m0Expectation": { + "const": "fail_closed" + } } } }, @@ -551,133 +1067,285 @@ "additionalProperties": false, "minProperties": 1, "properties": { - "actorKind": {"$ref": "#/$defs/nonEmptyString"}, - "serviceActorRef": {"$ref": "#/$defs/nonEmptyString"}, - "organizationRef": {"$ref": "#/$defs/nonEmptyString"}, - "principalRef": {"$ref": "#/$defs/nonEmptyString"}, - "agentRef": {"$ref": "#/$defs/nonEmptyString"}, - "agentVersion": {"type": "integer", "minimum": 0}, - "membershipVersion": {"type": "integer", "minimum": 0}, - "currentPolicyEpoch": {"type": "integer", "minimum": 0}, - "purpose": {"$ref": "#/$defs/nonEmptyString"}, - "requiredAclMode": {"$ref": "#/$defs/nonEmptyString"}, - "capabilityAudience": {"$ref": "#/$defs/nonEmptyString"}, - "authenticationSource": {"$ref": "#/$defs/nonEmptyString"}, - "durableJobRef": {"$ref": "#/$defs/nonEmptyString"}, - "samplePlanRef": {"$ref": "#/$defs/nonEmptyString"}, - "source": {"$ref": "#/$defs/nonEmptyString"}, + "actorKind": { + "$ref": "#/$defs/nonEmptyString" + }, + "serviceActorRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "organizationRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "principalRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "agentRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "agentVersion": { + "type": "integer", + "minimum": 0 + }, + "membershipVersion": { + "type": "integer", + "minimum": 0 + }, + "currentPolicyEpoch": { + "type": "integer", + "minimum": 0 + }, + "purpose": { + "$ref": "#/$defs/nonEmptyString" + }, + "requiredAclMode": { + "$ref": "#/$defs/nonEmptyString" + }, + "capabilityAudience": { + "$ref": "#/$defs/nonEmptyString" + }, + "authenticationSource": { + "$ref": "#/$defs/nonEmptyString" + }, + "durableJobRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "samplePlanRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "source": { + "$ref": "#/$defs/nonEmptyString" + }, "invocations": { "type": "array", "minItems": 1, - "items": {"$ref": "#/$defs/invocationIdentity"} + "items": { + "$ref": "#/$defs/invocationIdentity" + } } } }, "invocationIdentity": { "type": "object", "additionalProperties": false, - "required": ["organizationRef", "principalRef", "purpose"], + "required": [ + "organizationRef", + "principalRef", + "purpose" + ], "properties": { - "organizationRef": {"$ref": "#/$defs/nonEmptyString"}, - "principalRef": {"$ref": "#/$defs/nonEmptyString"}, - "purpose": {"$ref": "#/$defs/nonEmptyString"} + "organizationRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "principalRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "purpose": { + "$ref": "#/$defs/nonEmptyString" + } } }, "setup": { "type": "object", "additionalProperties": false, - "required": ["preconditions", "trustedIdentity"], + "required": [ + "preconditions", + "trustedIdentity" + ], "properties": { - "preconditions": {"$ref": "#/$defs/stringArray"}, - "trustedIdentity": {"$ref": "#/$defs/trustedIdentity"} + "preconditions": { + "$ref": "#/$defs/stringArray" + }, + "trustedIdentity": { + "$ref": "#/$defs/trustedIdentity" + } } }, "adversarialMutation": { "type": "object", "additionalProperties": false, "minProperties": 2, - "required": ["kind"], + "required": [ + "kind" + ], "properties": { - "kind": {"$ref": "#/$defs/nonEmptyString"}, - "caseRef": {"$ref": "#/$defs/nonEmptyString"}, + "kind": { + "$ref": "#/$defs/nonEmptyString" + }, + "caseRef": { + "$ref": "#/$defs/nonEmptyString" + }, "attempts": { "type": "array", "minItems": 1, - "items": {"$ref": "#/$defs/probeAttempt"} - }, - "candidateWasDiscoveredFor": {"$ref": "#/$defs/nonEmptyString"}, - "candidateFields": {"$ref": "#/$defs/stringArray"}, - "currentInvocation": {"$ref": "#/$defs/nonEmptyString"}, - "requestedAgentSources": {"$ref": "#/$defs/stringArray"}, - "signedAgentCeiling": {"$ref": "#/$defs/stringArray"}, - "requestNarrowing": {"$ref": "#/$defs/requestNarrowing"}, - "promptInjectedSourceRefs": {"$ref": "#/$defs/stringArray"}, - "tokenPolicyEpoch": {"type": "integer", "minimum": 0}, - "cachedResourceStillPresent": {"type": "boolean"}, - "orderedCandidateRefs": {"$ref": "#/$defs/stringArray"}, + "items": { + "$ref": "#/$defs/probeAttempt" + } + }, + "candidateWasDiscoveredFor": { + "$ref": "#/$defs/nonEmptyString" + }, + "candidateFields": { + "$ref": "#/$defs/stringArray" + }, + "currentInvocation": { + "$ref": "#/$defs/nonEmptyString" + }, + "requestedAgentSources": { + "$ref": "#/$defs/stringArray" + }, + "signedAgentCeiling": { + "$ref": "#/$defs/stringArray" + }, + "requestNarrowing": { + "$ref": "#/$defs/requestNarrowing" + }, + "promptInjectedSourceRefs": { + "$ref": "#/$defs/stringArray" + }, + "tokenPolicyEpoch": { + "type": "integer", + "minimum": 0 + }, + "cachedResourceStillPresent": { + "type": "boolean" + }, + "orderedCandidateRefs": { + "$ref": "#/$defs/stringArray" + }, "candidateRankOrders": { "type": "array", "minItems": 1, "uniqueItems": true, - "items": {"$ref": "#/$defs/stringArray"} + "items": { + "$ref": "#/$defs/stringArray" + } }, "candidatePayloadFields": { "type": "array", "uniqueItems": true, - "items": {"$ref": "#/$defs/nonEmptyString"} + "items": { + "$ref": "#/$defs/nonEmptyString" + } + }, + "bodyFields": { + "$ref": "#/$defs/injectedBodyFields" + }, + "replayCount": { + "type": "integer", + "minimum": 1 + }, + "mutatedClaim": { + "$ref": "#/$defs/mutatedClaim" + }, + "retainedNonce": { + "$ref": "#/$defs/nonEmptyString" }, - "bodyFields": {"$ref": "#/$defs/injectedBodyFields"}, - "replayCount": {"type": "integer", "minimum": 1}, - "mutatedClaim": {"$ref": "#/$defs/mutatedClaim"}, - "retainedNonce": {"$ref": "#/$defs/nonEmptyString"}, "parameterizedCases": { "type": "array", "minItems": 1, "uniqueItems": true, - "items": {"$ref": "#/$defs/parameterizedCase"} - }, - "requestedFallback": {"$ref": "#/$defs/nonEmptyString"}, - "missingCapability": {"$ref": "#/$defs/nonEmptyString"}, - "locator": {"$ref": "#/$defs/nonEmptyString"}, - "originalPolicyEpoch": {"type": "integer", "minimum": 0}, - "attemptedAlternateUse": {"$ref": "#/$defs/nonEmptyString"}, - "probes": {"$ref": "#/$defs/stringArray"}, - "order": {"$ref": "#/$defs/stringArray"}, - "ticketKind": {"$ref": "#/$defs/nonEmptyString"}, - "requestedEffect": {"$ref": "#/$defs/nonEmptyString"}, - "destination": {"$ref": "#/$defs/nonEmptyString"}, - "targetOrganization": {"$ref": "#/$defs/nonEmptyString"} + "items": { + "$ref": "#/$defs/parameterizedCase" + } + }, + "requestedFallback": { + "$ref": "#/$defs/nonEmptyString" + }, + "missingCapability": { + "$ref": "#/$defs/nonEmptyString" + }, + "locator": { + "$ref": "#/$defs/nonEmptyString" + }, + "originalPolicyEpoch": { + "type": "integer", + "minimum": 0 + }, + "attemptedAlternateUse": { + "$ref": "#/$defs/nonEmptyString" + }, + "probes": { + "$ref": "#/$defs/stringArray" + }, + "order": { + "$ref": "#/$defs/stringArray" + }, + "ticketKind": { + "$ref": "#/$defs/nonEmptyString" + }, + "requestedEffect": { + "$ref": "#/$defs/nonEmptyString" + }, + "destination": { + "$ref": "#/$defs/nonEmptyString" + }, + "targetOrganization": { + "$ref": "#/$defs/nonEmptyString" + } } }, "probeAttempt": { "type": "object", "additionalProperties": false, - "required": ["invocation", "target"], + "required": [ + "invocation", + "target" + ], "properties": { - "invocation": {"$ref": "#/$defs/nonEmptyString"}, - "target": {"$ref": "#/$defs/nonEmptyString"} + "invocation": { + "$ref": "#/$defs/nonEmptyString" + }, + "target": { + "$ref": "#/$defs/nonEmptyString" + } } }, "requestNarrowing": { "type": "object", "additionalProperties": false, - "required": ["sourceRefs"], + "required": [ + "sourceRefs" + ], "properties": { - "sourceRefs": {"$ref": "#/$defs/stringArray"} + "sourceRefs": { + "$ref": "#/$defs/stringArray" + } } }, "injectedBodyFields": { "type": "object", "additionalProperties": false, - "required": ["organizationRef", "principalRef", "purpose", "audience", "acl", "rawSql", "bypassAuthorization"], + "required": [ + "organizationRef", + "principalRef", + "purpose", + "audience", + "acl", + "rawSql", + "bypassAuthorization" + ], "properties": { - "organizationRef": {"$ref": "#/$defs/nonEmptyString"}, - "principalRef": {"$ref": "#/$defs/nonEmptyString"}, - "purpose": {"$ref": "#/$defs/nonEmptyString"}, - "audience": {"$ref": "#/$defs/stringArray"}, - "acl": {"$ref": "#/$defs/nonEmptyString"}, - "rawSql": {"$ref": "#/$defs/nonEmptyString"}, - "bypassAuthorization": {"type": "boolean"} + "organizationRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "principalRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "purpose": { + "$ref": "#/$defs/nonEmptyString" + }, + "audience": { + "$ref": "#/$defs/stringArray" + }, + "acl": { + "$ref": "#/$defs/nonEmptyString" + }, + "rawSql": { + "$ref": "#/$defs/nonEmptyString" + }, + "bypassAuthorization": { + "type": "boolean" + } } }, "mutatedClaim": { @@ -685,77 +1353,189 @@ "additionalProperties": false, "minProperties": 1, "properties": { - "organizationRef": {"$ref": "#/$defs/nonEmptyString"}, - "jobRef": {"$ref": "#/$defs/nonEmptyString"}, - "sourceRef": {"$ref": "#/$defs/nonEmptyString"}, - "operation": {"$ref": "#/$defs/nonEmptyString"}, - "generation": {"type": "integer", "minimum": 0}, - "nonce": {"$ref": "#/$defs/nonEmptyString"} + "organizationRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "jobRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "sourceRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "operation": { + "$ref": "#/$defs/nonEmptyString" + }, + "generation": { + "type": "integer", + "minimum": 0 + }, + "nonce": { + "$ref": "#/$defs/nonEmptyString" + } } }, "parameterizedCase": { "type": "object", "additionalProperties": false, - "required": ["id", "mutation", "expectedStatus", "expectedOutcome", "expectedNewDurableEffects", "expectedWrongOrganizationEffects", "expectedContentWorkCalls"], + "required": [ + "id", + "mutation", + "expectedStatus", + "expectedOutcome", + "expectedNewDurableEffects", + "expectedWrongOrganizationEffects", + "expectedContentWorkCalls" + ], "properties": { - "id": {"$ref": "#/$defs/nonEmptyString"}, - "claim": {"$ref": "#/$defs/nonEmptyString"}, + "id": { + "$ref": "#/$defs/nonEmptyString" + }, + "claim": { + "$ref": "#/$defs/nonEmptyString" + }, "mutation": { - "type": ["string", "integer"], + "type": [ + "string", + "integer" + ], "minLength": 1, "pattern": "\\S", "minimum": 0 }, - "expectedStatus": {"type": "integer", "minimum": 100, "maximum": 599}, - "expectedOutcome": {"$ref": "#/$defs/nonEmptyString"}, - "expectedNewDurableEffects": {"type": "integer", "const": 0}, - "expectedWrongOrganizationEffects": {"type": "integer", "const": 0}, - "expectedContentWorkCalls": {"type": "integer", "const": 0}, - "activatedOracle": {"$ref": "#/$defs/nonEmptyString"} - } - }, - "operation": { - "type": "object", - "additionalProperties": false, + "expectedStatus": { + "type": "integer", + "minimum": 100, + "maximum": 599 + }, + "expectedOutcome": { + "$ref": "#/$defs/nonEmptyString" + }, + "expectedNewDurableEffects": { + "type": "integer", + "const": 0 + }, + "expectedWrongOrganizationEffects": { + "type": "integer", + "const": 0 + }, + "expectedContentWorkCalls": { + "type": "integer", + "const": 0 + }, + "activatedOracle": { + "$ref": "#/$defs/nonEmptyString" + } + } + }, + "operation": { + "type": "object", + "additionalProperties": false, "minProperties": 2, - "required": ["interface", "request"], + "required": [ + "interface", + "request" + ], "properties": { - "interface": {"$ref": "#/$defs/nonEmptyString"}, - "request": {"$ref": "#/$defs/nonEmptyString"}, - "count": {"type": "integer", "minimum": 1}, - "observation": {"$ref": "#/$defs/nonEmptyString"}, - "expectedAuthorizedProjection": {"$ref": "#/$defs/stringArray"}, - "expectedEffectiveScope": {"$ref": "#/$defs/stringArray"}, - "comparison": {"$ref": "#/$defs/nonEmptyString"}, - "timing": {"$ref": "#/$defs/nonEmptyString"}, - "requiredTypeFlow": {"$ref": "#/$defs/stringArray"}, - "phase": {"$ref": "#/$defs/nonEmptyString"}, - "durableComparison": {"$ref": "#/$defs/nonEmptyString"}, - "comparisonFields": {"$ref": "#/$defs/stringArray"}, - "normalizationAllowlist": {"$ref": "#/$defs/stringArray"} + "interface": { + "$ref": "#/$defs/nonEmptyString" + }, + "request": { + "$ref": "#/$defs/nonEmptyString" + }, + "count": { + "type": "integer", + "minimum": 1 + }, + "observation": { + "$ref": "#/$defs/nonEmptyString" + }, + "expectedAuthorizedProjection": { + "$ref": "#/$defs/stringArray" + }, + "expectedEffectiveScope": { + "$ref": "#/$defs/stringArray" + }, + "comparison": { + "$ref": "#/$defs/nonEmptyString" + }, + "timing": { + "$ref": "#/$defs/nonEmptyString" + }, + "requiredTypeFlow": { + "$ref": "#/$defs/stringArray" + }, + "phase": { + "$ref": "#/$defs/nonEmptyString" + }, + "durableComparison": { + "$ref": "#/$defs/nonEmptyString" + }, + "comparisonFields": { + "$ref": "#/$defs/stringArray" + }, + "normalizationAllowlist": { + "$ref": "#/$defs/stringArray" + } } }, "externalResponse": { "type": "object", "additionalProperties": false, "minProperties": 2, - "required": ["status"], + "required": [ + "status" + ], "properties": { - "status": {"type": "integer", "minimum": 100, "maximum": 599}, - "code": {"$ref": "#/$defs/nonEmptyString"}, - "body": {"$ref": "#/$defs/responseBody"}, - "sameOutcomeSemanticsForBothAttempts": {"type": "boolean"}, - "authorizedPayloadUtf8": {"$ref": "#/$defs/nonEmptyString"}, - "authorizedPayloadBytes": {"type": "integer", "minimum": 0}, - "privateFieldPresent": {"type": "boolean"}, - "privateResourcePresent": {"type": "boolean"}, - "source2Present": {"type": "boolean"}, - "orgBContentPresent": {"type": "boolean"}, - "fieldNamesEchoed": {"type": "boolean"}, - "leaseClaimsEchoed": {"type": "boolean"}, - "headers": {"$ref": "#/$defs/responseHeaders"}, - "normalizedByteIdenticalAcrossProbes": {"type": "boolean", "const": true}, - "timingEqualityClaimed": {"type": "boolean", "const": false} + "status": { + "type": "integer", + "minimum": 100, + "maximum": 599 + }, + "code": { + "$ref": "#/$defs/nonEmptyString" + }, + "body": { + "$ref": "#/$defs/responseBody" + }, + "sameOutcomeSemanticsForBothAttempts": { + "type": "boolean" + }, + "authorizedPayloadUtf8": { + "$ref": "#/$defs/nonEmptyString" + }, + "authorizedPayloadBytes": { + "type": "integer", + "minimum": 0 + }, + "privateFieldPresent": { + "type": "boolean" + }, + "privateResourcePresent": { + "type": "boolean" + }, + "source2Present": { + "type": "boolean" + }, + "orgBContentPresent": { + "type": "boolean" + }, + "fieldNamesEchoed": { + "type": "boolean" + }, + "leaseClaimsEchoed": { + "type": "boolean" + }, + "headers": { + "$ref": "#/$defs/responseHeaders" + }, + "normalizedByteIdenticalAcrossProbes": { + "type": "boolean", + "const": true + }, + "timingEqualityClaimed": { + "type": "boolean", + "const": false + } } }, "responseBody": { @@ -763,232 +1543,691 @@ "additionalProperties": false, "minProperties": 1, "properties": { - "kind": {"$ref": "#/$defs/nonEmptyString"}, - "gap": {"$ref": "#/$defs/nonEmptyString"}, - "retryable": {"type": "boolean"}, - "package": {"$ref": "#/$defs/contextPackage"} + "kind": { + "$ref": "#/$defs/nonEmptyString" + }, + "gap": { + "$ref": "#/$defs/nonEmptyString" + }, + "retryable": { + "type": "boolean" + }, + "package": { + "$ref": "#/$defs/contextPackage" + } } }, "contextPackage": { "type": "object", "additionalProperties": false, - "required": ["organizationRef", "purpose", "ttlSeconds", "asOf", "expiresAt", "decisionRef", "packageDigest", "blocks", "evidence", "gaps", "budgetUsage", "coverage"], + "required": [ + "packageId", + "packageDigest", + "purpose", + "audienceDigest", + "policyEpoch", + "policySnapshotRef", + "decisionRef", + "runRef", + "releaseManifestRef", + "retentionPolicyRef", + "asOf", + "expiresAt", + "ttlSeconds", + "tokenizerRef", + "packageSchemaRef", + "blocks", + "evidence", + "gaps", + "coverage", + "budgetUsage", + "continuation" + ], "properties": { - "organizationRef": {"$ref": "#/$defs/nonEmptyString"}, - "purpose": {"$ref": "#/$defs/nonEmptyString"}, - "ttlSeconds": {"type": "integer", "minimum": 1}, - "asOf": {"$ref": "#/$defs/nonEmptyString"}, - "expiresAt": {"$ref": "#/$defs/nonEmptyString"}, - "decisionRef": {"$ref": "#/$defs/nonEmptyString"}, - "packageDigest": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "packageId": { + "type": "string", + "pattern": "^pkg_[0-9a-f]{32}$" + }, + "packageDigest": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "purpose": { + "$ref": "#/$defs/nonEmptyString" + }, + "audienceDigest": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "policyEpoch": { + "type": "integer", + "minimum": 1 + }, + "policySnapshotRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "decisionRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "runRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "releaseManifestRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "retentionPolicyRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "asOf": { + "$ref": "#/$defs/nonEmptyString" + }, + "expiresAt": { + "$ref": "#/$defs/nonEmptyString" + }, + "ttlSeconds": { + "type": "integer", + "minimum": 1 + }, + "tokenizerRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "packageSchemaRef": { + "$ref": "#/$defs/nonEmptyString" + }, "blocks": { "type": "array", "uniqueItems": true, - "items": {"$ref": "#/$defs/packageBlock"} + "items": { + "$ref": "#/$defs/packageBlock" + } }, "evidence": { "type": "array", "uniqueItems": true, - "items": {"$ref": "#/$defs/packageEvidence"} + "items": { + "$ref": "#/$defs/packageEvidence" + } }, - "gaps": {"type": "array", "maxItems": 0}, - "budgetUsage": {"$ref": "#/$defs/budgetUsage"}, - "coverage": {"$ref": "#/$defs/coverage"} + "gaps": { + "type": "array", + "uniqueItems": true, + "items": { + "$ref": "#/$defs/packageGap" + } + }, + "budgetUsage": { + "$ref": "#/$defs/budgetUsage" + }, + "coverage": { + "$ref": "#/$defs/coverage" + }, + "continuation": { + "anyOf": [ + { + "type": "null" + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "continuationToken", + "remainingBudgetDigest" + ], + "properties": { + "continuationToken": { + "$ref": "#/$defs/nonEmptyString" + }, + "remainingBudgetDigest": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + } + } + } + ] + } }, "if": { "properties": { "coverage": { - "properties": {"status": {"const": "empty"}}, - "required": ["status"] + "properties": { + "status": { + "const": "empty" + } + }, + "required": [ + "status" + ] } }, - "required": ["coverage"] + "required": [ + "coverage" + ] }, "then": { "properties": { - "blocks": {"maxItems": 0}, - "evidence": {"maxItems": 0}, - "budgetUsage": {"$ref": "#/$defs/zeroBudgetUsage"} + "blocks": { + "maxItems": 0 + }, + "evidence": { + "maxItems": 0 + }, + "budgetUsage": { + "$ref": "#/$defs/zeroBudgetUsage" + } } }, "else": { "properties": { - "blocks": {"minItems": 1}, - "evidence": {"minItems": 1} + "blocks": { + "minItems": 1 + }, + "evidence": { + "minItems": 1 + } } } }, "packageBlock": { "type": "object", "additionalProperties": false, - "required": ["blockId", "text", "evidenceRefs"], + "required": [ + "blockId", + "text", + "evidenceRefs" + ], "properties": { - "blockId": {"$ref": "#/$defs/blockRef"}, - "text": {"$ref": "#/$defs/nonEmptyString"}, + "blockId": { + "$ref": "#/$defs/blockRef" + }, + "text": { + "$ref": "#/$defs/nonEmptyString" + }, "evidenceRefs": { "type": "array", "minItems": 1, "maxItems": 1, "uniqueItems": true, - "items": {"$ref": "#/$defs/evidenceRef"} + "items": { + "$ref": "#/$defs/evidenceRef" + } } } }, "packageEvidence": { "type": "object", "additionalProperties": false, - "required": ["evidenceRef", "sourceRef", "resourceRef", "revisionRef", "fragmentRef", "projectedFields", "runRef", "purpose", "authorizationAsOf", "decisionRef", "policySnapshotRef", "policyEpoch", "sourceDecisionRef"], + "required": [ + "evidenceRef", + "sourceRef", + "resourceRef", + "revisionRef", + "fragmentRef", + "projectedFields", + "runRef", + "purpose", + "authorizationAsOf", + "decisionRef", + "policySnapshotRef", + "policyEpoch", + "sourceAclEvidence", + "citationOpenRef" + ], "properties": { - "evidenceRef": {"$ref": "#/$defs/evidenceRef"}, - "sourceRef": {"$ref": "#/$defs/nonEmptyString"}, - "resourceRef": {"$ref": "#/$defs/nonEmptyString"}, - "revisionRef": {"$ref": "#/$defs/nonEmptyString"}, - "fragmentRef": {"$ref": "#/$defs/nonEmptyString"}, + "evidenceRef": { + "$ref": "#/$defs/evidenceRef" + }, + "sourceRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "resourceRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "revisionRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "fragmentRef": { + "$ref": "#/$defs/nonEmptyString" + }, "projectedFields": { "type": "array", "minItems": 1, "maxItems": 64, "uniqueItems": true, - "items": {"$ref": "#/$defs/projectedFieldRef"} - }, - "runRef": {"$ref": "#/$defs/nonEmptyString"}, - "purpose": {"$ref": "#/$defs/nonEmptyString"}, - "authorizationAsOf": {"$ref": "#/$defs/nonEmptyString"}, - "decisionRef": {"$ref": "#/$defs/nonEmptyString"}, - "policySnapshotRef": {"$ref": "#/$defs/nonEmptyString"}, - "policyEpoch": {"type": "integer", "minimum": 1}, - "sourceDecisionRef": {"$ref": "#/$defs/nonEmptyString"} + "items": { + "$ref": "#/$defs/projectedFieldRef" + } + }, + "runRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "purpose": { + "$ref": "#/$defs/nonEmptyString" + }, + "authorizationAsOf": { + "$ref": "#/$defs/nonEmptyString" + }, + "decisionRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "policySnapshotRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "policyEpoch": { + "type": "integer", + "minimum": 1 + }, + "sourceAclEvidence": { + "$ref": "#/$defs/sourceAclEvidence" + }, + "citationOpenRef": { + "anyOf": [ + { + "type": "null" + }, + { + "$ref": "#/$defs/nonEmptyString" + } + ] + } + } + }, + "sourceAclEvidence": { + "type": "object", + "additionalProperties": false, + "required": [ + "kind", + "projectionRef", + "aclAsOf", + "freshnessProfileRef" + ], + "properties": { + "kind": { + "const": "mirrored" + }, + "projectionRef": { + "$ref": "#/$defs/nonEmptyString" + }, + "aclAsOf": { + "$ref": "#/$defs/nonEmptyString" + }, + "freshnessProfileRef": { + "$ref": "#/$defs/nonEmptyString" + } + } + }, + "packageGap": { + "type": "object", + "additionalProperties": false, + "required": [ + "category", + "retryable" + ], + "properties": { + "category": { + "enum": [ + "source_unavailable", + "stale_evidence", + "budget_exhausted", + "capability_unsupported" + ] + }, + "retryable": { + "type": "boolean" + } } }, "coverage": { "type": "object", "additionalProperties": false, - "required": ["status"], + "required": [ + "status" + ], "properties": { - "status": {"enum": ["empty", "sufficient"]}, - "reason": {"const": "no_authorized_evidence"} + "status": { + "enum": [ + "empty", + "partial", + "sufficient" + ] + }, + "reason": { + "enum": [ + "no_authorized_evidence", + "source_unavailable", + "stale_evidence", + "budget_exhausted", + "capability_unsupported" + ] + } }, "if": { - "properties": {"status": {"const": "empty"}}, - "required": ["status"] + "properties": { + "status": { + "const": "empty" + } + }, + "required": [ + "status" + ] }, - "then": {"required": ["reason"]}, - "else": {"properties": {"reason": false}} + "then": { + "required": [ + "reason" + ] + }, + "else": { + "properties": { + "reason": false + } + } }, "budgetUsage": { "type": "object", "additionalProperties": false, - "required": ["tokens", "providerCalls", "costMicrounits", "elapsedMs"], + "required": [ + "tokens", + "providerCalls", + "costMicrounits", + "elapsedMs" + ], "properties": { - "tokens": {"type": "integer", "minimum": 0}, - "providerCalls": {"type": "integer", "minimum": 0}, - "costMicrounits": {"type": "integer", "minimum": 0}, - "elapsedMs": {"type": "integer", "minimum": 0} + "tokens": { + "type": "integer", + "minimum": 0 + }, + "providerCalls": { + "type": "integer", + "minimum": 0 + }, + "costMicrounits": { + "type": "integer", + "minimum": 0 + }, + "elapsedMs": { + "type": "integer", + "minimum": 0 + } } }, "zeroBudgetUsage": { "type": "object", "additionalProperties": false, - "required": ["tokens", "providerCalls", "costMicrounits", "elapsedMs"], + "required": [ + "tokens", + "providerCalls", + "costMicrounits", + "elapsedMs" + ], "properties": { - "tokens": {"type": "integer", "const": 0}, - "providerCalls": {"type": "integer", "const": 0}, - "costMicrounits": {"type": "integer", "const": 0}, - "elapsedMs": {"type": "integer", "const": 0} + "tokens": { + "type": "integer", + "const": 0 + }, + "providerCalls": { + "type": "integer", + "const": 0 + }, + "costMicrounits": { + "type": "integer", + "const": 0 + }, + "elapsedMs": { + "type": "integer", + "const": 0 + } } }, "responseHeaders": { "type": "object", "additionalProperties": false, - "required": ["Content-Type", "Cache-Control", "X-Context-Request-Id"], + "required": [ + "Content-Type", + "Cache-Control", + "X-Context-Request-Id" + ], "properties": { - "Content-Type": {"const": "application/json"}, - "Cache-Control": {"const": "no-store"}, - "X-Context-Request-Id": {"$ref": "#/$defs/nonEmptyString"} + "Content-Type": { + "const": "application/json" + }, + "Cache-Control": { + "const": "no-store" + }, + "X-Context-Request-Id": { + "$ref": "#/$defs/nonEmptyString" + } } }, "packageOrError": { "type": "object", "additionalProperties": false, "minProperties": 2, - "required": ["kind"], + "required": [ + "kind" + ], "properties": { - "kind": {"$ref": "#/$defs/nonEmptyString"}, - "packageCount": {"type": "integer", "minimum": 0}, - "crossOrganizationResourceDetailCount": {"type": "integer", "minimum": 0}, - "coverageStatus": {"$ref": "#/$defs/nonEmptyString"}, - "coverageReason": {"$ref": "#/$defs/nonEmptyString"}, - "evidenceFields": {"$ref": "#/$defs/stringArray"}, - "deniedFieldCountExposed": {"type": "boolean"}, - "evidenceResourceRefs": {"$ref": "#/$defs/stringArray"}, - "gap": {"$ref": "#/$defs/nonEmptyString"}, - "sourceRefs": {"$ref": "#/$defs/stringArray"}, - "expandedSourceCallCount": {"type": "integer", "minimum": 0}, - "stalePackageReturned": {"type": "boolean"}, - "revokedResourceDetailCount": {"type": "integer", "minimum": 0}, - "evidenceRefs": {"$ref": "#/$defs/stringArray"}, - "deniedCandidateCountExposed": {"type": "boolean"}, - "blocksPerPackage": {"type": "integer", "minimum": 0}, - "evidencePerPackage": {"type": "integer", "minimum": 0}, - "unauthorizedFieldCount": {"type": "integer", "const": 0}, - "unauthorizedEvidenceRefCount": {"type": "integer", "const": 0}, - "contextPackageCreated": {"type": "boolean"}, - "trustedContextConstructedFromBody": {"type": "boolean"}, - "reasonVisibleToWorker": {"$ref": "#/$defs/nonEmptyString"}, - "newReceiptCreated": {"type": "boolean"}, - "aclModeUsed": {"type": ["string", "null"], "minLength": 1}, - "weakFallbackCount": {"type": "integer", "minimum": 0}, - "capabilityReportedAsPass": {"type": "boolean"}, - "citationFieldsReturned": {"type": "integer", "minimum": 0}, - "capabilityStatus": {"$ref": "#/$defs/nonEmptyString"}, - "deniedCountExposed": {"type": "boolean", "const": false}, - "existenceDetailCount": {"type": "integer", "const": 0}, - "actionTicketCreated": {"type": "boolean"}, - "contextTicketConsumed": {"type": "boolean"} + "kind": { + "$ref": "#/$defs/nonEmptyString" + }, + "packageCount": { + "type": "integer", + "minimum": 0 + }, + "crossOrganizationResourceDetailCount": { + "type": "integer", + "minimum": 0 + }, + "coverageStatus": { + "$ref": "#/$defs/nonEmptyString" + }, + "coverageReason": { + "$ref": "#/$defs/nonEmptyString" + }, + "evidenceFields": { + "$ref": "#/$defs/stringArray" + }, + "deniedFieldCountExposed": { + "type": "boolean" + }, + "evidenceResourceRefs": { + "$ref": "#/$defs/stringArray" + }, + "gap": { + "$ref": "#/$defs/nonEmptyString" + }, + "sourceRefs": { + "$ref": "#/$defs/stringArray" + }, + "expandedSourceCallCount": { + "type": "integer", + "minimum": 0 + }, + "stalePackageReturned": { + "type": "boolean" + }, + "revokedResourceDetailCount": { + "type": "integer", + "minimum": 0 + }, + "evidenceRefs": { + "$ref": "#/$defs/stringArray" + }, + "deniedCandidateCountExposed": { + "type": "boolean" + }, + "blocksPerPackage": { + "type": "integer", + "minimum": 0 + }, + "evidencePerPackage": { + "type": "integer", + "minimum": 0 + }, + "unauthorizedFieldCount": { + "type": "integer", + "const": 0 + }, + "unauthorizedEvidenceRefCount": { + "type": "integer", + "const": 0 + }, + "contextPackageCreated": { + "type": "boolean" + }, + "trustedContextConstructedFromBody": { + "type": "boolean" + }, + "reasonVisibleToWorker": { + "$ref": "#/$defs/nonEmptyString" + }, + "newReceiptCreated": { + "type": "boolean" + }, + "aclModeUsed": { + "type": [ + "string", + "null" + ], + "minLength": 1 + }, + "weakFallbackCount": { + "type": "integer", + "minimum": 0 + }, + "capabilityReportedAsPass": { + "type": "boolean" + }, + "citationFieldsReturned": { + "type": "integer", + "minimum": 0 + }, + "capabilityStatus": { + "$ref": "#/$defs/nonEmptyString" + }, + "deniedCountExposed": { + "type": "boolean", + "const": false + }, + "existenceDetailCount": { + "type": "integer", + "const": 0 + }, + "actionTicketCreated": { + "type": "boolean" + }, + "contextTicketConsumed": { + "type": "boolean" + } } }, "evidenceMetrics": { "type": "object", "additionalProperties": false, - "required": ["unauthorizedEvidenceCount", "unauthorizedContentBytes", "missingContextFallbackCount", "outboundBytes"], + "required": [ + "unauthorizedEvidenceCount", + "unauthorizedContentBytes", + "missingContextFallbackCount", + "outboundBytes" + ], "properties": { - "unauthorizedEvidenceCount": {"type": "integer", "minimum": 0, "const": 0}, - "unauthorizedContentBytes": {"type": "integer", "minimum": 0, "const": 0}, - "missingContextFallbackCount": {"type": "integer", "minimum": 0, "const": 0}, - "outboundBytes": {"type": "integer", "minimum": 0} + "unauthorizedEvidenceCount": { + "type": "integer", + "minimum": 0, + "const": 0 + }, + "unauthorizedContentBytes": { + "type": "integer", + "minimum": 0, + "const": 0 + }, + "missingContextFallbackCount": { + "type": "integer", + "minimum": 0, + "const": 0 + }, + "outboundBytes": { + "type": "integer", + "minimum": 0 + } } }, "businessEffectMetrics": { "type": "object", "additionalProperties": false, - "required": ["wrongOrganizationEffectCount", "mutationEffectCount", "totalEffectsAfterScenario"], + "required": [ + "wrongOrganizationEffectCount", + "mutationEffectCount", + "totalEffectsAfterScenario" + ], "properties": { - "wrongOrganizationEffectCount": {"type": "integer", "minimum": 0, "const": 0}, - "mutationEffectCount": {"type": "integer", "minimum": 0}, - "totalEffectsAfterScenario": {"type": "integer", "minimum": 0} + "wrongOrganizationEffectCount": { + "type": "integer", + "minimum": 0, + "const": 0 + }, + "mutationEffectCount": { + "type": "integer", + "minimum": 0 + }, + "totalEffectsAfterScenario": { + "type": "integer", + "minimum": 0 + } } }, "ioMetrics": { "type": "object", "additionalProperties": false, - "required": ["providerCalls", "indexCalls", "modelCalls", "actionCalls"], + "required": [ + "providerCalls", + "indexCalls", + "modelCalls", + "actionCalls" + ], "properties": { - "providerCalls": {"type": "integer", "minimum": 0}, - "indexCalls": {"type": "integer", "minimum": 0}, - "modelCalls": {"type": "integer", "minimum": 0}, - "actionCalls": {"type": "integer", "minimum": 0} + "providerCalls": { + "type": "integer", + "minimum": 0 + }, + "indexCalls": { + "type": "integer", + "minimum": 0 + }, + "modelCalls": { + "type": "integer", + "minimum": 0 + }, + "actionCalls": { + "type": "integer", + "minimum": 0 + } } }, "expected": { "type": "object", "additionalProperties": false, - "required": ["externalResponse", "packageOrError", "evidence", "businessEffects", "io"], + "required": [ + "externalResponse", + "packageOrError", + "evidence", + "businessEffects", + "io" + ], "properties": { - "externalResponse": {"$ref": "#/$defs/externalResponse"}, - "packageOrError": {"$ref": "#/$defs/packageOrError"}, - "evidence": {"$ref": "#/$defs/evidenceMetrics"}, - "businessEffects": {"$ref": "#/$defs/businessEffectMetrics"}, - "io": {"$ref": "#/$defs/ioMetrics"} + "externalResponse": { + "$ref": "#/$defs/externalResponse" + }, + "packageOrError": { + "$ref": "#/$defs/packageOrError" + }, + "evidence": { + "$ref": "#/$defs/evidenceMetrics" + }, + "businessEffects": { + "$ref": "#/$defs/businessEffectMetrics" + }, + "io": { + "$ref": "#/$defs/ioMetrics" + } } }, "fixture": { @@ -1007,28 +2246,49 @@ "authorityRefs" ], "properties": { - "id": {"$ref": "#/$defs/fixtureId"}, - "title": {"$ref": "#/$defs/nonEmptyString"}, + "id": { + "$ref": "#/$defs/fixtureId" + }, + "title": { + "$ref": "#/$defs/nonEmptyString" + }, "decisionStatus": { "type": "string", - "enum": ["accepted", "future_case"] + "enum": [ + "accepted", + "future_case" + ] + }, + "carrier": { + "$ref": "#/$defs/carrier" + }, + "setup": { + "$ref": "#/$defs/setup" + }, + "adversarialMutation": { + "$ref": "#/$defs/adversarialMutation" + }, + "operation": { + "$ref": "#/$defs/operation" + }, + "expected": { + "$ref": "#/$defs/expected" }, - "carrier": {"$ref": "#/$defs/carrier"}, - "setup": {"$ref": "#/$defs/setup"}, - "adversarialMutation": {"$ref": "#/$defs/adversarialMutation"}, - "operation": {"$ref": "#/$defs/operation"}, - "expected": {"$ref": "#/$defs/expected"}, "invariantRefs": { "type": "array", "minItems": 1, "uniqueItems": true, - "items": {"$ref": "#/$defs/invariantId"} + "items": { + "$ref": "#/$defs/invariantId" + } }, "authorityRefs": { "type": "array", "minItems": 1, "uniqueItems": true, - "items": {"$ref": "#/$defs/authorityRef"} + "items": { + "$ref": "#/$defs/authorityRef" + } } }, "allOf": [ @@ -1037,12 +2297,21 @@ "properties": { "carrier": { "properties": { - "statusAtM0": {"enum": ["unavailable", "future"]} + "statusAtM0": { + "enum": [ + "unavailable", + "future" + ] + } }, - "required": ["statusAtM0"] + "required": [ + "statusAtM0" + ] } }, - "required": ["carrier"] + "required": [ + "carrier" + ] }, "then": { "properties": { @@ -1050,10 +2319,18 @@ "properties": { "io": { "properties": { - "providerCalls": {"const": 0}, - "indexCalls": {"const": 0}, - "modelCalls": {"const": 0}, - "actionCalls": {"const": 0} + "providerCalls": { + "const": 0 + }, + "indexCalls": { + "const": 0 + }, + "modelCalls": { + "const": 0 + }, + "actionCalls": { + "const": 0 + } } } } @@ -1064,9 +2341,13 @@ { "if": { "properties": { - "id": {"const": "ACCEPT-002"} + "id": { + "const": "ACCEPT-002" + } }, - "required": ["id"] + "required": [ + "id" + ] }, "then": { "properties": { @@ -1083,9 +2364,13 @@ { "if": { "properties": { - "id": {"const": "ACCEPT-008"} + "id": { + "const": "ACCEPT-008" + } }, - "required": ["id"] + "required": [ + "id" + ] }, "then": { "properties": { @@ -1102,9 +2387,13 @@ { "if": { "properties": { - "id": {"const": "ACCEPT-012"} + "id": { + "const": "ACCEPT-012" + } }, - "required": ["id"] + "required": [ + "id" + ] }, "then": { "properties": { diff --git a/eval/catalogs/security-invariants.yaml b/eval/catalogs/security-invariants.yaml index 29901223..21423093 100644 --- a/eval/catalogs/security-invariants.yaml +++ b/eval/catalogs/security-invariants.yaml @@ -11,7 +11,8 @@ "#19", "#48", "#63", - "#65" + "#65", + "#66" ], "documentRefs": [ "README.md", @@ -27,9 +28,10 @@ "docs/decisions/0031-persist-authorized-context-run-lineage.md", "docs/decisions/0032-bind-materialized-fields-to-membership-projection-rights.md", "docs/decisions/0045-redeem-private-delivery-evidence-at-ingress.md", - "docs/decisions/0046-bind-egress-to-one-exact-package-hop.md" + "docs/decisions/0046-bind-egress-to-one-exact-package-hop.md", + "docs/decisions/0047-freeze-openapi-v0-through-one-runtime-path.md" ], - "reconciliation": "Issue #2 fixes the product and testing decisions, issue #5 requires exactly fifteen release invariants and twelve canonical acceptance fixtures, and ADR-0019 resolves the later nineteen-label prose expansion without weakening any safeguard. Issue #15 activates only Organization-level next-request resolve(Acquire) revocation evidence under REVOCATION-006: PG-REVOCATION-006, RUN-006, and CACHE-002 are active while BLOB-002 and Continue, citation, Policy-Epoch-bound WorkerLease, production ContextAccessTicket/ActionTicket, audit, outbox, cleanup, finer-epoch, UI, and external-admin carriers remain future or NOT_ACTIVE. Issue #16 activates only the M0 refusal gate for unavailable Continue, OpenCitation, and server-owned unavailable Acquire plans: its real continuation, citation, federated/source-native, and File carriers remain future, while its Runtime and HTTP refusal surfaces prove generic outcomes before content I/O. Issue #17 activates only the signed one-shot persistent no-op durable-job WorkerLease subcarrier under WORKER-LEASE-007. It binds one exact worker audience but no end-user delivery audience or Policy Epoch, and proves only LEASE-SIGNING-017, PG-WORKER-LEASE-NOOP-017, and WORKER-LEASE-REPLAY-007; Source, Resource, Revision, Policy Epoch, end-user delivery audience, idempotency, generation, business mutation, outbox, File publication, and the full ACCEPT-008 matrix remain deferred or NOT_ACTIVE. Issue #18 activates only distinct signed synthetic ContextAccessTicket Provider-read and ActionTicket no-op channel-action subcarriers under ACTION-SEPARATION-014, with current Organization-v0 Policy Epoch validation. TICKET-AUDIENCE-018 and PG-TICKET-EPOCH-018 do not activate production ContextProvider integration, ContextRuntime ticket integration, BotDelivery, full M2 ActionPlane.prepare/perform, a real Sender or external effect, payload/destination/approval/idempotency binding, durable one-shot/replay/reconciliation, or full ACCEPT-012 PASS; those remain future or NOT_ACTIVE. Issue #19 activates only the current Acquire authorized-only ContextRun and restricted delivered-empty DecisionAudit subcarrier under TRACE-REDACTION-012. DIGEST-019, RUN-LINEAGE-019, AUTHORIZED-RUN-019, and PG-TRACE-REDACTION-012 prove deterministic Package and Organization-bound query digests, retained-UserActor-transaction persistence, decisionRef resolution, redaction, and short-lived exact-Organization operator ticket reads with no application-role table access; the supported reader commits deletion before returning, while a direct caller rollback is not claimed as durable exactly-once redemption. Raw query retention, full ContextPackage body retention, unauthenticated transport failures as ContextRuns, cross-Organization analytics, and general observability redaction remain NOT_ACTIVE. Issue #48 activates only the current ACCEPT-002 authenticated HTTP Acquire Membership field-projection carrier under SCOPE-INTERSECTION-004, INDEX-NOT-AUTHORITY-005, and TRACE-REDACTION-012. PROP-FIELD-PROJECTION-048, PG-FIELD-PROJECTION-048, and HTTP-ACCEPT-002-048 bind one current Membership/version field ceiling to same-transaction FORCE-RLS reduction, the sealed AuthorizationKernel, AuthorizedProjection and Evidence integrity, and authorized-only ContextRun/audit persistence. General permission DSLs, caller-authored projection lists, CandidateRef or index field authority, production Provider/source-native ACL negotiation, Supply publication, File/Base field ACL, typed fields, Continue/OpenCitation, and Issue #20 runner substitution remain future or NOT_ACTIVE. Issue #63 activates only the digest-only private authenticated HTTP Acquire DeliveryEvidenceRef carrier under TRANSPORT-UNTRUSTED-008. PROP-DELIVERY-EVIDENCE-063, PG-DELIVERY-EVIDENCE-063, HTTP-DELIVERY-EVIDENCE-063, and FILE-DELIVERY-EVIDENCE-063 prove exact service/request/Organization/asker/Membership-version/destination/consumer/purpose/audience/epoch/lifetime binding, stable identical retry identity, role isolation, expiry cleanup, pre-content generic rejection, and one File-backed sealed Runtime delivery. Group AudienceSnapshot, group/public DeliveryEvidenceRef, OpenCitation, production ModelGateway, ActionPlane, the BotDelivery application, frozen OpenAPI compatibility, and the generated TypeScript SDK remain future or NOT_ACTIVE. Issue #65 activates only one opaque digest-only model or channel EgressGrant after final Package policy, exact atomic PostgreSQL redemption and restricted audit, nominal BotDelivery inputs, and deterministic network-free ModelGateway or Sender-preflight spies under EGRESS-011. PROP-EGRESS-011, PG-EGRESS-011, and RUNTIME-EGRESS-011 prove exact Package/Organization/purpose/audience/epoch/hop/profile/lifetime binding and zero additional bytes on replay. Real model/provider calls, a real Sender or channel write, ActionTicket effects, group AudienceSnapshot revalidation, the BotDelivery application process, and a generated SDK consumer remain future or NOT_ACTIVE. The canonical set is IDs 001 through 012, 014, 015, and 019: CACHE-SCOPE-013 remains a preregistered conditional extension; AUDIENCE-016 is absorbed by SCOPE-INTERSECTION-004 and EGRESS-011; ACL-PROOF-017 is absorbed by INDEX-NOT-AUTHORITY-005 and REVOCATION-006; DELIVERY-EVIDENCE-018 is absorbed by TRANSPORT-UNTRUSTED-008. ACCEPT-001 through ACCEPT-012 follow ADR-0019's category order. Protected-asset references A-01 through A-08 refer, in order, to the eight bullets in the threat model's Protected assets section. Every expectedEvidence value below is a stable planned case identifier, not a claim that the case ran or passed; only an exact activation record upgrades named evidence, while fixture carrier status and the explicit M0 oracle preserve every other accepted-versus-active distinction." + "reconciliation": "Issue #2 fixes the product and testing decisions, issue #5 requires exactly fifteen release invariants and twelve canonical acceptance fixtures, and ADR-0019 resolves the later nineteen-label prose expansion without weakening any safeguard. Issue #15 activates only Organization-level next-request resolve(Acquire) revocation evidence under REVOCATION-006: PG-REVOCATION-006, RUN-006, and CACHE-002 are active while BLOB-002 and Continue, citation, Policy-Epoch-bound WorkerLease, production ContextAccessTicket/ActionTicket, audit, outbox, cleanup, finer-epoch, UI, and external-admin carriers remain future or NOT_ACTIVE. Issue #16 activates only the M0 refusal gate for unavailable Continue, OpenCitation, and server-owned unavailable Acquire plans: its real continuation, citation, federated/source-native, and File carriers remain future, while its Runtime and HTTP refusal surfaces prove generic outcomes before content I/O. Issue #17 activates only the signed one-shot persistent no-op durable-job WorkerLease subcarrier under WORKER-LEASE-007. It binds one exact worker audience but no end-user delivery audience or Policy Epoch, and proves only LEASE-SIGNING-017, PG-WORKER-LEASE-NOOP-017, and WORKER-LEASE-REPLAY-007; Source, Resource, Revision, Policy Epoch, end-user delivery audience, idempotency, generation, business mutation, outbox, File publication, and the full ACCEPT-008 matrix remain deferred or NOT_ACTIVE. Issue #18 activates only distinct signed synthetic ContextAccessTicket Provider-read and ActionTicket no-op channel-action subcarriers under ACTION-SEPARATION-014, with current Organization-v0 Policy Epoch validation. TICKET-AUDIENCE-018 and PG-TICKET-EPOCH-018 do not activate production ContextProvider integration, ContextRuntime ticket integration, BotDelivery, full M2 ActionPlane.prepare/perform, a real Sender or external effect, payload/destination/approval/idempotency binding, durable one-shot/replay/reconciliation, or full ACCEPT-012 PASS; those remain future or NOT_ACTIVE. Issue #19 activates only the current Acquire authorized-only ContextRun and restricted delivered-empty DecisionAudit subcarrier under TRACE-REDACTION-012. DIGEST-019, RUN-LINEAGE-019, AUTHORIZED-RUN-019, and PG-TRACE-REDACTION-012 prove deterministic Package and Organization-bound query digests, retained-UserActor-transaction persistence, decisionRef resolution, redaction, and short-lived exact-Organization operator ticket reads with no application-role table access; the supported reader commits deletion before returning, while a direct caller rollback is not claimed as durable exactly-once redemption. Raw query retention, full ContextPackage body retention, unauthenticated transport failures as ContextRuns, cross-Organization analytics, and general observability redaction remain NOT_ACTIVE. Issue #48 activates only the current ACCEPT-002 authenticated HTTP Acquire Membership field-projection carrier under SCOPE-INTERSECTION-004, INDEX-NOT-AUTHORITY-005, and TRACE-REDACTION-012. PROP-FIELD-PROJECTION-048, PG-FIELD-PROJECTION-048, and HTTP-ACCEPT-002-048 bind one current Membership/version field ceiling to same-transaction FORCE-RLS reduction, the sealed AuthorizationKernel, AuthorizedProjection and Evidence integrity, and authorized-only ContextRun/audit persistence. General permission DSLs, caller-authored projection lists, CandidateRef or index field authority, production Provider/source-native ACL negotiation, Supply publication, File/Base field ACL, typed fields, Continue/OpenCitation, and Issue #20 runner substitution remain future or NOT_ACTIVE. Issue #63 activates only the digest-only private authenticated HTTP Acquire DeliveryEvidenceRef carrier under TRANSPORT-UNTRUSTED-008. PROP-DELIVERY-EVIDENCE-063, PG-DELIVERY-EVIDENCE-063, HTTP-DELIVERY-EVIDENCE-063, and FILE-DELIVERY-EVIDENCE-063 prove exact service/request/Organization/asker/Membership-version/destination/consumer/purpose/audience/epoch/lifetime binding, stable identical retry identity, role isolation, expiry cleanup, pre-content generic rejection, and one File-backed sealed Runtime delivery. Group AudienceSnapshot, group/public DeliveryEvidenceRef, OpenCitation, production ModelGateway, ActionPlane, the BotDelivery application, frozen OpenAPI compatibility, and the generated TypeScript SDK remain future or NOT_ACTIVE. Issue #65 activates only one opaque digest-only model or channel EgressGrant after final Package policy, exact atomic PostgreSQL redemption and restricted audit, nominal BotDelivery inputs, and deterministic network-free ModelGateway or Sender-preflight spies under EGRESS-011. PROP-EGRESS-011, PG-EGRESS-011, and RUNTIME-EGRESS-011 prove exact Package/Organization/purpose/audience/epoch/hop/profile/lifetime binding and zero additional bytes on replay. Real model/provider calls, a real Sender or channel write, ActionTicket effects, group AudienceSnapshot revalidation, the BotDelivery application process, and a generated SDK consumer remain future or NOT_ACTIVE. Issue #66 activates the frozen public POST /v0/resolve OpenAPI carrier under TRANSPORT-UNTRUSTED-008. OPENAPI-CONTRACT-066, OPENAPI-BREAKING-066, HTTP-V0-066, and PG-RUNTIME-RELEASE-066 prove one public closed operation, deterministic immutable snapshot and breaking-change refusal, a hidden v1 bridge through the same handler and sealed Runtime path, and exact read-only observation of the active Learning-promoted release with fail-closed missing-release behavior before content work. Generated TypeScript SDK conformance, a production BotDelivery caller, Continue and OpenCitation redemption, MCP, group AudienceSnapshot, and external effects remain future or NOT_ACTIVE. The canonical set is IDs 001 through 012, 014, 015, and 019: CACHE-SCOPE-013 remains a preregistered conditional extension; AUDIENCE-016 is absorbed by SCOPE-INTERSECTION-004 and EGRESS-011; ACL-PROOF-017 is absorbed by INDEX-NOT-AUTHORITY-005 and REVOCATION-006; DELIVERY-EVIDENCE-018 is absorbed by TRANSPORT-UNTRUSTED-008. ACCEPT-001 through ACCEPT-012 follow ADR-0019's category order. Protected-asset references A-01 through A-08 refer, in order, to the eight bullets in the threat model's Protected assets section. Every expectedEvidence value below is a stable planned case identifier, not a claim that the case ran or passed; only an exact activation record upgrades named evidence, while fixture carrier status and the explicit M0 oracle preserve every other accepted-versus-active distinction." }, "hardOracles": [ { @@ -73,9 +75,23 @@ "oracle": "An injected pre-revocation authorization decision or a mid-resolve epoch change fails the final current-epoch gate and delivers zero stale Evidence without relying on candidate or content removal." } ], - "deferredEvidence": ["BLOB-002"], - "futureCarriers": ["Continue", "OpenCitation", "Policy-Epoch-bound WorkerLease", "production ContextAccessTicket", "production ActionTicket"], - "notActive": ["DecisionAudit", "outbox", "cleanup", "Source/Resource Policy Epochs", "UI/external admin"] + "deferredEvidence": [ + "BLOB-002" + ], + "futureCarriers": [ + "Continue", + "OpenCitation", + "Policy-Epoch-bound WorkerLease", + "production ContextAccessTicket", + "production ActionTicket" + ], + "notActive": [ + "DecisionAudit", + "outbox", + "cleanup", + "Source/Resource Policy Epochs", + "UI/external admin" + ] }, { "issueRef": "#16", @@ -96,9 +112,22 @@ "oracle": "The closed HTTP and OpenAPI request union admits its declared variants, maps known unavailable capabilities to generic 200 domain outcomes before configured scope-authority or content I/O, rejects unknown fields and every query string with 422, and serializes no internal cause or protected detail." } ], - "deferredEvidence": ["real-continuation-redemption", "real-citation-redemption", "real-federated-source-native-authorization"], - "futureCarriers": ["Continue", "OpenCitation", "federated/source-native ContextProvider"], - "notActive": ["continuation issuance/redemption", "citation locator redemption", "federated Provider/source-native ACL I/O", "File publication"] + "deferredEvidence": [ + "real-continuation-redemption", + "real-citation-redemption", + "real-federated-source-native-authorization" + ], + "futureCarriers": [ + "Continue", + "OpenCitation", + "federated/source-native ContextProvider" + ], + "notActive": [ + "continuation issuance/redemption", + "citation locator redemption", + "federated Provider/source-native ACL I/O", + "File publication" + ] }, { "issueRef": "#17", @@ -124,9 +153,35 @@ "oracle": "The real worker application seam completes exactly one persistent no-op job with its server-minted lease; replay returns only generic work-not-available and leaves the completed durable state unchanged." } ], - "deferredEvidence": ["PROP-WORKER-LEASE-007", "PG-WORKER-LEASE-007", "DB-011", "JOB-001", "JOB-005", "full ACCEPT-008 per-binding matrix"], - "futureCarriers": ["Source-bound acquisition", "Resource/Revision mutation", "Policy-Epoch/end-user-delivery-audience-bound WorkerLease", "idempotency/generation-bound business mutation", "outbox dispatch", "File publication"], - "notActive": ["Source", "Resource", "Revision", "Policy Epoch", "end-user delivery audience", "idempotency", "generation", "content-bearing mutation", "outbox", "File publication", "full ACCEPT-008 PASS"] + "deferredEvidence": [ + "PROP-WORKER-LEASE-007", + "PG-WORKER-LEASE-007", + "DB-011", + "JOB-001", + "JOB-005", + "full ACCEPT-008 per-binding matrix" + ], + "futureCarriers": [ + "Source-bound acquisition", + "Resource/Revision mutation", + "Policy-Epoch/end-user-delivery-audience-bound WorkerLease", + "idempotency/generation-bound business mutation", + "outbox dispatch", + "File publication" + ], + "notActive": [ + "Source", + "Resource", + "Revision", + "Policy Epoch", + "end-user delivery audience", + "idempotency", + "generation", + "content-bearing mutation", + "outbox", + "File publication", + "full ACCEPT-008 PASS" + ] }, { "issueRef": "#18", @@ -147,9 +202,25 @@ "oracle": "The real PostgreSQL non-owner UserActor transaction exercises both ticket types before a trusted Control transaction commits an Organization epoch bump, then rejects both previously valid tickets before their separate synthetic read and action effect counters increment. This proves current Organization-v0 epoch binding, not durable ticket consumption or a real external effect." } ], - "deferredEvidence": ["PROP-ACTION-SEPARATION-014", "PG-ACTION-SEPARATION-014", "ACTION-001 through ACTION-009", "full ACCEPT-012 matrix"], - "futureCarriers": ["production ContextProvider read/projection", "ContextRuntime ticket integration", "BotDelivery", "M2 ActionPlane and real Sender"], - "notActive": ["full M2 ActionPlane.prepare/perform", "real Sender/external effect", "payload/destination/approval/idempotency", "durable one-shot/replay/reconciliation", "full ACCEPT-012 PASS"] + "deferredEvidence": [ + "PROP-ACTION-SEPARATION-014", + "PG-ACTION-SEPARATION-014", + "ACTION-001 through ACTION-009", + "full ACCEPT-012 matrix" + ], + "futureCarriers": [ + "production ContextProvider read/projection", + "ContextRuntime ticket integration", + "BotDelivery", + "M2 ActionPlane and real Sender" + ], + "notActive": [ + "full M2 ActionPlane.prepare/perform", + "real Sender/external effect", + "payload/destination/approval/idempotency", + "durable one-shot/replay/reconciliation", + "full ACCEPT-012 PASS" + ] }, { "issueRef": "#19", @@ -180,9 +251,24 @@ "oracle": "Real PostgreSQL FORCE RLS permits Runtime INSERT only for the exact current UserActor, gives security-operator and Control no direct table reads, and permits one exact safe ContextRun projection when Control issues a digest-only 60-second Organization-and-decision-bound ticket that security-operator deletes before projection; a committed read, arbitrary GUCs, wrong bindings, expiry, and revocation disclose no additional row, while direct-caller rollback is not claimed as durable exactly-once redemption and DecisionAudit remains seven redacted lineage/category columns." } ], - "deferredEvidence": ["PROP-TRACE-REDACTION-012 across every future observability carrier", "OBS-002 secret scanning beyond the activated query/key contracts", "OBS-003 production debug-endpoint authorization"], - "futureCarriers": ["Continue and OpenCitation ContextRun lineage", "full retrieval candidate/ranking traces", "authorized feedback and golden-set extraction", "explicitly approved full-Package retention"], - "notActive": ["raw query retention", "full ContextPackage body retention", "unauthenticated transport failures as ContextRuns", "cross-Organization analytics", "general logs/metrics/debug/evaluation/Learning redaction coverage"] + "deferredEvidence": [ + "PROP-TRACE-REDACTION-012 across every future observability carrier", + "OBS-002 secret scanning beyond the activated query/key contracts", + "OBS-003 production debug-endpoint authorization" + ], + "futureCarriers": [ + "Continue and OpenCitation ContextRun lineage", + "full retrieval candidate/ranking traces", + "authorized feedback and golden-set extraction", + "explicitly approved full-Package retention" + ], + "notActive": [ + "raw query retention", + "full ContextPackage body retention", + "unauthenticated transport failures as ContextRuns", + "cross-Organization analytics", + "general logs/metrics/debug/evaluation/Learning redaction coverage" + ] }, { "issueRef": "#48", @@ -208,9 +294,26 @@ "oracle": "The authenticated HTTP Acquire seam reuses one content-free CandidateRef for same-Organization limited and full Memberships; the limited Package contains only status=open while the full Package contains both authorized fields, and after the limited right is removed the next resolve returns generic empty coverage. The limited response, ContextRun, and DecisionAudit contain zero private_note or secret bytes and no denied names, identifiers, or counts." } ], - "deferredEvidence": ["production Provider-native field authorization", "File and Base source-field authorization", "typed or non-text field projection"], - "futureCarriers": ["production ContextProvider native field projection", "File and Base ingestion field ACL", "Continue and OpenCitation field projection", "field-policy change independent of Membership version"], - "notActive": ["general permission DSL", "caller-authored projection lists", "CandidateRef or index field authority", "Provider capability negotiation or source-native field ACL", "Supply publication and field classification", "ranking or relevance-model field authority", "Issue #20 gate or runner substitution"] + "deferredEvidence": [ + "production Provider-native field authorization", + "File and Base source-field authorization", + "typed or non-text field projection" + ], + "futureCarriers": [ + "production ContextProvider native field projection", + "File and Base ingestion field ACL", + "Continue and OpenCitation field projection", + "field-policy change independent of Membership version" + ], + "notActive": [ + "general permission DSL", + "caller-authored projection lists", + "CandidateRef or index field authority", + "Provider capability negotiation or source-native field ACL", + "Supply publication and field classification", + "ranking or relevance-model field authority", + "Issue #20 gate or runner substitution" + ] }, { "issueRef": "#63", @@ -241,9 +344,25 @@ "oracle": "The real File-backed authenticated HTTP Acquire redeems private evidence inside the current UserActor transaction and still proves CandidateRef through the sealed AuthorizationKernel to AuthorizedProjection; an identical retry returns authorized content under one stored logical redemption identity, and both private responses plus their ContextRuns omit the bearer and raw private delivery bindings." } ], - "deferredEvidence": ["group AudienceSnapshot DeliveryEvidenceRef", "frozen OpenAPI and generated TypeScript SDK carrier", "production BotDelivery caller"], - "futureCarriers": ["public group DeliveryEvidenceRef", "OpenCitation delivery evidence", "generated TypeScript SDK", "private BotDelivery application"], - "notActive": ["group delivery", "AudienceSnapshot", "production ModelGateway", "ActionPlane", "BotDelivery application", "OpenAPI compatibility freeze", "generated SDK"] + "deferredEvidence": [ + "group AudienceSnapshot DeliveryEvidenceRef", + "generated TypeScript SDK carrier", + "production BotDelivery caller" + ], + "futureCarriers": [ + "public group DeliveryEvidenceRef", + "OpenCitation delivery evidence", + "generated TypeScript SDK", + "private BotDelivery application" + ], + "notActive": [ + "group delivery", + "AudienceSnapshot", + "production ModelGateway", + "ActionPlane", + "BotDelivery application", + "generated SDK" + ] }, { "issueRef": "#65", @@ -269,9 +388,76 @@ "oracle": "A real File-backed authenticated HTTP Acquire proves CandidateRef through the sealed AuthorizationKernel to an audience-bound ContextPackage, returns one model grant only after final policy, and the independent egress role permits exactly one deterministic ModelGateway spy request; replay emits zero additional model bytes." } ], - "deferredEvidence": ["production provider ModelGateway conformance", "production Sender and ActionPlane effect conformance", "group AudienceSnapshot send-time revalidation"], - "futureCarriers": ["production ModelGateway", "production Sender preflight", "ActionPlane prepare and perform", "group-public and asker-private delivery"], - "notActive": ["real model or provider network call", "real Sender or channel write", "ActionTicket or external effect", "group AudienceSnapshot", "BotDelivery application process", "generated SDK consumer"] + "deferredEvidence": [ + "production provider ModelGateway conformance", + "production Sender and ActionPlane effect conformance", + "group AudienceSnapshot send-time revalidation" + ], + "futureCarriers": [ + "production ModelGateway", + "production Sender preflight", + "ActionPlane prepare and perform", + "group-public and asker-private delivery" + ], + "notActive": [ + "real model or provider network call", + "real Sender or channel write", + "ActionTicket or external effect", + "group AudienceSnapshot", + "BotDelivery application process", + "generated SDK consumer" + ] + }, + { + "issueRef": "#66", + "invariantRef": "TRANSPORT-UNTRUSTED-008", + "carrier": "frozen public POST /v0/resolve OpenAPI contract", + "status": "active_fail_closed", + "policyEpochScope": "organization-v0", + "controlBoundary": "authenticated HTTP metadata -> closed ResolveWire -> current UserActor and active release observation -> sealed ContextRuntime.resolve -> closed ResolutionOutcome", + "testEvidence": [ + { + "id": "OPENAPI-CONTRACT-066", + "surface": "tests/unit/test_openapi_v0_contract.py", + "oracle": "The frozen document exposes exactly one public versioned operation with a closed Acquire, Continue, or OpenCitation body, closed outcome union, complete ContextPackage, bounded metadata and payloads, generic failure statuses, and no raw trusted identity or audience fields." + }, + { + "id": "OPENAPI-BREAKING-066", + "surface": "tests/unit/test_openapi_v0_snapshot.py", + "oracle": "The deterministic immutable snapshot and SHA-256 checksum gate reject current drift, base-commit mutation, and overwrite, while deliberate security, response, union, required-field, and type mutations prove the recursive gate rejects contract changes." + }, + { + "id": "HTTP-V0-066", + "surface": "tests/unit/test_http_trust_boundary.py::test_trusted_field_injection_is_closed_before_domain_execution tests/unit/test_http_unavailable_capabilities.py::test_accept_005_continue_is_generic_non_retryable_and_zero_io tests/process/test_processes.py::test_http_acquire_smoke_returns_the_empty_package_contract", + "oracle": "Public v0 rejects trusted-field injection and returns generic inactive-carrier outcomes before content work, while the process returns the frozen empty-package contract; a separate focused test proves the hidden v1 bridge shares the same sealed path." + }, + { + "id": "PG-RUNTIME-RELEASE-066", + "surface": "tests/integration/test_runtime_empty_package_integration.py::test_seeded_existing_organization_reaches_http_empty_package tests/integration/test_runtime_empty_package_integration.py::test_public_v0_resolve_without_supported_active_release_fails_before_content tests/integration/test_runtime_authorized_evidence_integration.py::test_real_postgres_http_delivers_only_exact_authorized_evidence_bidirectionally", + "oracle": "Real PostgreSQL proves the Package carries the exact Learning-promoted active manifest, tokenizer, and package schema observed under the current UserActor transaction with read-only Runtime RLS, while a missing or unsupported release returns one generic unavailable outcome before content I/O and without a ContextRun; the public v0 seam also proves CandidateRef through the sealed Kernel to exact AuthorizedProjection with real PostgreSQL." + } + ], + "deferredEvidence": [ + "generated TypeScript SDK conformance", + "production BotDelivery generated-SDK caller", + "Continue and OpenCitation redemption" + ], + "futureCarriers": [ + "generated TypeScript SDK", + "MCP", + "BotDelivery application", + "Continue redemption", + "OpenCitation redemption" + ], + "notActive": [ + "generated SDK consumer", + "MCP", + "BotDelivery application process", + "continuation issuance or redemption", + "citation persistence or redemption", + "group AudienceSnapshot", + "external effects" + ] } ], "invariants": [ @@ -279,22 +465,43 @@ "id": "TENANT-OWNERSHIP-001", "title": "Every tenant-owned object has explicit Organization ownership", "purpose": "Prevent orphaned or ambiguously owned rows, blobs, index records, jobs, traces, and Packages from entering a tenant path.", - "threatRefs": ["TM-02", "TM-08"], - "protectedAssets": ["A-01", "A-03", "A-08"], + "threatRefs": [ + "TM-02", + "TM-08" + ], + "protectedAssets": [ + "A-01", + "A-03", + "A-08" + ], "deterministicOracle": "Pass only when every classified tenant object has one Organization owner, missing-owner creation is rejected, and the orphan count is exactly 0; fail on any accepted missing owner or ambiguous ownership chain.", - "hardOracleRefs": ["Unauthorized Evidence", "wrong-Organization effect", "missing-context fallback"], + "hardOracleRefs": [ + "Unauthorized Evidence", + "wrong-Organization effect", + "missing-context fallback" + ], "applicability": { "mode": "required", "applicableFrom": "M0", "rationale": null }, "capabilityRef": "organization-owned-storage", - "requiredMilestones": ["M0", "M1"], + "requiredMilestones": [ + "M0", + "M1" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-TENANT-OWNERSHIP-001"], - "postgres": ["PG-TENANT-OWNERSHIP-001", "DB-008"], - "runtimeOrDelivery": ["RUNTIME-TENANT-OWNERSHIP-001"] + "property": [ + "PROP-TENANT-OWNERSHIP-001" + ], + "postgres": [ + "PG-TENANT-OWNERSHIP-001", + "DB-008" + ], + "runtimeOrDelivery": [ + "RUNTIME-TENANT-OWNERSHIP-001" + ] }, "authorityRefs": [ "docs/security/context-engine-threat-model.md#2-protected-assets", @@ -306,22 +513,40 @@ "id": "TENANT-FK-002", "title": "Tenant children cannot reference another Organization's parent", "purpose": "Make cross-Organization object graphs structurally unrepresentable even when application filters or identifiers are wrong.", - "threatRefs": ["TM-02"], - "protectedAssets": ["A-01", "A-03"], + "threatRefs": [ + "TM-02" + ], + "protectedAssets": [ + "A-01", + "A-03" + ], "deterministicOracle": "Pass only when every attempted cross-Organization child-to-parent write is rejected and creates exactly 0 rows; fail if any cross-Organization reference commits.", - "hardOracleRefs": ["Unauthorized Evidence", "wrong-Organization effect"], + "hardOracleRefs": [ + "Unauthorized Evidence", + "wrong-Organization effect" + ], "applicability": { "mode": "required", "applicableFrom": "M0", "rationale": null }, "capabilityRef": "composite-tenant-ownership", - "requiredMilestones": ["M0", "M1"], + "requiredMilestones": [ + "M0", + "M1" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-TENANT-FK-002"], - "postgres": ["PG-TENANT-FK-002", "DB-003"], - "runtimeOrDelivery": ["RUNTIME-TENANT-FK-002"] + "property": [ + "PROP-TENANT-FK-002" + ], + "postgres": [ + "PG-TENANT-FK-002", + "DB-003" + ], + "runtimeOrDelivery": [ + "RUNTIME-TENANT-FK-002" + ] }, "authorityRefs": [ "docs/security/context-engine-threat-model.md#6-threat-register", @@ -333,22 +558,44 @@ "id": "RLS-FAIL-CLOSED-003", "title": "Missing or invalid tenant transaction context fails closed", "purpose": "Ensure a non-owner database session never falls back to a default tenant or inherited pool context.", - "threatRefs": ["TM-01", "TM-02"], - "protectedAssets": ["A-01", "A-02", "A-06"], + "threatRefs": [ + "TM-01", + "TM-02" + ], + "protectedAssets": [ + "A-01", + "A-02", + "A-06" + ], "deterministicOracle": "Pass only when non-owner SELECT returns 0 tenant rows or a generic error, every tenant write errors, and missing-context fallback is exactly 0; fail if any tenant datum is read or written without the complete transaction-local context.", - "hardOracleRefs": ["Unauthorized Evidence", "missing-context fallback"], + "hardOracleRefs": [ + "Unauthorized Evidence", + "missing-context fallback" + ], "applicability": { "mode": "required", "applicableFrom": "M0", "rationale": null }, "capabilityRef": "non-owner-force-rls", - "requiredMilestones": ["M0"], + "requiredMilestones": [ + "M0" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-RLS-FAIL-CLOSED-003"], - "postgres": ["PG-RLS-FAIL-CLOSED-003", "DB-001", "DB-006", "DB-009"], - "runtimeOrDelivery": ["AUTH-003", "RUNTIME-RLS-FAIL-CLOSED-003"] + "property": [ + "PROP-RLS-FAIL-CLOSED-003" + ], + "postgres": [ + "PG-RLS-FAIL-CLOSED-003", + "DB-001", + "DB-006", + "DB-009" + ], + "runtimeOrDelivery": [ + "AUTH-003", + "RUNTIME-RLS-FAIL-CLOSED-003" + ] }, "authorityRefs": [ "docs/security/context-engine-threat-model.md#3-trust-boundaries", @@ -360,22 +607,50 @@ "id": "SCOPE-INTERSECTION-004", "title": "Agent and request scope can only narrow trusted scope", "purpose": "Keep EffectiveScope equal to the complete trusted authorization intersection while treating optional RequestNarrowing only as an additional restriction.", - "threatRefs": ["TM-01", "TM-11"], - "protectedAssets": ["A-01", "A-02", "A-04"], + "threatRefs": [ + "TM-01", + "TM-11" + ], + "protectedAssets": [ + "A-01", + "A-02", + "A-04" + ], "deterministicOracle": "Pass only when every generated Agent ceiling, request filter, and audience intersection produces a result set that is a subset of the trusted Principal scope; fail if adding an untrusted operand introduces any Resource or field, or if a missing required trusted operand yields a nonempty result.", - "hardOracleRefs": ["Unauthorized Evidence", "missing-context fallback"], + "hardOracleRefs": [ + "Unauthorized Evidence", + "missing-context fallback" + ], "applicability": { "mode": "required", "applicableFrom": "M0", "rationale": null }, "capabilityRef": "effective-scope-intersection", - "requiredMilestones": ["M0", "M1", "M5"], + "requiredMilestones": [ + "M0", + "M1", + "M5" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-SCOPE-INTERSECTION-004", "PROP-FIELD-PROJECTION-048"], - "postgres": ["PG-SCOPE-INTERSECTION-004", "DB-010", "PG-FIELD-PROJECTION-048"], - "runtimeOrDelivery": ["AUTH-006", "AUTH-007", "AUTH-010", "AUTH-011", "RUN-014", "HTTP-ACCEPT-002-048"] + "property": [ + "PROP-SCOPE-INTERSECTION-004", + "PROP-FIELD-PROJECTION-048" + ], + "postgres": [ + "PG-SCOPE-INTERSECTION-004", + "DB-010", + "PG-FIELD-PROJECTION-048" + ], + "runtimeOrDelivery": [ + "AUTH-006", + "AUTH-007", + "AUTH-010", + "AUTH-011", + "RUN-014", + "HTTP-ACCEPT-002-048" + ] }, "authorityRefs": [ "docs/agents/prd-contextengine-implementation.md#solution", @@ -389,22 +664,56 @@ "id": "INDEX-NOT-AUTHORITY-005", "title": "Candidate discovery is never authorization", "purpose": "Keep CandidateRef content-free and require every candidate or expansion to cross the sealed AuthorizationKernel before any content-bearing consumer.", - "threatRefs": ["TM-03", "TM-04", "TM-09"], - "protectedAssets": ["A-01", "A-04", "A-07"], + "threatRefs": [ + "TM-03", + "TM-04", + "TM-09" + ], + "protectedAssets": [ + "A-01", + "A-04", + "A-07" + ], "deterministicOracle": "Pass only when each raw candidate follows CandidateRef to AuthorizationKernel to AuthorizedProjection, denied projections and denied content bytes are exactly 0 at hydration, rerank, assembly, model, Package, and ContextRun seams; fail if index or cache output alone reaches any content-bearing consumer.", - "hardOracleRefs": ["Unauthorized Evidence"], + "hardOracleRefs": [ + "Unauthorized Evidence" + ], "applicability": { "mode": "required", "applicableFrom": "M0", "rationale": null }, "capabilityRef": "sealed-authorization-projection", - "requiredMilestones": ["M0", "M1", "M3"], + "requiredMilestones": [ + "M0", + "M1", + "M3" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-INDEX-NOT-AUTHORITY-005", "PROP-FIELD-PROJECTION-048"], - "postgres": ["PG-INDEX-NOT-AUTHORITY-005", "IDX-001", "IDX-002", "PG-FIELD-PROJECTION-048"], - "runtimeOrDelivery": ["RUN-002", "RUN-003", "RUN-013", "PROV-010", "PROV-013", "PROV-014", "PROV-015", "PROV-018", "PROV-019", "PROV-020", "HTTP-ACCEPT-002-048"] + "property": [ + "PROP-INDEX-NOT-AUTHORITY-005", + "PROP-FIELD-PROJECTION-048" + ], + "postgres": [ + "PG-INDEX-NOT-AUTHORITY-005", + "IDX-001", + "IDX-002", + "PG-FIELD-PROJECTION-048" + ], + "runtimeOrDelivery": [ + "RUN-002", + "RUN-003", + "RUN-013", + "PROV-010", + "PROV-013", + "PROV-014", + "PROV-015", + "PROV-018", + "PROV-019", + "PROV-020", + "HTTP-ACCEPT-002-048" + ] }, "authorityRefs": [ "docs/design/2026-07-18-context-engine-implementation-design.md#3-runtime-security-pipeline", @@ -418,22 +727,52 @@ "id": "REVOCATION-006", "title": "Observed revocation invalidates the next controlled operation", "purpose": "Prevent stale cache, index, continuation, citation, ticket, or ACL snapshots from preserving future access after Policy Epoch or source evidence changes.", - "threatRefs": ["TM-05", "TM-06", "TM-14"], - "protectedAssets": ["A-01", "A-04", "A-05"], + "threatRefs": [ + "TM-05", + "TM-06", + "TM-14" + ], + "protectedAssets": [ + "A-01", + "A-04", + "A-05" + ], "deterministicOracle": "Pass only when the first controlled operation after an observed revoke returns 0 revoked Evidence and 0 revoked content bytes without relying on asynchronous cleanup; fail if any stale decision, capability, cache, or strong-to-weak ACL fallback restores visibility.", - "hardOracleRefs": ["Unauthorized Evidence", "missing-context fallback"], + "hardOracleRefs": [ + "Unauthorized Evidence", + "missing-context fallback" + ], "applicability": { "mode": "required", "applicableFrom": "M1", "rationale": null }, "capabilityRef": "policy-epoch-revocation", - "requiredMilestones": ["M1", "M2"], + "requiredMilestones": [ + "M1", + "M2" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-REVOCATION-006"], - "postgres": ["PG-REVOCATION-006", "CACHE-002", "BLOB-002"], - "runtimeOrDelivery": ["RUN-006", "RUN-011", "CITE-002", "PROV-013", "PROV-014", "PROV-015", "PROV-018", "PROV-019", "PROV-020"] + "property": [ + "PROP-REVOCATION-006" + ], + "postgres": [ + "PG-REVOCATION-006", + "CACHE-002", + "BLOB-002" + ], + "runtimeOrDelivery": [ + "RUN-006", + "RUN-011", + "CITE-002", + "PROV-013", + "PROV-014", + "PROV-015", + "PROV-018", + "PROV-019", + "PROV-020" + ] }, "authorityRefs": [ "docs/design/2026-07-18-context-engine-implementation-design.md#44-revocation-linearization", @@ -446,22 +785,44 @@ "id": "WORKER-LEASE-007", "title": "Worker authority is exact-job, least-privilege, and one-shot", "purpose": "Prevent worker user impersonation and authority replay across Organizations, jobs, sources, operations, revisions, workloads, or generations.", - "threatRefs": ["TM-07", "TM-08"], - "protectedAssets": ["A-05", "A-06", "A-08"], + "threatRefs": [ + "TM-07", + "TM-08" + ], + "protectedAssets": [ + "A-05", + "A-06", + "A-08" + ], "deterministicOracle": "Pass only when mutation of any registered WorkerLease binding, stale generation, expiry, replay, or UserActor impersonation causes exactly 0 new durable mutations and 0 wrong-Organization effects; fail if a mismatched lease changes durable state.", - "hardOracleRefs": ["wrong-Organization effect", "missing-context fallback"], + "hardOracleRefs": [ + "wrong-Organization effect", + "missing-context fallback" + ], "applicability": { "mode": "required", "applicableFrom": "M1", "rationale": null }, "capabilityRef": "signed-worker-lease", - "requiredMilestones": ["M1", "M3"], + "requiredMilestones": [ + "M1", + "M3" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-WORKER-LEASE-007"], - "postgres": ["PG-WORKER-LEASE-007", "DB-011", "JOB-001", "JOB-005"], - "runtimeOrDelivery": ["WORKER-LEASE-REPLAY-007"] + "property": [ + "PROP-WORKER-LEASE-007" + ], + "postgres": [ + "PG-WORKER-LEASE-007", + "DB-011", + "JOB-001", + "JOB-005" + ], + "runtimeOrDelivery": [ + "WORKER-LEASE-REPLAY-007" + ] }, "authorityRefs": [ "docs/security/context-engine-threat-model.md#3-trust-boundaries", @@ -474,22 +835,52 @@ "id": "TRANSPORT-UNTRUSTED-008", "title": "Untrusted transport cannot author trusted invocation facts", "purpose": "Bind Organization, Principal, Membership, purpose, audience, and delivery facts only from authenticated ingress or a redeemed request-bound DeliveryEvidenceRef.", - "threatRefs": ["TM-01", "TM-10"], - "protectedAssets": ["A-02", "A-04", "A-05"], + "threatRefs": [ + "TM-01", + "TM-10" + ], + "protectedAssets": [ + "A-02", + "A-04", + "A-05" + ], "deterministicOracle": "Pass only when every caller-authored trusted field or invalid DeliveryEvidenceRef is rejected before provider, index, model, action, or Package work, with all four call counts and missing-context fallback exactly 0; fail if a body or replayed reference influences trusted context.", - "hardOracleRefs": ["Unauthorized Evidence", "wrong-Organization effect", "missing-context fallback"], + "hardOracleRefs": [ + "Unauthorized Evidence", + "wrong-Organization effect", + "missing-context fallback" + ], "applicability": { "mode": "required", "applicableFrom": "M1", "rationale": null }, "capabilityRef": "closed-trusted-ingress", - "requiredMilestones": ["M1", "M2"], + "requiredMilestones": [ + "M1", + "M2" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-TRANSPORT-UNTRUSTED-008", "PROP-DELIVERY-EVIDENCE-063"], - "postgres": ["PG-TRANSPORT-UNTRUSTED-008", "PG-DELIVERY-EVIDENCE-063"], - "runtimeOrDelivery": ["AUTH-002", "AUTH-009", "DELIV-001", "DELIV-002", "DELIV-003", "DELIV-004", "RUN-012", "HTTP-DELIVERY-EVIDENCE-063", "FILE-DELIVERY-EVIDENCE-063"] + "property": [ + "PROP-TRANSPORT-UNTRUSTED-008", + "PROP-DELIVERY-EVIDENCE-063" + ], + "postgres": [ + "PG-TRANSPORT-UNTRUSTED-008", + "PG-DELIVERY-EVIDENCE-063" + ], + "runtimeOrDelivery": [ + "AUTH-002", + "AUTH-009", + "DELIV-001", + "DELIV-002", + "DELIV-003", + "DELIV-004", + "RUN-012", + "HTTP-DELIVERY-EVIDENCE-063", + "FILE-DELIVERY-EVIDENCE-063" + ] }, "authorityRefs": [ "docs/design/2026-07-18-context-engine-implementation-design.md#21-contextcontrol", @@ -501,22 +892,44 @@ "id": "NON-ENUMERATION-009", "title": "Denied and nonexistent objects are externally equivalent", "purpose": "Prevent hidden Resource existence, counts, names, and denial branches from becoming a caller-visible side channel.", - "threatRefs": ["TM-02", "TM-18"], - "protectedAssets": ["A-01", "A-02", "A-07"], + "threatRefs": [ + "TM-02", + "TM-18" + ], + "protectedAssets": [ + "A-01", + "A-02", + "A-07" + ], "deterministicOracle": "Pass only when denied and missing probes have byte-identical status, body, headers, and domain outcome after documented per-run fields are normalized; fail on any existence-dependent external difference or leaked denied count. Statistical timing equality is not claimed before its separately preregistered M5 gate.", - "hardOracleRefs": ["Unauthorized Evidence"], + "hardOracleRefs": [ + "Unauthorized Evidence" + ], "applicability": { "mode": "required", "applicableFrom": "M1", "rationale": null }, "capabilityRef": "non-enumerating-resolution", - "requiredMilestones": ["M1", "M5"], + "requiredMilestones": [ + "M1", + "M5" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-NON-ENUMERATION-009"], - "postgres": ["PG-NON-ENUMERATION-009", "BLOB-001"], - "runtimeOrDelivery": ["AUTH-008", "RUN-001", "ENUM-001", "ENUM-002"] + "property": [ + "PROP-NON-ENUMERATION-009" + ], + "postgres": [ + "PG-NON-ENUMERATION-009", + "BLOB-001" + ], + "runtimeOrDelivery": [ + "AUTH-008", + "RUN-001", + "ENUM-001", + "ENUM-002" + ] }, "authorityRefs": [ "docs/security/context-engine-threat-model.md#6-threat-register", @@ -528,22 +941,45 @@ "id": "CITATION-AUTH-010", "title": "Citation opens reauthorize and are not bearer capabilities", "purpose": "Keep CitationOpenRef separate from one-shot ContinuationToken and require current opener, audience, source, and policy authorization on every open.", - "threatRefs": ["TM-06", "TM-14"], - "protectedAssets": ["A-01", "A-04", "A-05"], + "threatRefs": [ + "TM-06", + "TM-14" + ], + "protectedAssets": [ + "A-01", + "A-04", + "A-05" + ], "deterministicOracle": "Pass only when a wrong opener, revoked grant, tampered locator, or token-kind swap yields exactly 0 fields, 0 source bytes, and a generic unavailable response; fail if the reference itself restores authority.", - "hardOracleRefs": ["Unauthorized Evidence", "missing-context fallback"], + "hardOracleRefs": [ + "Unauthorized Evidence", + "missing-context fallback" + ], "applicability": { "mode": "required", "applicableFrom": "M2", "rationale": null }, "capabilityRef": "citation-open-reauthorization", - "requiredMilestones": ["M2", "M3"], + "requiredMilestones": [ + "M2", + "M3" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-CITATION-AUTH-010"], - "postgres": ["PG-CITATION-AUTH-010", "BLOB-002"], - "runtimeOrDelivery": ["CITE-001", "CITE-002", "CITE-003", "CITE-004"] + "property": [ + "PROP-CITATION-AUTH-010" + ], + "postgres": [ + "PG-CITATION-AUTH-010", + "BLOB-002" + ], + "runtimeOrDelivery": [ + "CITE-001", + "CITE-002", + "CITE-003", + "CITE-004" + ] }, "authorityRefs": [ "docs/design/2026-07-18-context-engine-implementation-design.md#53-tokens-and-locators", @@ -555,22 +991,50 @@ "id": "EGRESS-011", "title": "Delivery egress is package-, audience-, and grant-bound", "purpose": "Ensure model and sender payloads derive only from one current audience-bound ContextPackage and a matching EgressGrant, with send-time audience revalidation.", - "threatRefs": ["TM-10", "TM-11", "TM-12", "TM-13"], - "protectedAssets": ["A-02", "A-04", "A-05"], + "threatRefs": [ + "TM-10", + "TM-11", + "TM-12", + "TM-13" + ], + "protectedAssets": [ + "A-02", + "A-04", + "A-05" + ], "deterministicOracle": "Pass only when every sensitivity, purpose, provider, region, audience, digest, or snapshot mismatch produces exactly 0 model or sender payload bytes and 0 wrong-Organization effects; fail on any payload or effect without the exact current grant.", - "hardOracleRefs": ["Unauthorized Evidence", "wrong-Organization effect", "missing-context fallback"], + "hardOracleRefs": [ + "Unauthorized Evidence", + "wrong-Organization effect", + "missing-context fallback" + ], "applicability": { "mode": "required", "applicableFrom": "M2", "rationale": null }, "capabilityRef": "delivery-egress-grant", - "requiredMilestones": ["M2", "M5"], + "requiredMilestones": [ + "M2", + "M5" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-EGRESS-011"], - "postgres": ["PG-EGRESS-011"], - "runtimeOrDelivery": ["EGR-001", "EGR-003", "EGR-004", "EGR-005", "EGR-006", "RUN-014", "RUN-015"] + "property": [ + "PROP-EGRESS-011" + ], + "postgres": [ + "PG-EGRESS-011" + ], + "runtimeOrDelivery": [ + "EGR-001", + "EGR-003", + "EGR-004", + "EGR-005", + "EGR-006", + "RUN-014", + "RUN-015" + ] }, "authorityRefs": [ "docs/design/2026-07-18-context-engine-implementation-design.md#5-delivery-audience-egress-and-capability-taxonomy", @@ -582,22 +1046,46 @@ "id": "TRACE-REDACTION-012", "title": "Tenant-visible runs contain authorized lineage only", "purpose": "Keep denied details and secrets out of ContextRun, logs, metrics, debug output, evaluation, and Learning while retaining only restricted redacted DecisionAudit categories and digests.", - "threatRefs": ["TM-15"], - "protectedAssets": ["A-01", "A-06", "A-07"], + "threatRefs": [ + "TM-15" + ], + "protectedAssets": [ + "A-01", + "A-06", + "A-07" + ], "deterministicOracle": "Pass only when tenant-visible and Learning-safe records contain exactly 0 raw denied bodies, denied names, secret values, or denied counts, and restricted audit contains only approved opaque references, digests, and categories; fail on any forbidden match.", - "hardOracleRefs": ["Unauthorized Evidence"], + "hardOracleRefs": [ + "Unauthorized Evidence" + ], "applicability": { "mode": "required", "applicableFrom": "M0", "rationale": null }, "capabilityRef": "authorized-only-observability", - "requiredMilestones": ["M0", "M1"], + "requiredMilestones": [ + "M0", + "M1" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-TRACE-REDACTION-012", "PROP-FIELD-PROJECTION-048"], - "postgres": ["PG-TRACE-REDACTION-012", "OBS-004", "OBS-005", "PG-FIELD-PROJECTION-048"], - "runtimeOrDelivery": ["OBS-001", "OBS-002", "OBS-003", "HTTP-ACCEPT-002-048"] + "property": [ + "PROP-TRACE-REDACTION-012", + "PROP-FIELD-PROJECTION-048" + ], + "postgres": [ + "PG-TRACE-REDACTION-012", + "OBS-004", + "OBS-005", + "PG-FIELD-PROJECTION-048" + ], + "runtimeOrDelivery": [ + "OBS-001", + "OBS-002", + "OBS-003", + "HTTP-ACCEPT-002-048" + ] }, "authorityRefs": [ "docs/security/context-engine-threat-model.md#6-threat-register", @@ -613,22 +1101,48 @@ "id": "ACTION-SEPARATION-014", "title": "Context authority never grants external-effect authority", "purpose": "Require ActionPlane prepare then perform with a distinct Organization-, audience-, effect-, destination-, payload-, epoch-, and idempotency-bound one-shot ActionTicket for every effect.", - "threatRefs": ["TM-13"], - "protectedAssets": ["A-04", "A-05", "A-08"], + "threatRefs": [ + "TM-13" + ], + "protectedAssets": [ + "A-04", + "A-05", + "A-08" + ], "deterministicOracle": "Pass only when bypassed prepare, wrong capability class, cross-effect reuse, binding mutation, and replay each add exactly 0 effects and wrong-Organization effect is exactly 0; fail if ContextAccessTicket or any mismatched ActionTicket causes a new effect.", - "hardOracleRefs": ["Unauthorized Evidence", "wrong-Organization effect", "missing-context fallback"], + "hardOracleRefs": [ + "Unauthorized Evidence", + "wrong-Organization effect", + "missing-context fallback" + ], "applicability": { "mode": "required", "applicableFrom": "M2", "rationale": null }, "capabilityRef": "action-plane-one-shot-ticket", - "requiredMilestones": ["M2"], + "requiredMilestones": [ + "M2" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-ACTION-SEPARATION-014"], - "postgres": ["PG-ACTION-SEPARATION-014"], - "runtimeOrDelivery": ["ACTION-001", "ACTION-002", "ACTION-003", "ACTION-004", "ACTION-005", "ACTION-006", "ACTION-007", "ACTION-008", "ACTION-009"] + "property": [ + "PROP-ACTION-SEPARATION-014" + ], + "postgres": [ + "PG-ACTION-SEPARATION-014" + ], + "runtimeOrDelivery": [ + "ACTION-001", + "ACTION-002", + "ACTION-003", + "ACTION-004", + "ACTION-005", + "ACTION-006", + "ACTION-007", + "ACTION-008", + "ACTION-009" + ] }, "authorityRefs": [ "docs/design/2026-07-18-context-engine-implementation-design.md#25-actionplane", @@ -642,22 +1156,43 @@ "id": "CROSS-ORG-LEARN-015", "title": "V1 Learning contains no raw cross-Organization artifacts", "purpose": "Prevent feedback, evaluation, exports, and global artifacts from turning authorized tenant content or denied traces into a cross-tenant channel.", - "threatRefs": ["TM-15", "TM-16"], - "protectedAssets": ["A-01", "A-03", "A-07"], + "threatRefs": [ + "TM-15", + "TM-16" + ], + "protectedAssets": [ + "A-01", + "A-03", + "A-07" + ], "deterministicOracle": "Pass only when cross-Organization feedback references are rejected, global artifacts contain exactly 0 raw tenant references, and no artifact is produced without the declared opt-in and aggregation gate; fail on any raw cross-Organization lineage.", - "hardOracleRefs": ["Unauthorized Evidence", "wrong-Organization effect"], + "hardOracleRefs": [ + "Unauthorized Evidence", + "wrong-Organization effect" + ], "applicability": { "mode": "required", "applicableFrom": "M0", "rationale": null }, "capabilityRef": "organization-scoped-learning", - "requiredMilestones": ["M0", "M3"], + "requiredMilestones": [ + "M0", + "M3" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-CROSS-ORG-LEARN-015"], - "postgres": ["PG-CROSS-ORG-LEARN-015", "LEARN-001"], - "runtimeOrDelivery": ["LEARN-002", "LEARN-003"] + "property": [ + "PROP-CROSS-ORG-LEARN-015" + ], + "postgres": [ + "PG-CROSS-ORG-LEARN-015", + "LEARN-001" + ], + "runtimeOrDelivery": [ + "LEARN-002", + "LEARN-003" + ] }, "authorityRefs": [ "docs/agents/prd-contextengine-implementation.md#out-of-scope", @@ -669,22 +1204,44 @@ "id": "RELEASE-OWNER-019", "title": "ContextLearning promotion is the only release activation authority", "purpose": "Prevent Control, migration, bootstrap, Curation, Runtime, or evaluator paths from directly changing the active ReleaseManifest, including initial activation and rollback.", - "threatRefs": ["TM-16"], - "protectedAssets": ["A-03", "A-07", "A-08"], + "threatRefs": [ + "TM-16" + ], + "protectedAssets": [ + "A-03", + "A-07", + "A-08" + ], "deterministicOracle": "Pass only when every direct active-pointer attempt outside release-operator-authorized ContextLearning.promote changes exactly 0 pointers and 0 publication state, while initial and rollback selections require the same audited promote path; fail on any second publication authority.", - "hardOracleRefs": ["Unauthorized Evidence", "wrong-Organization effect"], + "hardOracleRefs": [ + "Unauthorized Evidence", + "wrong-Organization effect" + ], "applicability": { "mode": "required", "applicableFrom": "M0", "rationale": null }, "capabilityRef": "governed-release-promotion", - "requiredMilestones": ["M0", "M3"], + "requiredMilestones": [ + "M0", + "M3" + ], "evidenceStatus": "accepted", "expectedEvidence": { - "property": ["PROP-RELEASE-OWNER-019"], - "postgres": ["PG-RELEASE-OWNER-019", "LEARN-006", "LEARN-007"], - "runtimeOrDelivery": ["LEARN-004", "LEARN-008", "LEARN-009"] + "property": [ + "PROP-RELEASE-OWNER-019" + ], + "postgres": [ + "PG-RELEASE-OWNER-019", + "LEARN-006", + "LEARN-007" + ], + "runtimeOrDelivery": [ + "LEARN-004", + "LEARN-008", + "LEARN-009" + ] }, "authorityRefs": [ "docs/design/2026-07-18-context-engine-implementation-design.md#63-release-ownership", @@ -711,8 +1268,16 @@ ], "trustedIdentity": { "invocations": [ - {"organizationRef": "org-a", "principalRef": "member-a", "purpose": "context.answer"}, - {"organizationRef": "org-b", "principalRef": "member-b", "purpose": "context.answer"} + { + "organizationRef": "org-a", + "principalRef": "member-a", + "purpose": "context.answer" + }, + { + "organizationRef": "org-b", + "principalRef": "member-b", + "purpose": "context.answer" + } ], "source": "authenticated ingress; callers do not author these values" } @@ -720,8 +1285,14 @@ "adversarialMutation": { "kind": "cross_organization_resource_probe", "attempts": [ - {"invocation": "member-a", "target": "shared-name/b-secret"}, - {"invocation": "member-b", "target": "shared-name/a-secret"} + { + "invocation": "member-a", + "target": "shared-name/b-secret" + }, + { + "invocation": "member-b", + "target": "shared-name/a-secret" + } ] }, "operation": { @@ -736,28 +1307,106 @@ "body": { "kind": "resolved", "package": { - "organizationRef": "orgpkg_0000000000000000000000000000000a", "purpose": "context.answer", "ttlSeconds": 30, "asOf": "2026-07-21T09:30:00Z", "expiresAt": "2026-07-21T09:30:30Z", "decisionRef": "dec_0000000000000000000000000000000a", - "packageDigest": "60891a2328498f53607c4bb67e0e17804c1e91debdbfb2489f67f681573ffcc7", - "blocks": [{"blockId": "block_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "text": "A-safe", "evidenceRefs": ["ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]}], - "evidence": [{"evidenceRef": "ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "sourceRef": "source-synthetic-a", "resourceRef": "resource-authorized-a", "revisionRef": "revision-authorized-a", "fragmentRef": "fragment-authorized-a", "projectedFields": ["body"], "runRef": "run-authorized-a", "purpose": "context.answer", "authorizationAsOf": "2026-07-21T09:30:00Z", "decisionRef": "dec_0000000000000000000000000000000a", "policySnapshotRef": "policy-snapshot-a", "policyEpoch": 1, "sourceDecisionRef": "source-decision-a"}], + "blocks": [ + { + "blockId": "block_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "text": "A-safe", + "evidenceRefs": [ + "ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + ] + } + ], + "evidence": [ + { + "evidenceRef": "ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "sourceRef": "source-synthetic-a", + "resourceRef": "resource-authorized-a", + "revisionRef": "revision-authorized-a", + "fragmentRef": "fragment-authorized-a", + "projectedFields": [ + "body" + ], + "runRef": "run-authorized-a", + "purpose": "context.answer", + "authorizationAsOf": "2026-07-21T09:30:00Z", + "decisionRef": "dec_0000000000000000000000000000000a", + "policySnapshotRef": "policy-snapshot-a", + "policyEpoch": 1, + "sourceAclEvidence": { + "kind": "mirrored", + "projectionRef": "source-decision-a", + "aclAsOf": "2026-07-21T09:30:00Z", + "freshnessProfileRef": "file-source-access-current-transaction-v1" + }, + "citationOpenRef": null + } + ], "gaps": [], - "budgetUsage": {"tokens": 6, "providerCalls": 0, "costMicrounits": 0, "elapsedMs": 0}, - "coverage": {"status": "sufficient"} + "budgetUsage": { + "tokens": 6, + "providerCalls": 0, + "costMicrounits": 0, + "elapsedMs": 0 + }, + "coverage": { + "status": "sufficient" + }, + "packageId": "pkg_0000000000000000000000000000000a", + "audienceDigest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "policyEpoch": 1, + "policySnapshotRef": "policy-snapshot-a", + "runRef": "run-authorized-a", + "releaseManifestRef": "manifest-m0-empty-v0", + "retentionPolicyRef": "package-digest-only-retention-v1", + "tokenizerRef": "utf8-byte-budget-v1", + "packageSchemaRef": "context-package-openapi-v0", + "continuation": null, + "packageDigest": "9dbfcc7aa6c6a05acd5d61122fc2b8d6a4741794ac2eff59a1bbbaae2e1c616f" } }, "sameOutcomeSemanticsForBothAttempts": true }, - "packageOrError": {"kind": "ContextPackage", "packageCount": 2, "coverageStatus": "sufficient", "blocksPerPackage": 1, "evidencePerPackage": 1, "unauthorizedFieldCount": 0, "unauthorizedEvidenceRefCount": 0, "crossOrganizationResourceDetailCount": 0}, - "evidence": {"unauthorizedEvidenceCount": 0, "unauthorizedContentBytes": 0, "missingContextFallbackCount": 0, "outboundBytes": 6}, - "businessEffects": {"wrongOrganizationEffectCount": 0, "mutationEffectCount": 0, "totalEffectsAfterScenario": 0}, - "io": {"providerCalls": 0, "indexCalls": 0, "modelCalls": 0, "actionCalls": 0} + "packageOrError": { + "kind": "ContextPackage", + "packageCount": 2, + "coverageStatus": "sufficient", + "blocksPerPackage": 1, + "evidencePerPackage": 1, + "unauthorizedFieldCount": 0, + "unauthorizedEvidenceRefCount": 0, + "crossOrganizationResourceDetailCount": 0 + }, + "evidence": { + "unauthorizedEvidenceCount": 0, + "unauthorizedContentBytes": 0, + "missingContextFallbackCount": 0, + "outboundBytes": 6 + }, + "businessEffects": { + "wrongOrganizationEffectCount": 0, + "mutationEffectCount": 0, + "totalEffectsAfterScenario": 0 + }, + "io": { + "providerCalls": 0, + "indexCalls": 0, + "modelCalls": 0, + "actionCalls": 0 + } }, - "invariantRefs": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "SCOPE-INTERSECTION-004", "INDEX-NOT-AUTHORITY-005", "NON-ENUMERATION-009"], + "invariantRefs": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "SCOPE-INTERSECTION-004", + "INDEX-NOT-AUTHORITY-005", + "NON-ENUMERATION-009" + ], "authorityRefs": [ "docs/agents/prd-contextengine-implementation.md#user-stories", "docs/security/Test-Architecture-与可验证性设计.md#13-v1-acceptance-scenarios", @@ -789,22 +1438,56 @@ "adversarialMutation": { "kind": "broader_membership_candidate_reuse", "candidateWasDiscoveredFor": "member-full", - "candidateFields": ["status", "private_note"], + "candidateFields": [ + "status", + "private_note" + ], "currentInvocation": "member-limited" }, "operation": { "interface": "ContextRuntime.resolve", "request": "Acquire ticket-1", - "expectedAuthorizedProjection": ["status"] + "expectedAuthorizedProjection": [ + "status" + ] }, "expected": { - "externalResponse": {"status": 200, "authorizedPayloadUtf8": "status=open", "authorizedPayloadBytes": 11, "privateFieldPresent": false}, - "packageOrError": {"kind": "ContextPackage", "evidenceFields": ["status"], "deniedFieldCountExposed": false}, - "evidence": {"unauthorizedEvidenceCount": 0, "unauthorizedContentBytes": 0, "missingContextFallbackCount": 0, "outboundBytes": 11}, - "businessEffects": {"wrongOrganizationEffectCount": 0, "mutationEffectCount": 0, "totalEffectsAfterScenario": 0}, - "io": {"providerCalls": 1, "indexCalls": 1, "modelCalls": 0, "actionCalls": 0} + "externalResponse": { + "status": 200, + "authorizedPayloadUtf8": "status=open", + "authorizedPayloadBytes": 11, + "privateFieldPresent": false + }, + "packageOrError": { + "kind": "ContextPackage", + "evidenceFields": [ + "status" + ], + "deniedFieldCountExposed": false + }, + "evidence": { + "unauthorizedEvidenceCount": 0, + "unauthorizedContentBytes": 0, + "missingContextFallbackCount": 0, + "outboundBytes": 11 + }, + "businessEffects": { + "wrongOrganizationEffectCount": 0, + "mutationEffectCount": 0, + "totalEffectsAfterScenario": 0 + }, + "io": { + "providerCalls": 1, + "indexCalls": 1, + "modelCalls": 0, + "actionCalls": 0 + } }, - "invariantRefs": ["SCOPE-INTERSECTION-004", "INDEX-NOT-AUTHORITY-005", "TRACE-REDACTION-012"], + "invariantRefs": [ + "SCOPE-INTERSECTION-004", + "INDEX-NOT-AUTHORITY-005", + "TRACE-REDACTION-012" + ], "authorityRefs": [ "docs/security/安全负向测试清单.md#9-minimal-release-matrix", "docs/security/安全负向测试清单.md#2-identitytenant-与-delegation", @@ -838,22 +1521,125 @@ }, "adversarialMutation": { "kind": "agent_scope_expansion", - "requestedAgentSources": ["public-1", "private-1"], - "signedAgentCeiling": ["public-1"] + "requestedAgentSources": [ + "public-1", + "private-1" + ], + "signedAgentCeiling": [ + "public-1" + ] }, "operation": { "interface": "ContextRuntime.resolve", "request": "Acquire both identifiers", - "expectedEffectiveScope": ["public-1"] + "expectedEffectiveScope": [ + "public-1" + ] }, "expected": { - "externalResponse": {"status": 200, "body": {"kind": "resolved", "package": {"organizationRef": "orgpkg_0000000000000000000000000000000a", "purpose": "context.answer", "ttlSeconds": 30, "asOf": "2026-07-21T09:30:00Z", "expiresAt": "2026-07-21T09:30:30Z", "decisionRef": "dec_0000000000000000000000000000000a", "packageDigest": "60891a2328498f53607c4bb67e0e17804c1e91debdbfb2489f67f681573ffcc7", "blocks": [{"blockId": "block_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "text": "A-safe", "evidenceRefs": ["ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]}], "evidence": [{"evidenceRef": "ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "sourceRef": "source-synthetic-a", "resourceRef": "resource-authorized-a", "revisionRef": "revision-authorized-a", "fragmentRef": "fragment-authorized-a", "projectedFields": ["body"], "runRef": "run-authorized-a", "purpose": "context.answer", "authorizationAsOf": "2026-07-21T09:30:00Z", "decisionRef": "dec_0000000000000000000000000000000a", "policySnapshotRef": "policy-snapshot-a", "policyEpoch": 1, "sourceDecisionRef": "source-decision-a"}], "gaps": [], "budgetUsage": {"tokens": 6, "providerCalls": 0, "costMicrounits": 0, "elapsedMs": 0}, "coverage": {"status": "sufficient"}}}, "authorizedPayloadUtf8": "A-safe", "authorizedPayloadBytes": 6, "privateResourcePresent": false}, - "packageOrError": {"kind": "ContextPackage", "evidenceResourceRefs": ["resource-authorized-a"], "blocksPerPackage": 1, "evidencePerPackage": 1, "unauthorizedFieldCount": 0, "unauthorizedEvidenceRefCount": 0}, - "evidence": {"unauthorizedEvidenceCount": 0, "unauthorizedContentBytes": 0, "missingContextFallbackCount": 0, "outboundBytes": 6}, - "businessEffects": {"wrongOrganizationEffectCount": 0, "mutationEffectCount": 0, "totalEffectsAfterScenario": 0}, - "io": {"providerCalls": 0, "indexCalls": 1, "modelCalls": 0, "actionCalls": 0} + "externalResponse": { + "status": 200, + "body": { + "kind": "resolved", + "package": { + "purpose": "context.answer", + "ttlSeconds": 30, + "asOf": "2026-07-21T09:30:00Z", + "expiresAt": "2026-07-21T09:30:30Z", + "decisionRef": "dec_0000000000000000000000000000000a", + "blocks": [ + { + "blockId": "block_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "text": "A-safe", + "evidenceRefs": [ + "ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + ] + } + ], + "evidence": [ + { + "evidenceRef": "ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "sourceRef": "source-synthetic-a", + "resourceRef": "resource-authorized-a", + "revisionRef": "revision-authorized-a", + "fragmentRef": "fragment-authorized-a", + "projectedFields": [ + "body" + ], + "runRef": "run-authorized-a", + "purpose": "context.answer", + "authorizationAsOf": "2026-07-21T09:30:00Z", + "decisionRef": "dec_0000000000000000000000000000000a", + "policySnapshotRef": "policy-snapshot-a", + "policyEpoch": 1, + "sourceAclEvidence": { + "kind": "mirrored", + "projectionRef": "source-decision-a", + "aclAsOf": "2026-07-21T09:30:00Z", + "freshnessProfileRef": "file-source-access-current-transaction-v1" + }, + "citationOpenRef": null + } + ], + "gaps": [], + "budgetUsage": { + "tokens": 6, + "providerCalls": 0, + "costMicrounits": 0, + "elapsedMs": 0 + }, + "coverage": { + "status": "sufficient" + }, + "packageId": "pkg_0000000000000000000000000000000a", + "audienceDigest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "policyEpoch": 1, + "policySnapshotRef": "policy-snapshot-a", + "runRef": "run-authorized-a", + "releaseManifestRef": "manifest-m0-empty-v0", + "retentionPolicyRef": "package-digest-only-retention-v1", + "tokenizerRef": "utf8-byte-budget-v1", + "packageSchemaRef": "context-package-openapi-v0", + "continuation": null, + "packageDigest": "9dbfcc7aa6c6a05acd5d61122fc2b8d6a4741794ac2eff59a1bbbaae2e1c616f" + } + }, + "authorizedPayloadUtf8": "A-safe", + "authorizedPayloadBytes": 6, + "privateResourcePresent": false + }, + "packageOrError": { + "kind": "ContextPackage", + "evidenceResourceRefs": [ + "resource-authorized-a" + ], + "blocksPerPackage": 1, + "evidencePerPackage": 1, + "unauthorizedFieldCount": 0, + "unauthorizedEvidenceRefCount": 0 + }, + "evidence": { + "unauthorizedEvidenceCount": 0, + "unauthorizedContentBytes": 0, + "missingContextFallbackCount": 0, + "outboundBytes": 6 + }, + "businessEffects": { + "wrongOrganizationEffectCount": 0, + "mutationEffectCount": 0, + "totalEffectsAfterScenario": 0 + }, + "io": { + "providerCalls": 0, + "indexCalls": 1, + "modelCalls": 0, + "actionCalls": 0 + } }, - "invariantRefs": ["SCOPE-INTERSECTION-004", "INDEX-NOT-AUTHORITY-005"], + "invariantRefs": [ + "SCOPE-INTERSECTION-004", + "INDEX-NOT-AUTHORITY-005" + ], "authorityRefs": [ "docs/agents/prd-contextengine-implementation.md#solution", "docs/security/Test-Architecture-与可验证性设计.md#5-property-based-authorization-tests", @@ -884,8 +1670,15 @@ }, "adversarialMutation": { "kind": "prompt_controlled_filter_expansion", - "requestNarrowing": {"sourceRefs": ["source-1"]}, - "promptInjectedSourceRefs": ["source-1", "source-2"] + "requestNarrowing": { + "sourceRefs": [ + "source-1" + ] + }, + "promptInjectedSourceRefs": [ + "source-1", + "source-2" + ] }, "operation": { "interface": "ContextRuntime.resolve", @@ -893,13 +1686,111 @@ "comparison": "Result set must be a subset of the same invocation without RequestNarrowing." }, "expected": { - "externalResponse": {"status": 200, "body": {"kind": "resolved", "package": {"organizationRef": "orgpkg_0000000000000000000000000000000a", "purpose": "context.answer", "ttlSeconds": 30, "asOf": "2026-07-21T09:30:00Z", "expiresAt": "2026-07-21T09:30:30Z", "decisionRef": "dec_0000000000000000000000000000000a", "packageDigest": "60891a2328498f53607c4bb67e0e17804c1e91debdbfb2489f67f681573ffcc7", "blocks": [{"blockId": "block_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "text": "A-safe", "evidenceRefs": ["ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]}], "evidence": [{"evidenceRef": "ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "sourceRef": "source-synthetic-a", "resourceRef": "resource-authorized-a", "revisionRef": "revision-authorized-a", "fragmentRef": "fragment-authorized-a", "projectedFields": ["body"], "runRef": "run-authorized-a", "purpose": "context.answer", "authorizationAsOf": "2026-07-21T09:30:00Z", "decisionRef": "dec_0000000000000000000000000000000a", "policySnapshotRef": "policy-snapshot-a", "policyEpoch": 1, "sourceDecisionRef": "source-decision-a"}], "gaps": [], "budgetUsage": {"tokens": 6, "providerCalls": 0, "costMicrounits": 0, "elapsedMs": 0}, "coverage": {"status": "sufficient"}}}, "authorizedPayloadUtf8": "A-safe", "authorizedPayloadBytes": 6, "source2Present": false}, - "packageOrError": {"kind": "ContextPackage", "sourceRefs": ["source-synthetic-a"], "expandedSourceCallCount": 0, "blocksPerPackage": 1, "evidencePerPackage": 1, "unauthorizedFieldCount": 0, "unauthorizedEvidenceRefCount": 0}, - "evidence": {"unauthorizedEvidenceCount": 0, "unauthorizedContentBytes": 0, "missingContextFallbackCount": 0, "outboundBytes": 6}, - "businessEffects": {"wrongOrganizationEffectCount": 0, "mutationEffectCount": 0, "totalEffectsAfterScenario": 0}, - "io": {"providerCalls": 0, "indexCalls": 1, "modelCalls": 0, "actionCalls": 0} + "externalResponse": { + "status": 200, + "body": { + "kind": "resolved", + "package": { + "purpose": "context.answer", + "ttlSeconds": 30, + "asOf": "2026-07-21T09:30:00Z", + "expiresAt": "2026-07-21T09:30:30Z", + "decisionRef": "dec_0000000000000000000000000000000a", + "blocks": [ + { + "blockId": "block_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "text": "A-safe", + "evidenceRefs": [ + "ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + ] + } + ], + "evidence": [ + { + "evidenceRef": "ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "sourceRef": "source-synthetic-a", + "resourceRef": "resource-authorized-a", + "revisionRef": "revision-authorized-a", + "fragmentRef": "fragment-authorized-a", + "projectedFields": [ + "body" + ], + "runRef": "run-authorized-a", + "purpose": "context.answer", + "authorizationAsOf": "2026-07-21T09:30:00Z", + "decisionRef": "dec_0000000000000000000000000000000a", + "policySnapshotRef": "policy-snapshot-a", + "policyEpoch": 1, + "sourceAclEvidence": { + "kind": "mirrored", + "projectionRef": "source-decision-a", + "aclAsOf": "2026-07-21T09:30:00Z", + "freshnessProfileRef": "file-source-access-current-transaction-v1" + }, + "citationOpenRef": null + } + ], + "gaps": [], + "budgetUsage": { + "tokens": 6, + "providerCalls": 0, + "costMicrounits": 0, + "elapsedMs": 0 + }, + "coverage": { + "status": "sufficient" + }, + "packageId": "pkg_0000000000000000000000000000000a", + "audienceDigest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "policyEpoch": 1, + "policySnapshotRef": "policy-snapshot-a", + "runRef": "run-authorized-a", + "releaseManifestRef": "manifest-m0-empty-v0", + "retentionPolicyRef": "package-digest-only-retention-v1", + "tokenizerRef": "utf8-byte-budget-v1", + "packageSchemaRef": "context-package-openapi-v0", + "continuation": null, + "packageDigest": "9dbfcc7aa6c6a05acd5d61122fc2b8d6a4741794ac2eff59a1bbbaae2e1c616f" + } + }, + "authorizedPayloadUtf8": "A-safe", + "authorizedPayloadBytes": 6, + "source2Present": false + }, + "packageOrError": { + "kind": "ContextPackage", + "sourceRefs": [ + "source-synthetic-a" + ], + "expandedSourceCallCount": 0, + "blocksPerPackage": 1, + "evidencePerPackage": 1, + "unauthorizedFieldCount": 0, + "unauthorizedEvidenceRefCount": 0 + }, + "evidence": { + "unauthorizedEvidenceCount": 0, + "unauthorizedContentBytes": 0, + "missingContextFallbackCount": 0, + "outboundBytes": 6 + }, + "businessEffects": { + "wrongOrganizationEffectCount": 0, + "mutationEffectCount": 0, + "totalEffectsAfterScenario": 0 + }, + "io": { + "providerCalls": 0, + "indexCalls": 1, + "modelCalls": 0, + "actionCalls": 0 + } }, - "invariantRefs": ["SCOPE-INTERSECTION-004", "INDEX-NOT-AUTHORITY-005", "TRANSPORT-UNTRUSTED-008"], + "invariantRefs": [ + "SCOPE-INTERSECTION-004", + "INDEX-NOT-AUTHORITY-005", + "TRANSPORT-UNTRUSTED-008" + ], "authorityRefs": [ "docs/agents/prd-contextengine-implementation.md#implementation-decisions", "docs/security/安全负向测试清单.md#2-identitytenant-与-delegation", @@ -940,13 +1831,41 @@ "timing": "first controlled operation after observed revocation" }, "expected": { - "externalResponse": {"status": 200, "body": {"kind": "request_not_available", "retryable": false}}, - "packageOrError": {"kind": "request_not_available", "stalePackageReturned": false, "revokedResourceDetailCount": 0}, - "evidence": {"unauthorizedEvidenceCount": 0, "unauthorizedContentBytes": 0, "missingContextFallbackCount": 0, "outboundBytes": 0}, - "businessEffects": {"wrongOrganizationEffectCount": 0, "mutationEffectCount": 0, "totalEffectsAfterScenario": 0}, - "io": {"providerCalls": 0, "indexCalls": 0, "modelCalls": 0, "actionCalls": 0} + "externalResponse": { + "status": 200, + "body": { + "kind": "request_not_available", + "retryable": false + } + }, + "packageOrError": { + "kind": "request_not_available", + "stalePackageReturned": false, + "revokedResourceDetailCount": 0 + }, + "evidence": { + "unauthorizedEvidenceCount": 0, + "unauthorizedContentBytes": 0, + "missingContextFallbackCount": 0, + "outboundBytes": 0 + }, + "businessEffects": { + "wrongOrganizationEffectCount": 0, + "mutationEffectCount": 0, + "totalEffectsAfterScenario": 0 + }, + "io": { + "providerCalls": 0, + "indexCalls": 0, + "modelCalls": 0, + "actionCalls": 0 + } }, - "invariantRefs": ["REVOCATION-006", "CITATION-AUTH-010", "TRACE-REDACTION-012"], + "invariantRefs": [ + "REVOCATION-006", + "CITATION-AUTH-010", + "TRACE-REDACTION-012" + ], "authorityRefs": [ "docs/agents/prd-contextengine-implementation.md#implementation-decisions", "docs/security/Test-Architecture-与可验证性设计.md#9-runtime-behavior-tests", @@ -977,23 +1896,163 @@ }, "adversarialMutation": { "kind": "cross_organization_candidate_injection", - "orderedCandidateRefs": ["candidate-hostile-b", "candidate-denied-a", "candidate-authorized-a"], - "candidateRankOrders": [["candidate-authorized-a", "candidate-denied-a", "candidate-hostile-b"], ["candidate-authorized-a", "candidate-hostile-b", "candidate-denied-a"], ["candidate-denied-a", "candidate-authorized-a", "candidate-hostile-b"], ["candidate-denied-a", "candidate-hostile-b", "candidate-authorized-a"], ["candidate-hostile-b", "candidate-authorized-a", "candidate-denied-a"], ["candidate-hostile-b", "candidate-denied-a", "candidate-authorized-a"]], + "orderedCandidateRefs": [ + "candidate-hostile-b", + "candidate-denied-a", + "candidate-authorized-a" + ], + "candidateRankOrders": [ + [ + "candidate-authorized-a", + "candidate-denied-a", + "candidate-hostile-b" + ], + [ + "candidate-authorized-a", + "candidate-hostile-b", + "candidate-denied-a" + ], + [ + "candidate-denied-a", + "candidate-authorized-a", + "candidate-hostile-b" + ], + [ + "candidate-denied-a", + "candidate-hostile-b", + "candidate-authorized-a" + ], + [ + "candidate-hostile-b", + "candidate-authorized-a", + "candidate-denied-a" + ], + [ + "candidate-hostile-b", + "candidate-denied-a", + "candidate-authorized-a" + ] + ], "candidatePayloadFields": [] }, "operation": { "interface": "ContextRuntime.resolve", "request": "Acquire", - "requiredTypeFlow": ["CandidateRef", "AuthorizationKernel", "AuthorizedProjection"] + "requiredTypeFlow": [ + "CandidateRef", + "AuthorizationKernel", + "AuthorizedProjection" + ] }, "expected": { - "externalResponse": {"status": 200, "body": {"kind": "resolved", "package": {"organizationRef": "orgpkg_0000000000000000000000000000000a", "purpose": "context.answer", "ttlSeconds": 30, "asOf": "2026-07-21T09:30:00Z", "expiresAt": "2026-07-21T09:30:30Z", "decisionRef": "dec_0000000000000000000000000000000a", "packageDigest": "60891a2328498f53607c4bb67e0e17804c1e91debdbfb2489f67f681573ffcc7", "blocks": [{"blockId": "block_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "text": "A-safe", "evidenceRefs": ["ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]}], "evidence": [{"evidenceRef": "ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "sourceRef": "source-synthetic-a", "resourceRef": "resource-authorized-a", "revisionRef": "revision-authorized-a", "fragmentRef": "fragment-authorized-a", "projectedFields": ["body"], "runRef": "run-authorized-a", "purpose": "context.answer", "authorizationAsOf": "2026-07-21T09:30:00Z", "decisionRef": "dec_0000000000000000000000000000000a", "policySnapshotRef": "policy-snapshot-a", "policyEpoch": 1, "sourceDecisionRef": "source-decision-a"}], "gaps": [], "budgetUsage": {"tokens": 6, "providerCalls": 0, "costMicrounits": 0, "elapsedMs": 0}, "coverage": {"status": "sufficient"}}}, "authorizedPayloadUtf8": "A-safe", "authorizedPayloadBytes": 6, "orgBContentPresent": false}, - "packageOrError": {"kind": "ContextPackage", "evidenceRefs": ["ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"], "blocksPerPackage": 1, "evidencePerPackage": 1, "unauthorizedFieldCount": 0, "unauthorizedEvidenceRefCount": 0, "deniedCandidateCountExposed": false}, - "evidence": {"unauthorizedEvidenceCount": 0, "unauthorizedContentBytes": 0, "missingContextFallbackCount": 0, "outboundBytes": 6}, - "businessEffects": {"wrongOrganizationEffectCount": 0, "mutationEffectCount": 0, "totalEffectsAfterScenario": 0}, - "io": {"providerCalls": 0, "indexCalls": 1, "modelCalls": 0, "actionCalls": 0} + "externalResponse": { + "status": 200, + "body": { + "kind": "resolved", + "package": { + "purpose": "context.answer", + "ttlSeconds": 30, + "asOf": "2026-07-21T09:30:00Z", + "expiresAt": "2026-07-21T09:30:30Z", + "decisionRef": "dec_0000000000000000000000000000000a", + "blocks": [ + { + "blockId": "block_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "text": "A-safe", + "evidenceRefs": [ + "ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + ] + } + ], + "evidence": [ + { + "evidenceRef": "ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "sourceRef": "source-synthetic-a", + "resourceRef": "resource-authorized-a", + "revisionRef": "revision-authorized-a", + "fragmentRef": "fragment-authorized-a", + "projectedFields": [ + "body" + ], + "runRef": "run-authorized-a", + "purpose": "context.answer", + "authorizationAsOf": "2026-07-21T09:30:00Z", + "decisionRef": "dec_0000000000000000000000000000000a", + "policySnapshotRef": "policy-snapshot-a", + "policyEpoch": 1, + "sourceAclEvidence": { + "kind": "mirrored", + "projectionRef": "source-decision-a", + "aclAsOf": "2026-07-21T09:30:00Z", + "freshnessProfileRef": "file-source-access-current-transaction-v1" + }, + "citationOpenRef": null + } + ], + "gaps": [], + "budgetUsage": { + "tokens": 6, + "providerCalls": 0, + "costMicrounits": 0, + "elapsedMs": 0 + }, + "coverage": { + "status": "sufficient" + }, + "packageId": "pkg_0000000000000000000000000000000a", + "audienceDigest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "policyEpoch": 1, + "policySnapshotRef": "policy-snapshot-a", + "runRef": "run-authorized-a", + "releaseManifestRef": "manifest-m0-empty-v0", + "retentionPolicyRef": "package-digest-only-retention-v1", + "tokenizerRef": "utf8-byte-budget-v1", + "packageSchemaRef": "context-package-openapi-v0", + "continuation": null, + "packageDigest": "9dbfcc7aa6c6a05acd5d61122fc2b8d6a4741794ac2eff59a1bbbaae2e1c616f" + } + }, + "authorizedPayloadUtf8": "A-safe", + "authorizedPayloadBytes": 6, + "orgBContentPresent": false + }, + "packageOrError": { + "kind": "ContextPackage", + "evidenceRefs": [ + "ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + ], + "blocksPerPackage": 1, + "evidencePerPackage": 1, + "unauthorizedFieldCount": 0, + "unauthorizedEvidenceRefCount": 0, + "deniedCandidateCountExposed": false + }, + "evidence": { + "unauthorizedEvidenceCount": 0, + "unauthorizedContentBytes": 0, + "missingContextFallbackCount": 0, + "outboundBytes": 6 + }, + "businessEffects": { + "wrongOrganizationEffectCount": 0, + "mutationEffectCount": 0, + "totalEffectsAfterScenario": 0 + }, + "io": { + "providerCalls": 0, + "indexCalls": 1, + "modelCalls": 0, + "actionCalls": 0 + } }, - "invariantRefs": ["TENANT-OWNERSHIP-001", "TENANT-FK-002", "RLS-FAIL-CLOSED-003", "SCOPE-INTERSECTION-004", "INDEX-NOT-AUTHORITY-005", "TRACE-REDACTION-012"], + "invariantRefs": [ + "TENANT-OWNERSHIP-001", + "TENANT-FK-002", + "RLS-FAIL-CLOSED-003", + "SCOPE-INTERSECTION-004", + "INDEX-NOT-AUTHORITY-005", + "TRACE-REDACTION-012" + ], "authorityRefs": [ "docs/design/2026-07-18-context-engine-implementation-design.md#3-runtime-security-pipeline", "docs/security/安全负向测试清单.md#6-runtimeassemblycitation-与-egress", @@ -1027,17 +2086,59 @@ "organizationRef": "org-b", "principalRef": "member-b", "purpose": "admin.export", - "audience": ["member-b"], + "audience": [ + "member-b" + ], "acl": "allow-all", "rawSql": "select *", "bypassAuthorization": true }, "parameterizedCases": [ - {"id": "BODY-INJECTION", "mutation": "Inject Organization, Principal, purpose, audience, ACL, raw SQL, and bypass fields into the closed request body.", "expectedStatus": 422, "expectedOutcome": "invalid_request", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "DELIV-001", "mutation": "Forge or tamper with the opaque DeliveryEvidenceRef.", "expectedStatus": 200, "expectedOutcome": "request_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "DELIV-002", "mutation": "Replay the valid reference under resolve request req-b.", "expectedStatus": 200, "expectedOutcome": "request_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "DELIV-003", "mutation": "Redeem from bot-service-b or destination conversation-b.", "expectedStatus": 200, "expectedOutcome": "request_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "DELIV-004", "mutation": "Redeem after expiry or reuse the already redeemed reference outside the identical authenticated retry.", "expectedStatus": 200, "expectedOutcome": "request_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0} + { + "id": "BODY-INJECTION", + "mutation": "Inject Organization, Principal, purpose, audience, ACL, raw SQL, and bypass fields into the closed request body.", + "expectedStatus": 422, + "expectedOutcome": "invalid_request", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "DELIV-001", + "mutation": "Forge or tamper with the opaque DeliveryEvidenceRef.", + "expectedStatus": 200, + "expectedOutcome": "request_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "DELIV-002", + "mutation": "Replay the valid reference under resolve request req-b.", + "expectedStatus": 200, + "expectedOutcome": "request_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "DELIV-003", + "mutation": "Redeem from bot-service-b or destination conversation-b.", + "expectedStatus": 200, + "expectedOutcome": "request_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "DELIV-004", + "mutation": "Redeem after expiry or reuse the already redeemed reference outside the identical authenticated retry.", + "expectedStatus": 200, + "expectedOutcome": "request_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + } ] }, "operation": { @@ -1046,13 +2147,39 @@ "phase": "closed-schema decoding or DeliveryEvidenceRef redemption before trusted context construction and all content work" }, "expected": { - "externalResponse": {"status": 422, "code": "invalid_request", "fieldNamesEchoed": false}, - "packageOrError": {"kind": "error", "contextPackageCreated": false, "trustedContextConstructedFromBody": false}, - "evidence": {"unauthorizedEvidenceCount": 0, "unauthorizedContentBytes": 0, "missingContextFallbackCount": 0, "outboundBytes": 0}, - "businessEffects": {"wrongOrganizationEffectCount": 0, "mutationEffectCount": 0, "totalEffectsAfterScenario": 0}, - "io": {"providerCalls": 0, "indexCalls": 0, "modelCalls": 0, "actionCalls": 0} + "externalResponse": { + "status": 422, + "code": "invalid_request", + "fieldNamesEchoed": false + }, + "packageOrError": { + "kind": "error", + "contextPackageCreated": false, + "trustedContextConstructedFromBody": false + }, + "evidence": { + "unauthorizedEvidenceCount": 0, + "unauthorizedContentBytes": 0, + "missingContextFallbackCount": 0, + "outboundBytes": 0 + }, + "businessEffects": { + "wrongOrganizationEffectCount": 0, + "mutationEffectCount": 0, + "totalEffectsAfterScenario": 0 + }, + "io": { + "providerCalls": 0, + "indexCalls": 0, + "modelCalls": 0, + "actionCalls": 0 + } }, - "invariantRefs": ["RLS-FAIL-CLOSED-003", "TRANSPORT-UNTRUSTED-008", "EGRESS-011"], + "invariantRefs": [ + "RLS-FAIL-CLOSED-003", + "TRANSPORT-UNTRUSTED-008", + "EGRESS-011" + ], "authorityRefs": [ "docs/agents/prd-contextengine-implementation.md#testing-decisions", "docs/security/Test-Architecture-与可验证性设计.md#74-transport-contract", @@ -1084,26 +2211,181 @@ "adversarialMutation": { "kind": "parameterized_worker_lease_binding_and_replay", "replayCount": 1, - "mutatedClaim": {"organizationRef": "org-b"}, + "mutatedClaim": { + "organizationRef": "org-b" + }, "retainedNonce": "n-1", "parameterizedCases": [ - {"id": "LEASE-ORGANIZATION", "claim": "organizationRef", "mutation": "org-b", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-JOB", "claim": "jobRef", "mutation": "job-b", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-OPERATION", "claim": "operation", "mutation": "publish", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-SOURCE", "claim": "sourceRef", "mutation": "source-b", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-RESOURCE", "claim": "resourceRef", "mutation": "resource-b", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-REVISION", "claim": "revisionRef", "mutation": "revision-b", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-SERVICE-ACTOR", "claim": "serviceActorRef", "mutation": "worker-b", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-WORKLOAD", "claim": "workload", "mutation": "workload-b", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-POLICY-EPOCH", "claim": "policyEpoch", "mutation": 3, "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-AUDIENCE", "claim": "audienceDigest", "mutation": "audience-b", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-IDEMPOTENCY", "claim": "idempotencyKey", "mutation": "idem-b", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-GENERATION", "claim": "generation", "mutation": 1, "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-ISSUED-AT", "claim": "issuedAt", "mutation": "outside-bound-window", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-EXPIRY", "claim": "expiresAt", "mutation": "expired", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-NONCE", "claim": "nonce", "mutation": "n-2", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-REPLAY", "claim": "redemption", "mutation": "reuse-consumed-lease", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0}, - {"id": "LEASE-USER-IMPERSONATION", "claim": "actorKind", "mutation": "UserActor", "expectedStatus": 404, "expectedOutcome": "work_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0} + { + "id": "LEASE-ORGANIZATION", + "claim": "organizationRef", + "mutation": "org-b", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-JOB", + "claim": "jobRef", + "mutation": "job-b", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-OPERATION", + "claim": "operation", + "mutation": "publish", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-SOURCE", + "claim": "sourceRef", + "mutation": "source-b", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-RESOURCE", + "claim": "resourceRef", + "mutation": "resource-b", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-REVISION", + "claim": "revisionRef", + "mutation": "revision-b", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-SERVICE-ACTOR", + "claim": "serviceActorRef", + "mutation": "worker-b", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-WORKLOAD", + "claim": "workload", + "mutation": "workload-b", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-POLICY-EPOCH", + "claim": "policyEpoch", + "mutation": 3, + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-AUDIENCE", + "claim": "audienceDigest", + "mutation": "audience-b", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-IDEMPOTENCY", + "claim": "idempotencyKey", + "mutation": "idem-b", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-GENERATION", + "claim": "generation", + "mutation": 1, + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-ISSUED-AT", + "claim": "issuedAt", + "mutation": "outside-bound-window", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-EXPIRY", + "claim": "expiresAt", + "mutation": "expired", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-NONCE", + "claim": "nonce", + "mutation": "n-2", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-REPLAY", + "claim": "redemption", + "mutation": "reuse-consumed-lease", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + }, + { + "id": "LEASE-USER-IMPERSONATION", + "claim": "actorKind", + "mutation": "UserActor", + "expectedStatus": 404, + "expectedOutcome": "work_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0 + } ] }, "operation": { @@ -1112,13 +2394,39 @@ "durableComparison": "Compare mutation ledger before and after the replay." }, "expected": { - "externalResponse": {"status": 404, "code": "work_not_available", "leaseClaimsEchoed": false}, - "packageOrError": {"kind": "worker_rejection", "reasonVisibleToWorker": "generic_unavailable", "newReceiptCreated": false}, - "evidence": {"unauthorizedEvidenceCount": 0, "unauthorizedContentBytes": 0, "missingContextFallbackCount": 0, "outboundBytes": 0}, - "businessEffects": {"wrongOrganizationEffectCount": 0, "mutationEffectCount": 0, "totalEffectsAfterScenario": 1}, - "io": {"providerCalls": 0, "indexCalls": 0, "modelCalls": 0, "actionCalls": 0} + "externalResponse": { + "status": 404, + "code": "work_not_available", + "leaseClaimsEchoed": false + }, + "packageOrError": { + "kind": "worker_rejection", + "reasonVisibleToWorker": "generic_unavailable", + "newReceiptCreated": false + }, + "evidence": { + "unauthorizedEvidenceCount": 0, + "unauthorizedContentBytes": 0, + "missingContextFallbackCount": 0, + "outboundBytes": 0 + }, + "businessEffects": { + "wrongOrganizationEffectCount": 0, + "mutationEffectCount": 0, + "totalEffectsAfterScenario": 1 + }, + "io": { + "providerCalls": 0, + "indexCalls": 0, + "modelCalls": 0, + "actionCalls": 0 + } }, - "invariantRefs": ["TENANT-OWNERSHIP-001", "WORKER-LEASE-007", "TRACE-REDACTION-012"], + "invariantRefs": [ + "TENANT-OWNERSHIP-001", + "WORKER-LEASE-007", + "TRACE-REDACTION-012" + ], "authorityRefs": [ "docs/agents/prd-contextengine-implementation.md#implementation-decisions", "docs/security/安全负向测试清单.md#4-workeroutbox-与-publication", @@ -1156,11 +2464,56 @@ "requestedFallback": "Weak", "missingCapability": "live-source-native-acl", "parameterizedCases": [ - {"id": "PROV-013", "mutation": "A declared Live or strong ACL check times out, returns 429, or fails with 5xx.", "expectedStatus": 200, "expectedOutcome": "request_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "Fail closed or return a typed unavailable gap with zero Evidence; never substitute Weak proof."}, - {"id": "PROV-014", "mutation": "Mirrored ACL exceeds its freshness SLA or omits aclAsOf or sourceVersion.", "expectedStatus": 200, "expectedOutcome": "request_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "Reject, resynchronize, or use an equally strong supported Live check; every allowed Mirrored Evidence exposes proofKind Mirrored, aclAsOf, sourceVersion, and its declared freshness bound."}, - {"id": "PROV-015", "mutation": "A coarse-membership source requests Weak proof without a complete active Weak SourcePolicy and sensitivity decision.", "expectedStatus": 200, "expectedOutcome": "request_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "Weak is allowed only when the source genuinely lacks finer ACL semantics and explicitly declares it; incomplete, stale, unknown-sensitivity, or sensitive cases deny, while an allowed Package exposes proofKind Weak and declared as-of/freshness."}, - {"id": "PROV-018", "mutation": "FileSourceAccess is missing, incomplete, unknown, cross-Organization, cross-Resource, or not the active manifest version.", "expectedStatus": 200, "expectedOutcome": "request_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "Deny generically with zero Evidence and no implicit owner/public fallback; an allowed File result uses the active versioned PostgreSQL grant and exposes complete Mirrored proof and freshness fields."}, - {"id": "PROV-019", "mutation": "Host operating-system owner, mode, or ACL is permissive while FileSourceAccess is absent or denied.", "expectedStatus": 200, "expectedOutcome": "request_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "Host metadata never changes engine authorization; only active versioned PostgreSQL FileSourceAccess may yield an allowed Mirrored proof."} + { + "id": "PROV-013", + "mutation": "A declared Live or strong ACL check times out, returns 429, or fails with 5xx.", + "expectedStatus": 200, + "expectedOutcome": "request_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "Fail closed or return a typed unavailable gap with zero Evidence; never substitute Weak proof." + }, + { + "id": "PROV-014", + "mutation": "Mirrored ACL exceeds its freshness SLA or omits aclAsOf or sourceVersion.", + "expectedStatus": 200, + "expectedOutcome": "request_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "Reject, resynchronize, or use an equally strong supported Live check; every allowed Mirrored Evidence exposes proofKind Mirrored, aclAsOf, sourceVersion, and its declared freshness bound." + }, + { + "id": "PROV-015", + "mutation": "A coarse-membership source requests Weak proof without a complete active Weak SourcePolicy and sensitivity decision.", + "expectedStatus": 200, + "expectedOutcome": "request_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "Weak is allowed only when the source genuinely lacks finer ACL semantics and explicitly declares it; incomplete, stale, unknown-sensitivity, or sensitive cases deny, while an allowed Package exposes proofKind Weak and declared as-of/freshness." + }, + { + "id": "PROV-018", + "mutation": "FileSourceAccess is missing, incomplete, unknown, cross-Organization, cross-Resource, or not the active manifest version.", + "expectedStatus": 200, + "expectedOutcome": "request_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "Deny generically with zero Evidence and no implicit owner/public fallback; an allowed File result uses the active versioned PostgreSQL grant and exposes complete Mirrored proof and freshness fields." + }, + { + "id": "PROV-019", + "mutation": "Host operating-system owner, mode, or ACL is permissive while FileSourceAccess is absent or denied.", + "expectedStatus": 200, + "expectedOutcome": "request_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "Host metadata never changes engine authorization; only active versioned PostgreSQL FileSourceAccess may yield an allowed Mirrored proof." + } ] }, "operation": { @@ -1169,13 +2522,41 @@ "phase": "M0 capability availability check before Provider invocation; owning carrier later upgrades each activatedOracle at its highest public seam" }, "expected": { - "externalResponse": {"status": 200, "body": {"kind": "request_not_available", "retryable": false}}, - "packageOrError": {"kind": "request_not_available", "aclModeUsed": null, "weakFallbackCount": 0, "capabilityReportedAsPass": false}, - "evidence": {"unauthorizedEvidenceCount": 0, "unauthorizedContentBytes": 0, "missingContextFallbackCount": 0, "outboundBytes": 0}, - "businessEffects": {"wrongOrganizationEffectCount": 0, "mutationEffectCount": 0, "totalEffectsAfterScenario": 0}, - "io": {"providerCalls": 0, "indexCalls": 0, "modelCalls": 0, "actionCalls": 0} + "externalResponse": { + "status": 200, + "body": { + "kind": "request_not_available", + "retryable": false + } + }, + "packageOrError": { + "kind": "request_not_available", + "aclModeUsed": null, + "weakFallbackCount": 0, + "capabilityReportedAsPass": false + }, + "evidence": { + "unauthorizedEvidenceCount": 0, + "unauthorizedContentBytes": 0, + "missingContextFallbackCount": 0, + "outboundBytes": 0 + }, + "businessEffects": { + "wrongOrganizationEffectCount": 0, + "mutationEffectCount": 0, + "totalEffectsAfterScenario": 0 + }, + "io": { + "providerCalls": 0, + "indexCalls": 0, + "modelCalls": 0, + "actionCalls": 0 + } }, - "invariantRefs": ["INDEX-NOT-AUTHORITY-005", "REVOCATION-006"], + "invariantRefs": [ + "INDEX-NOT-AUTHORITY-005", + "REVOCATION-006" + ], "authorityRefs": [ "docs/design/2026-07-18-context-engine-implementation-design.md#33-contextprovider-and-source-projection", "docs/security/Test-Architecture-与可验证性设计.md#13-v1-acceptance-scenarios", @@ -1218,13 +2599,41 @@ "phase": "inactive-capability gate before source or blob I/O" }, "expected": { - "externalResponse": {"status": 200, "body": {"kind": "citation_not_available"}}, - "packageOrError": {"kind": "citation_not_available", "citationFieldsReturned": 0, "capabilityStatus": "unavailable", "capabilityReportedAsPass": false}, - "evidence": {"unauthorizedEvidenceCount": 0, "unauthorizedContentBytes": 0, "missingContextFallbackCount": 0, "outboundBytes": 0}, - "businessEffects": {"wrongOrganizationEffectCount": 0, "mutationEffectCount": 0, "totalEffectsAfterScenario": 0}, - "io": {"providerCalls": 0, "indexCalls": 0, "modelCalls": 0, "actionCalls": 0} + "externalResponse": { + "status": 200, + "body": { + "kind": "citation_not_available" + } + }, + "packageOrError": { + "kind": "citation_not_available", + "citationFieldsReturned": 0, + "capabilityStatus": "unavailable", + "capabilityReportedAsPass": false + }, + "evidence": { + "unauthorizedEvidenceCount": 0, + "unauthorizedContentBytes": 0, + "missingContextFallbackCount": 0, + "outboundBytes": 0 + }, + "businessEffects": { + "wrongOrganizationEffectCount": 0, + "mutationEffectCount": 0, + "totalEffectsAfterScenario": 0 + }, + "io": { + "providerCalls": 0, + "indexCalls": 0, + "modelCalls": 0, + "actionCalls": 0 + } }, - "invariantRefs": ["REVOCATION-006", "CITATION-AUTH-010", "NON-ENUMERATION-009"], + "invariantRefs": [ + "REVOCATION-006", + "CITATION-AUTH-010", + "NON-ENUMERATION-009" + ], "authorityRefs": [ "docs/design/2026-07-18-context-engine-implementation-design.md#53-tokens-and-locators", "docs/security/安全负向测试清单.md#6-runtimeassemblycitation-与-egress", @@ -1255,14 +2664,36 @@ }, "adversarialMutation": { "kind": "existence_oracle_triplet", - "probes": ["resource-cross-org", "resource-same-org-denied", "resource-missing"], - "order": ["cross_organization_denied", "same_organization_denied", "missing"] + "probes": [ + "resource-cross-org", + "resource-same-org-denied", + "resource-missing" + ], + "order": [ + "cross_organization_denied", + "same_organization_denied", + "missing" + ] }, "operation": { "interface": "ContextRuntime.resolve", "request": "Acquire each probe independently; one additional same-Organization denied-first rank variant repeats the same deterministic oracle", - "comparisonFields": ["status", "body", "headers", "domainOutcome"], - "normalizationAllowlist": ["body.package.organizationRef", "body.package.decisionRef", "body.package.asOf", "body.package.expiresAt", "body.package.packageDigest", "headers.X-Context-Request-Id"] + "comparisonFields": [ + "status", + "body", + "headers", + "domainOutcome" + ], + "normalizationAllowlist": [ + "body.package.packageId", + "body.package.decisionRef", + "body.package.policySnapshotRef", + "body.package.runRef", + "body.package.asOf", + "body.package.expiresAt", + "body.package.packageDigest", + "headers.X-Context-Request-Id" + ] }, "expected": { "externalResponse": { @@ -1270,30 +2701,75 @@ "body": { "kind": "resolved", "package": { - "organizationRef": "orgpkg_0000000000000000000000000000000a", "purpose": "context.answer", "ttlSeconds": 30, "asOf": "2026-07-21T09:30:00Z", "expiresAt": "2026-07-21T09:30:30Z", "decisionRef": "dec_0000000000000000000000000000000a", - "packageDigest": "27f6a284027ab9446aa577125727b33263f24c8f252b8cd4616bd17b8545185e", "blocks": [], "evidence": [], "gaps": [], - "budgetUsage": {"tokens": 0, "providerCalls": 0, "costMicrounits": 0, "elapsedMs": 0}, - "coverage": {"status": "empty", "reason": "no_authorized_evidence"} + "budgetUsage": { + "tokens": 0, + "providerCalls": 0, + "costMicrounits": 0, + "elapsedMs": 0 + }, + "coverage": { + "status": "empty", + "reason": "no_authorized_evidence" + }, + "packageId": "pkg_0000000000000000000000000000000a", + "audienceDigest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "policyEpoch": 1, + "policySnapshotRef": "policy-snapshot-a", + "runRef": "run-authorized-a", + "releaseManifestRef": "manifest-m0-empty-v0", + "retentionPolicyRef": "package-digest-only-retention-v1", + "tokenizerRef": "utf8-byte-budget-v1", + "packageSchemaRef": "context-package-openapi-v0", + "continuation": null, + "packageDigest": "94d68444d124f453eb6c62e0132ea8e90a3c4017230e8e7b3bfe138d1daa10d1" } }, - "headers": {"Content-Type": "application/json", "Cache-Control": "no-store", "X-Context-Request-Id": "normalized-request-id"}, + "headers": { + "Content-Type": "application/json", + "Cache-Control": "no-store", + "X-Context-Request-Id": "normalized-request-id" + }, "normalizedByteIdenticalAcrossProbes": true, "timingEqualityClaimed": false }, - "packageOrError": {"kind": "ContextPackage", "packageCount": 4, "coverageStatus": "empty", "coverageReason": "no_authorized_evidence", "deniedCountExposed": false, "existenceDetailCount": 0}, - "evidence": {"unauthorizedEvidenceCount": 0, "unauthorizedContentBytes": 0, "missingContextFallbackCount": 0, "outboundBytes": 0}, - "businessEffects": {"wrongOrganizationEffectCount": 0, "mutationEffectCount": 0, "totalEffectsAfterScenario": 0}, - "io": {"providerCalls": 0, "indexCalls": 1, "modelCalls": 0, "actionCalls": 0} + "packageOrError": { + "kind": "ContextPackage", + "packageCount": 4, + "coverageStatus": "empty", + "coverageReason": "no_authorized_evidence", + "deniedCountExposed": false, + "existenceDetailCount": 0 + }, + "evidence": { + "unauthorizedEvidenceCount": 0, + "unauthorizedContentBytes": 0, + "missingContextFallbackCount": 0, + "outboundBytes": 0 + }, + "businessEffects": { + "wrongOrganizationEffectCount": 0, + "mutationEffectCount": 0, + "totalEffectsAfterScenario": 0 + }, + "io": { + "providerCalls": 0, + "indexCalls": 1, + "modelCalls": 0, + "actionCalls": 0 + } }, - "invariantRefs": ["NON-ENUMERATION-009", "TRACE-REDACTION-012"], + "invariantRefs": [ + "NON-ENUMERATION-009", + "TRACE-REDACTION-012" + ], "authorityRefs": [ "docs/security/context-engine-threat-model.md#6-threat-register", "docs/security/安全负向测试清单.md#7-tracedebugnon-enumeration-与-learning", @@ -1335,20 +2811,146 @@ "destination": "conversation-b", "targetOrganization": "org-b", "parameterizedCases": [ - {"id": "AUTH-010", "mutation": "A trusted group AudienceSnapshot contains an unknown, unbound, external, or lookup-failed member.", "expectedStatus": 404, "expectedOutcome": "action_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "The public Package, group-send bytes, and group effects are zero; only a separately resolved explicit private flow may proceed."}, - {"id": "RUN-014", "mutation": "One question needs a group-public result and an asker-private supplement.", "expectedStatus": 404, "expectedOutcome": "action_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "Resolve two independent audience-bound Packages and EgressGrants; never derive or split the public Package from the asker-private Package, and cross-audience private bytes remain zero."}, - {"id": "EGR-003", "mutation": "BotDelivery bypasses the Kernel, expands AudienceSnapshot, or slices asker-private content for public delivery.", "expectedStatus": 404, "expectedOutcome": "action_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "Reject at the trusted boundary with zero public, model, or sender bytes and zero public effects; restricted audit records only the violation category."}, - {"id": "EGR-005", "mutation": "A member joins or leaves after resolve, or send-time audience lookup is stale, unknown, or unavailable.", "expectedStatus": 404, "expectedOutcome": "action_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "ActionPlane.prepare returns AudienceChanged for stale or unknown audience; no ActionTicket, group bytes, or effect is produced, and delivery must re-resolve or use a separate private flow."}, - {"id": "EGR-006", "mutation": "Future members can read group history while the old-snapshot Package contains content not authorized for every future reader.", "expectedStatus": 404, "expectedOutcome": "action_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "Protected public and future-member bytes and public effects remain zero unless verifiable delete/redaction compensation proves safety; otherwise use a generic notice, per-opener citation, or separate private delivery."}, - {"id": "ACTION-001", "mutation": "Use a ContextAccessTicket for refund, update, edit, or send.", "expectedStatus": 404, "expectedOutcome": "action_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "ActionPlane rejects the wrong capability or audience with effect zero; read authority never creates a write effect."}, - {"id": "ACTION-002", "mutation": "Use an ActionTicket for ContextRuntime resolve or Provider read.", "expectedStatus": 404, "expectedOutcome": "action_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "The read boundary rejects the wrong capability with zero Evidence and content work, and does not consume the ActionTicket."}, - {"id": "ACTION-003", "mutation": "Use a CreatePlaceholder ticket for FinalizeReply or another effect, or reverse the ticket/payload pairing.", "expectedStatus": 404, "expectedOutcome": "action_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "ActionPlane.perform returns Rejected with effect zero for every operation, destination, audience, or payload-class mismatch."}, - {"id": "ACTION-004", "mutation": "Replay separately prepared create and finalize tickets sequentially and concurrently.", "expectedStatus": 404, "expectedOutcome": "action_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "Each distinct ticket produces at most one corresponding Applied effect; every successful replay returns AlreadyApplied with the same stored receipt and adds zero effects."}, - {"id": "ACTION-005", "mutation": "Bypass prepare or present a caller-signed ActionTicket directly to perform.", "expectedStatus": 404, "expectedOutcome": "action_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "ActionPlane.perform returns Rejected with effect zero, creates no ticket, and makes no Sender call."}, - {"id": "ACTION-006", "mutation": "Mutate Organization, operation, destination, audience, payload digest, epoch, expiry, approval tier, idempotency key, or nonce after prepare.", "expectedStatus": 404, "expectedOutcome": "action_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "Exact binding validation returns Rejected with zero new, wrong-Organization, or wrong-audience effects."}, - {"id": "ACTION-007", "mutation": "After a timeout-after-send or ambiguous provider result, retry with a new ticket, key, or attempt id.", "expectedStatus": 404, "expectedOutcome": "action_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "Return ReconciliationRequired with the original providerAttemptRef; create no replacement ticket or additional effect and reconcile only under the original id."}, - {"id": "ACTION-008", "mutation": "Prepare encounters policy denial, audience drift, or temporary unavailability.", "expectedStatus": 404, "expectedOutcome": "action_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "Return exactly GenericDenied, AudienceChanged, or RetryableUnavailable for the matching condition, with no ActionTicket, Sender call, or effect."}, - {"id": "ACTION-009", "mutation": "Perform receives a wrong ticket or payload, or an external attempt remains ambiguous.", "expectedStatus": 404, "expectedOutcome": "action_not_available", "expectedNewDurableEffects": 0, "expectedWrongOrganizationEffects": 0, "expectedContentWorkCalls": 0, "activatedOracle": "Return Rejected(effect zero) for deterministic mismatch or ReconciliationRequired with the original providerAttemptRef for ambiguity; never mint retry authority or an extra effect."} + { + "id": "AUTH-010", + "mutation": "A trusted group AudienceSnapshot contains an unknown, unbound, external, or lookup-failed member.", + "expectedStatus": 404, + "expectedOutcome": "action_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "The public Package, group-send bytes, and group effects are zero; only a separately resolved explicit private flow may proceed." + }, + { + "id": "RUN-014", + "mutation": "One question needs a group-public result and an asker-private supplement.", + "expectedStatus": 404, + "expectedOutcome": "action_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "Resolve two independent audience-bound Packages and EgressGrants; never derive or split the public Package from the asker-private Package, and cross-audience private bytes remain zero." + }, + { + "id": "EGR-003", + "mutation": "BotDelivery bypasses the Kernel, expands AudienceSnapshot, or slices asker-private content for public delivery.", + "expectedStatus": 404, + "expectedOutcome": "action_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "Reject at the trusted boundary with zero public, model, or sender bytes and zero public effects; restricted audit records only the violation category." + }, + { + "id": "EGR-005", + "mutation": "A member joins or leaves after resolve, or send-time audience lookup is stale, unknown, or unavailable.", + "expectedStatus": 404, + "expectedOutcome": "action_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "ActionPlane.prepare returns AudienceChanged for stale or unknown audience; no ActionTicket, group bytes, or effect is produced, and delivery must re-resolve or use a separate private flow." + }, + { + "id": "EGR-006", + "mutation": "Future members can read group history while the old-snapshot Package contains content not authorized for every future reader.", + "expectedStatus": 404, + "expectedOutcome": "action_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "Protected public and future-member bytes and public effects remain zero unless verifiable delete/redaction compensation proves safety; otherwise use a generic notice, per-opener citation, or separate private delivery." + }, + { + "id": "ACTION-001", + "mutation": "Use a ContextAccessTicket for refund, update, edit, or send.", + "expectedStatus": 404, + "expectedOutcome": "action_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "ActionPlane rejects the wrong capability or audience with effect zero; read authority never creates a write effect." + }, + { + "id": "ACTION-002", + "mutation": "Use an ActionTicket for ContextRuntime resolve or Provider read.", + "expectedStatus": 404, + "expectedOutcome": "action_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "The read boundary rejects the wrong capability with zero Evidence and content work, and does not consume the ActionTicket." + }, + { + "id": "ACTION-003", + "mutation": "Use a CreatePlaceholder ticket for FinalizeReply or another effect, or reverse the ticket/payload pairing.", + "expectedStatus": 404, + "expectedOutcome": "action_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "ActionPlane.perform returns Rejected with effect zero for every operation, destination, audience, or payload-class mismatch." + }, + { + "id": "ACTION-004", + "mutation": "Replay separately prepared create and finalize tickets sequentially and concurrently.", + "expectedStatus": 404, + "expectedOutcome": "action_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "Each distinct ticket produces at most one corresponding Applied effect; every successful replay returns AlreadyApplied with the same stored receipt and adds zero effects." + }, + { + "id": "ACTION-005", + "mutation": "Bypass prepare or present a caller-signed ActionTicket directly to perform.", + "expectedStatus": 404, + "expectedOutcome": "action_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "ActionPlane.perform returns Rejected with effect zero, creates no ticket, and makes no Sender call." + }, + { + "id": "ACTION-006", + "mutation": "Mutate Organization, operation, destination, audience, payload digest, epoch, expiry, approval tier, idempotency key, or nonce after prepare.", + "expectedStatus": 404, + "expectedOutcome": "action_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "Exact binding validation returns Rejected with zero new, wrong-Organization, or wrong-audience effects." + }, + { + "id": "ACTION-007", + "mutation": "After a timeout-after-send or ambiguous provider result, retry with a new ticket, key, or attempt id.", + "expectedStatus": 404, + "expectedOutcome": "action_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "Return ReconciliationRequired with the original providerAttemptRef; create no replacement ticket or additional effect and reconcile only under the original id." + }, + { + "id": "ACTION-008", + "mutation": "Prepare encounters policy denial, audience drift, or temporary unavailability.", + "expectedStatus": 404, + "expectedOutcome": "action_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "Return exactly GenericDenied, AudienceChanged, or RetryableUnavailable for the matching condition, with no ActionTicket, Sender call, or effect." + }, + { + "id": "ACTION-009", + "mutation": "Perform receives a wrong ticket or payload, or an external attempt remains ambiguous.", + "expectedStatus": 404, + "expectedOutcome": "action_not_available", + "expectedNewDurableEffects": 0, + "expectedWrongOrganizationEffects": 0, + "expectedContentWorkCalls": 0, + "activatedOracle": "Return Rejected(effect zero) for deterministic mismatch or ReconciliationRequired with the original providerAttemptRef for ambiguity; never mint retry authority or an extra effect." + } ] }, "operation": { @@ -1357,13 +2959,43 @@ "phase": "M0 inactive-capability gate before content or Sender I/O; owning M2 carriers later upgrade each activatedOracle at its highest public seam" }, "expected": { - "externalResponse": {"status": 404, "code": "action_not_available", "body": {"kind": "generic_unavailable"}}, - "packageOrError": {"kind": "action_rejection", "actionTicketCreated": false, "contextTicketConsumed": false, "capabilityReportedAsPass": false}, - "evidence": {"unauthorizedEvidenceCount": 0, "unauthorizedContentBytes": 0, "missingContextFallbackCount": 0, "outboundBytes": 0}, - "businessEffects": {"wrongOrganizationEffectCount": 0, "mutationEffectCount": 0, "totalEffectsAfterScenario": 0}, - "io": {"providerCalls": 0, "indexCalls": 0, "modelCalls": 0, "actionCalls": 0} + "externalResponse": { + "status": 404, + "code": "action_not_available", + "body": { + "kind": "generic_unavailable" + } + }, + "packageOrError": { + "kind": "action_rejection", + "actionTicketCreated": false, + "contextTicketConsumed": false, + "capabilityReportedAsPass": false + }, + "evidence": { + "unauthorizedEvidenceCount": 0, + "unauthorizedContentBytes": 0, + "missingContextFallbackCount": 0, + "outboundBytes": 0 + }, + "businessEffects": { + "wrongOrganizationEffectCount": 0, + "mutationEffectCount": 0, + "totalEffectsAfterScenario": 0 + }, + "io": { + "providerCalls": 0, + "indexCalls": 0, + "modelCalls": 0, + "actionCalls": 0 + } }, - "invariantRefs": ["SCOPE-INTERSECTION-004", "TRANSPORT-UNTRUSTED-008", "EGRESS-011", "ACTION-SEPARATION-014"], + "invariantRefs": [ + "SCOPE-INTERSECTION-004", + "TRANSPORT-UNTRUSTED-008", + "EGRESS-011", + "ACTION-SEPARATION-014" + ], "authorityRefs": [ "docs/agents/prd-contextengine-implementation.md#implementation-decisions", "docs/security/Test-Architecture-与可验证性设计.md#75-egress-与-action-contract", diff --git a/migrations/versions/20260723_0021_runtime_release_observation.py b/migrations/versions/20260723_0021_runtime_release_observation.py new file mode 100644 index 00000000..7cd90a93 --- /dev/null +++ b/migrations/versions/20260723_0021_runtime_release_observation.py @@ -0,0 +1,118 @@ +"""Allow Runtime to observe, never publish, the active release. + +Revision ID: 20260723_0021 +Revises: 20260723_0020 +Create Date: 2026-07-23 +""" + +from collections.abc import Sequence + +from alembic import op + +revision: str = "20260723_0021" +down_revision: str | None = "20260723_0020" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + +_CURRENT_USER_ACTOR = """ +{table_name}.organization_id = NULLIF( + current_setting('app.organization_id', true), '' +)::uuid +AND current_setting('app.actor_kind', true) = 'user' +AND EXISTS ( + SELECT 1 + FROM public.membership AS actor_membership + WHERE actor_membership.organization_id = {table_name}.organization_id + AND actor_membership.user_id = NULLIF( + current_setting('app.user_id', true), '' + )::uuid + AND actor_membership.membership_id = NULLIF( + current_setting('app.membership_id', true), '' + )::uuid + AND actor_membership.membership_version = NULLIF( + current_setting('app.membership_version', true), '' + )::bigint + AND NULLIF(current_setting('app.principal_ref', true), '') IS NOT NULL + AND NULLIF(current_setting('app.request_id', true), '') IS NOT NULL + AND NULLIF( + current_setting('app.authentication_binding_ref', true), '' + ) IS NOT NULL + AND NULLIF(current_setting('app.checked_at', true), '') IS NOT NULL + AND actor_membership.status = 'active' + AND actor_membership.valid_from <= NULLIF( + current_setting('app.checked_at', true), '' + )::timestamptz + AND ( + actor_membership.valid_until IS NULL + OR actor_membership.valid_until > NULLIF( + current_setting('app.checked_at', true), '' + )::timestamptz + ) +) +""".strip() + + +def upgrade() -> None: + op.drop_constraint( + "ck_context_run_package_digest_profile", + "context_run", + type_="check", + ) + op.create_check_constraint( + "ck_context_run_package_digest_profile", + "context_run", + "package_digest_profile IN (" + "'context-package-canonical-json-v1', " + "'context-package-canonical-json-v2', " + "'context-package-canonical-json-v3'" + ")", + ) + for table_name in ("release_manifest", "active_release_manifest"): + op.execute( + f"CREATE POLICY {table_name}_runtime_select " + f"ON public.{table_name} AS PERMISSIVE FOR SELECT " + "TO context_engine_runtime " + f"USING ({_CURRENT_USER_ACTOR.format(table_name=table_name)})" + ) + op.execute( + f"GRANT SELECT ON TABLE public.{table_name} TO context_engine_runtime" + ) + + +def downgrade() -> None: + op.execute( + """ + DO $body$ + BEGIN + IF EXISTS ( + SELECT 1 FROM public.context_run + WHERE package_digest_profile = + 'context-package-canonical-json-v3' + ) THEN + RAISE EXCEPTION USING + ERRCODE = '55006', + MESSAGE = 'runtime release observation downgrade refused: ' + 'v3 ContextRun lineage exists'; + END IF; + END + $body$ + """ + ) + for table_name in ("release_manifest", "active_release_manifest"): + op.execute( + f"REVOKE SELECT ON TABLE public.{table_name} FROM context_engine_runtime" + ) + op.execute(f"DROP POLICY {table_name}_runtime_select ON public.{table_name}") + op.drop_constraint( + "ck_context_run_package_digest_profile", + "context_run", + type_="check", + ) + op.create_check_constraint( + "ck_context_run_package_digest_profile", + "context_run", + "package_digest_profile IN (" + "'context-package-canonical-json-v1', " + "'context-package-canonical-json-v2'" + ")", + ) diff --git a/openapi/v0/openapi.json b/openapi/v0/openapi.json new file mode 100644 index 00000000..83820f86 --- /dev/null +++ b/openapi/v0/openapi.json @@ -0,0 +1,1217 @@ +{ + "components": { + "schemas": { + "AcquireWire": { + "additionalProperties": false, + "description": "Closed untrusted Acquire variant.", + "properties": { + "kind": { + "const": "acquire", + "title": "Kind", + "type": "string" + }, + "need": { + "$ref": "#/components/schemas/ContextNeedWire" + }, + "packageBudget": { + "anyOf": [ + { + "$ref": "#/components/schemas/PackageBudgetWire" + }, + { + "type": "null" + } + ] + }, + "requestNarrowing": { + "anyOf": [ + { + "$ref": "#/components/schemas/RequestNarrowingWire" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "kind", + "need" + ], + "title": "AcquireWire", + "type": "object" + }, + "ApplicationForbiddenWire": { + "additionalProperties": false, + "properties": { + "code": { + "const": "application_forbidden", + "title": "Code", + "type": "string" + } + }, + "required": [ + "code" + ], + "title": "ApplicationForbiddenWire", + "type": "object" + }, + "AuthenticationFailureWire": { + "additionalProperties": false, + "description": "Closed public response for every transport authentication rejection.", + "properties": { + "code": { + "const": "authentication_failed", + "title": "Code", + "type": "string" + } + }, + "required": [ + "code" + ], + "title": "AuthenticationFailureWire", + "type": "object" + }, + "BlockWire": { + "additionalProperties": false, + "description": "One authorized text block bound to exactly one public Evidence ref.", + "properties": { + "blockId": { + "pattern": "^block_[0-9a-f]{64}$", + "title": "Blockid", + "type": "string" + }, + "evidenceRefs": { + "items": { + "pattern": "^ev_[0-9a-f]{64}$", + "type": "string" + }, + "maxItems": 1, + "minItems": 1, + "title": "Evidencerefs", + "type": "array" + }, + "text": { + "minLength": 1, + "pattern": ".*\\S.*", + "title": "Text", + "type": "string" + } + }, + "required": [ + "blockId", + "text", + "evidenceRefs" + ], + "title": "BlockWire", + "type": "object" + }, + "BudgetUsageWire": { + "additionalProperties": false, + "description": "Actual resources consumed by this Package.", + "properties": { + "costMicrounits": { + "minimum": 0.0, + "title": "Costmicrounits", + "type": "integer" + }, + "elapsedMs": { + "minimum": 0.0, + "title": "Elapsedms", + "type": "integer" + }, + "providerCalls": { + "minimum": 0.0, + "title": "Providercalls", + "type": "integer" + }, + "tokens": { + "minimum": 0.0, + "title": "Tokens", + "type": "integer" + } + }, + "required": [ + "tokens", + "providerCalls", + "costMicrounits", + "elapsedMs" + ], + "title": "BudgetUsageWire", + "type": "object" + }, + "ChannelEgressGrantWire": { + "additionalProperties": false, + "description": "Opaque one-hop channel grant; it carries no write authority.", + "properties": { + "kind": { + "const": "channel", + "title": "Kind", + "type": "string" + }, + "value": { + "pattern": "^egrc_[0-9a-f]{64}$", + "title": "Value", + "type": "string" + } + }, + "required": [ + "kind", + "value" + ], + "title": "ChannelEgressGrantWire", + "type": "object" + }, + "CitationNotAvailableWire": { + "additionalProperties": false, + "description": "Caller-safe outcome for an unavailable citation open.", + "properties": { + "kind": { + "const": "citation_not_available", + "title": "Kind", + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "CitationNotAvailableWire", + "type": "object" + }, + "ContextNeedWire": { + "additionalProperties": false, + "description": "Untrusted context need; it carries no identity or authority.", + "properties": { + "query": { + "minLength": 1, + "pattern": ".*\\S.*", + "title": "Query", + "type": "string" + } + }, + "required": [ + "query" + ], + "title": "ContextNeedWire", + "type": "object" + }, + "ContextPackageWire": { + "additionalProperties": false, + "description": "Public package with an exact block/Evidence closure.", + "properties": { + "asOf": { + "format": "date-time", + "title": "Asof", + "type": "string" + }, + "audienceDigest": { + "pattern": "^[0-9a-f]{64}$", + "title": "Audiencedigest", + "type": "string" + }, + "blocks": { + "items": { + "$ref": "#/components/schemas/BlockWire" + }, + "title": "Blocks", + "type": "array" + }, + "budgetUsage": { + "$ref": "#/components/schemas/BudgetUsageWire" + }, + "continuation": { + "anyOf": [ + { + "$ref": "#/components/schemas/ContinuationOfferWire" + }, + { + "type": "null" + } + ] + }, + "coverage": { + "$ref": "#/components/schemas/CoverageWire" + }, + "decisionRef": { + "pattern": "^dec_[0-9a-f]{32}$", + "title": "Decisionref", + "type": "string" + }, + "evidence": { + "items": { + "$ref": "#/components/schemas/EvidenceWire" + }, + "title": "Evidence", + "type": "array" + }, + "expiresAt": { + "format": "date-time", + "title": "Expiresat", + "type": "string" + }, + "gaps": { + "items": { + "$ref": "#/components/schemas/GapWire" + }, + "title": "Gaps", + "type": "array" + }, + "packageDigest": { + "pattern": "^[0-9a-f]{64}$", + "title": "Packagedigest", + "type": "string" + }, + "packageId": { + "pattern": "^pkg_[0-9a-f]{32}$", + "title": "Packageid", + "type": "string" + }, + "packageSchemaRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Packageschemaref", + "type": "string" + }, + "policyEpoch": { + "maximum": 9.223372036854776e+18, + "minimum": 1.0, + "title": "Policyepoch", + "type": "integer" + }, + "policySnapshotRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Policysnapshotref", + "type": "string" + }, + "purpose": { + "minLength": 1, + "pattern": ".*\\S.*", + "title": "Purpose", + "type": "string" + }, + "releaseManifestRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Releasemanifestref", + "type": "string" + }, + "retentionPolicyRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Retentionpolicyref", + "type": "string" + }, + "runRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Runref", + "type": "string" + }, + "tokenizerRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Tokenizerref", + "type": "string" + }, + "ttlSeconds": { + "exclusiveMinimum": 0.0, + "title": "Ttlseconds", + "type": "integer" + } + }, + "required": [ + "packageId", + "packageDigest", + "purpose", + "audienceDigest", + "policyEpoch", + "policySnapshotRef", + "decisionRef", + "runRef", + "releaseManifestRef", + "retentionPolicyRef", + "asOf", + "expiresAt", + "ttlSeconds", + "tokenizerRef", + "packageSchemaRef", + "blocks", + "evidence", + "gaps", + "coverage", + "budgetUsage", + "continuation" + ], + "title": "ContextPackageWire", + "type": "object" + }, + "ContinuationOfferWire": { + "additionalProperties": false, + "properties": { + "continuationToken": { + "maxLength": 4096, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Continuationtoken", + "type": "string" + }, + "remainingBudgetDigest": { + "pattern": "^[0-9a-f]{64}$", + "title": "Remainingbudgetdigest", + "type": "string" + } + }, + "required": [ + "continuationToken", + "remainingBudgetDigest" + ], + "title": "ContinuationOfferWire", + "type": "object" + }, + "ContinueWire": { + "additionalProperties": false, + "description": "Closed known continuation variant; its carrier is unavailable at M0.", + "properties": { + "continuationToken": { + "maxLength": 4096, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Continuationtoken", + "type": "string" + }, + "kind": { + "const": "continue", + "title": "Kind", + "type": "string" + }, + "packageBudget": { + "anyOf": [ + { + "$ref": "#/components/schemas/PackageBudgetWire" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "kind", + "continuationToken" + ], + "title": "ContinueWire", + "type": "object" + }, + "CoverageWire": { + "additionalProperties": false, + "description": "Typed tenant-safe coverage for the selected package content.", + "properties": { + "reason": { + "anyOf": [ + { + "enum": [ + "no_authorized_evidence", + "source_unavailable", + "stale_evidence", + "budget_exhausted", + "capability_unsupported" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Reason" + }, + "status": { + "enum": [ + "empty", + "partial", + "sufficient" + ], + "title": "Status", + "type": "string" + } + }, + "required": [ + "status" + ], + "title": "CoverageWire", + "type": "object" + }, + "EvidenceWire": { + "additionalProperties": false, + "description": "Public request-scoped Evidence and its authorization lineage.", + "properties": { + "authorizationAsOf": { + "format": "date-time", + "title": "Authorizationasof", + "type": "string" + }, + "citationOpenRef": { + "anyOf": [ + { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Citationopenref" + }, + "decisionRef": { + "pattern": "^dec_[0-9a-f]{32}$", + "title": "Decisionref", + "type": "string" + }, + "evidenceRef": { + "pattern": "^ev_[0-9a-f]{64}$", + "title": "Evidenceref", + "type": "string" + }, + "fragmentRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Fragmentref", + "type": "string" + }, + "policyEpoch": { + "maximum": 9.223372036854776e+18, + "minimum": 1.0, + "title": "Policyepoch", + "type": "integer" + }, + "policySnapshotRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Policysnapshotref", + "type": "string" + }, + "projectedFields": { + "items": { + "pattern": "^[a-z][a-z0-9_]{0,63}$", + "type": "string" + }, + "maxItems": 64, + "minItems": 1, + "title": "Projectedfields", + "type": "array" + }, + "purpose": { + "minLength": 1, + "pattern": ".*\\S.*", + "title": "Purpose", + "type": "string" + }, + "resourceRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Resourceref", + "type": "string" + }, + "revisionRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Revisionref", + "type": "string" + }, + "runRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Runref", + "type": "string" + }, + "sourceAclEvidence": { + "$ref": "#/components/schemas/SourceAclEvidenceWire" + }, + "sourceRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Sourceref", + "type": "string" + } + }, + "required": [ + "evidenceRef", + "sourceRef", + "resourceRef", + "revisionRef", + "fragmentRef", + "projectedFields", + "runRef", + "purpose", + "authorizationAsOf", + "decisionRef", + "policySnapshotRef", + "policyEpoch", + "sourceAclEvidence", + "citationOpenRef" + ], + "title": "EvidenceWire", + "type": "object" + }, + "GapWire": { + "additionalProperties": false, + "properties": { + "category": { + "enum": [ + "source_unavailable", + "stale_evidence", + "budget_exhausted", + "capability_unsupported" + ], + "title": "Category", + "type": "string" + }, + "retryable": { + "title": "Retryable", + "type": "boolean" + } + }, + "required": [ + "category", + "retryable" + ], + "title": "GapWire", + "type": "object" + }, + "InvalidRequestWire": { + "additionalProperties": false, + "description": "Closed public response for request syntax or schema rejection.", + "properties": { + "code": { + "const": "invalid_request", + "title": "Code", + "type": "string" + } + }, + "required": [ + "code" + ], + "title": "InvalidRequestWire", + "type": "object" + }, + "LiveSourceAclEvidenceWire": { + "additionalProperties": false, + "properties": { + "checkedAt": { + "format": "date-time", + "title": "Checkedat", + "type": "string" + }, + "kind": { + "const": "live", + "title": "Kind", + "type": "string" + }, + "sourceDecisionRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Sourcedecisionref", + "type": "string" + }, + "verificationProtocolRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Verificationprotocolref", + "type": "string" + } + }, + "required": [ + "kind", + "sourceDecisionRef", + "checkedAt", + "verificationProtocolRef" + ], + "title": "LiveSourceAclEvidenceWire", + "type": "object" + }, + "MirroredSourceAclEvidenceWire": { + "additionalProperties": false, + "properties": { + "aclAsOf": { + "format": "date-time", + "title": "Aclasof", + "type": "string" + }, + "freshnessProfileRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Freshnessprofileref", + "type": "string" + }, + "kind": { + "const": "mirrored", + "title": "Kind", + "type": "string" + }, + "projectionRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Projectionref", + "type": "string" + } + }, + "required": [ + "kind", + "projectionRef", + "aclAsOf", + "freshnessProfileRef" + ], + "title": "MirroredSourceAclEvidenceWire", + "type": "object" + }, + "ModelEgressGrantWire": { + "additionalProperties": false, + "description": "Opaque one-hop model grant; no trusted claim is exposed on the wire.", + "properties": { + "kind": { + "const": "model", + "title": "Kind", + "type": "string" + }, + "value": { + "pattern": "^egrm_[0-9a-f]{64}$", + "title": "Value", + "type": "string" + } + }, + "required": [ + "kind", + "value" + ], + "title": "ModelEgressGrantWire", + "type": "object" + }, + "OpenCitationWire": { + "additionalProperties": false, + "description": "Closed known citation variant; its locator carries no authority.", + "properties": { + "citationOpenRef": { + "maxLength": 4096, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Citationopenref", + "type": "string" + }, + "kind": { + "const": "open_citation", + "title": "Kind", + "type": "string" + } + }, + "required": [ + "kind", + "citationOpenRef" + ], + "title": "OpenCitationWire", + "type": "object" + }, + "PackageBudgetWire": { + "additionalProperties": false, + "description": "Caller ceiling; every supplied dimension is a strict positive integer.", + "properties": { + "maxCostMicrounits": { + "anyOf": [ + { + "exclusiveMinimum": 0.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Maxcostmicrounits" + }, + "maxElapsedMs": { + "anyOf": [ + { + "exclusiveMinimum": 0.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Maxelapsedms" + }, + "maxProviderCalls": { + "anyOf": [ + { + "exclusiveMinimum": 0.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Maxprovidercalls" + }, + "maxTokens": { + "anyOf": [ + { + "exclusiveMinimum": 0.0, + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Maxtokens" + } + }, + "title": "PackageBudgetWire", + "type": "object" + }, + "RateLimitedWire": { + "additionalProperties": false, + "properties": { + "code": { + "const": "rate_limited", + "title": "Code", + "type": "string" + } + }, + "required": [ + "code" + ], + "title": "RateLimitedWire", + "type": "object" + }, + "RequestNarrowingWire": { + "additionalProperties": false, + "description": "Untrusted source/resource filters that can only narrow future scope.", + "properties": { + "resourceRefs": { + "anyOf": [ + { + "items": { + "maxLength": 256, + "minLength": 1, + "pattern": ".*\\S.*", + "type": "string" + }, + "maxItems": 64, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Resourcerefs" + }, + "sourceRefs": { + "anyOf": [ + { + "items": { + "maxLength": 256, + "minLength": 1, + "pattern": ".*\\S.*", + "type": "string" + }, + "maxItems": 64, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Sourcerefs" + } + }, + "title": "RequestNarrowingWire", + "type": "object" + }, + "RequestNotAvailableWire": { + "additionalProperties": false, + "description": "Caller-safe outcome for an unavailable known request.", + "properties": { + "kind": { + "const": "request_not_available", + "title": "Kind", + "type": "string" + }, + "retryable": { + "const": false, + "title": "Retryable", + "type": "boolean" + } + }, + "required": [ + "kind", + "retryable" + ], + "title": "RequestNotAvailableWire", + "type": "object" + }, + "ResolutionOutcomeWire": { + "discriminator": { + "mapping": { + "citation_not_available": "#/components/schemas/CitationNotAvailableWire", + "request_not_available": "#/components/schemas/RequestNotAvailableWire", + "resolved": "#/components/schemas/ResolvedWire" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/components/schemas/ResolvedWire" + }, + { + "$ref": "#/components/schemas/RequestNotAvailableWire" + }, + { + "$ref": "#/components/schemas/CitationNotAvailableWire" + } + ] + }, + "ResolveWire": { + "discriminator": { + "mapping": { + "acquire": "#/components/schemas/AcquireWire", + "continue": "#/components/schemas/ContinueWire", + "open_citation": "#/components/schemas/OpenCitationWire" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/components/schemas/AcquireWire" + }, + { + "$ref": "#/components/schemas/ContinueWire" + }, + { + "$ref": "#/components/schemas/OpenCitationWire" + } + ] + }, + "ResolvedWire": { + "additionalProperties": false, + "description": "Successful public resolution envelope.", + "properties": { + "egressGrant": { + "anyOf": [ + { + "discriminator": { + "mapping": { + "channel": "#/components/schemas/ChannelEgressGrantWire", + "model": "#/components/schemas/ModelEgressGrantWire" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/components/schemas/ModelEgressGrantWire" + }, + { + "$ref": "#/components/schemas/ChannelEgressGrantWire" + } + ] + }, + { + "type": "null" + } + ], + "title": "Egressgrant" + }, + "kind": { + "const": "resolved", + "title": "Kind", + "type": "string" + }, + "package": { + "$ref": "#/components/schemas/ContextPackageWire" + } + }, + "required": [ + "kind", + "package", + "egressGrant" + ], + "title": "ResolvedWire", + "type": "object" + }, + "ServiceUnavailableWire": { + "additionalProperties": false, + "description": "Closed response when a required trusted authority is unavailable.", + "properties": { + "code": { + "const": "service_unavailable", + "title": "Code", + "type": "string" + } + }, + "required": [ + "code" + ], + "title": "ServiceUnavailableWire", + "type": "object" + }, + "SourceAclEvidenceWire": { + "discriminator": { + "mapping": { + "live": "#/components/schemas/LiveSourceAclEvidenceWire", + "mirrored": "#/components/schemas/MirroredSourceAclEvidenceWire", + "weak": "#/components/schemas/WeakSourceAclEvidenceWire" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/components/schemas/LiveSourceAclEvidenceWire" + }, + { + "$ref": "#/components/schemas/MirroredSourceAclEvidenceWire" + }, + { + "$ref": "#/components/schemas/WeakSourceAclEvidenceWire" + } + ] + }, + "WeakSourceAclEvidenceWire": { + "additionalProperties": false, + "properties": { + "boundedMembershipEvidenceRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Boundedmembershipevidenceref", + "type": "string" + }, + "checkedAt": { + "format": "date-time", + "title": "Checkedat", + "type": "string" + }, + "declarationRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Declarationref", + "type": "string" + }, + "expiresAt": { + "format": "date-time", + "title": "Expiresat", + "type": "string" + }, + "historySemanticsRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Historysemanticsref", + "type": "string" + }, + "kind": { + "const": "weak", + "title": "Kind", + "type": "string" + }, + "membershipCompleteness": { + "const": "complete", + "title": "Membershipcompleteness", + "type": "string" + }, + "sensitivityPolicyRef": { + "maxLength": 256, + "minLength": 1, + "pattern": "^\\S+$", + "title": "Sensitivitypolicyref", + "type": "string" + }, + "snapshotAsOf": { + "format": "date-time", + "title": "Snapshotasof", + "type": "string" + } + }, + "required": [ + "kind", + "declarationRef", + "checkedAt", + "boundedMembershipEvidenceRef", + "snapshotAsOf", + "expiresAt", + "membershipCompleteness", + "sensitivityPolicyRef", + "historySemanticsRef" + ], + "title": "WeakSourceAclEvidenceWire", + "type": "object" + } + }, + "securitySchemes": { + "ContextEngineBearer": { + "bearerFormat": "opaque", + "scheme": "bearer", + "type": "http" + } + } + }, + "info": { + "title": "ContextEngine", + "version": "0.0.0" + }, + "openapi": "3.1.0", + "paths": { + "/v0/resolve": { + "post": { + "description": "Map one authenticated closed request to the sealed Runtime entry.", + "operationId": "resolveContextV0", + "parameters": [ + { + "in": "header", + "name": "X-Context-Request-Id", + "required": true, + "schema": { + "maxLength": 256, + "minLength": 1, + "pattern": ".*\\S.*", + "title": "X-Context-Request-Id", + "type": "string" + } + }, + { + "in": "header", + "name": "X-Context-Delivery-Evidence-Ref", + "required": false, + "schema": { + "anyOf": [ + { + "maxLength": 4096, + "minLength": 1, + "pattern": "^\\S+$", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "X-Context-Delivery-Evidence-Ref" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ResolveWire" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ResolutionOutcomeWire" + } + } + }, + "description": "Successful Response" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestWire" + } + } + }, + "description": "The request transport syntax, media type, or active resource profile is invalid." + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AuthenticationFailureWire" + } + } + }, + "description": "Authentication failed.", + "headers": { + "WWW-Authenticate": { + "description": "The required transport authentication scheme.", + "schema": { + "type": "string" + } + } + } + }, + "403": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApplicationForbiddenWire" + } + } + }, + "description": "The authenticated application is not allowed." + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvalidRequestWire" + } + } + }, + "description": "The closed request schema rejected the body." + }, + "429": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RateLimitedWire" + } + } + }, + "description": "The application exceeded the route resource policy." + }, + "503": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ServiceUnavailableWire" + } + } + }, + "description": "A required trusted authority is unavailable." + } + }, + "security": [ + { + "ContextEngineBearer": [] + } + ], + "summary": "Resolve Context" + } + } + } +} diff --git a/openapi/v0/openapi.sha256 b/openapi/v0/openapi.sha256 new file mode 100644 index 00000000..28a4d436 --- /dev/null +++ b/openapi/v0/openapi.sha256 @@ -0,0 +1 @@ +5fa7add530dcfad066d67992bb1b18fdd1ed7ce423f632ebb55f880acaef1237 diff --git a/scripts/freeze_openapi.py b/scripts/freeze_openapi.py new file mode 100644 index 00000000..87a972a7 --- /dev/null +++ b/scripts/freeze_openapi.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +"""Create immutable OpenAPI snapshots and reject unreviewed contract drift.""" + +from __future__ import annotations + +import argparse +import json +import subprocess +from collections.abc import Mapping +from hashlib import sha256 +from pathlib import Path +from typing import Any, NoReturn + +from adapters.http.app import create_app + +ROOT = Path(__file__).resolve().parents[1] +DEFAULT_VERSION_DIRECTORY = ROOT / "openapi" / "v0" + + +class SnapshotAlreadyExists(RuntimeError): + """A historical contract snapshot cannot be replaced in place.""" + + +class BreakingContractChange(RuntimeError): + """The candidate no longer contains every accepted contract requirement.""" + + +class SnapshotDrift(RuntimeError): + """Generated OpenAPI differs from its accepted immutable snapshot.""" + + +def render_openapi_snapshot() -> bytes: + """Render the server contract with stable key ordering and one trailing LF.""" + + document = create_app().openapi() + return ( + json.dumps( + document, + ensure_ascii=False, + indent=2, + sort_keys=True, + separators=(",", ": "), + ) + + "\n" + ).encode("utf-8") + + +def write_new_snapshot(version_directory: Path) -> None: + """Create one new version directory, refusing every in-place replacement.""" + + snapshot = version_directory / "openapi.json" + digest = version_directory / "openapi.sha256" + if snapshot.exists() or digest.exists(): + raise SnapshotAlreadyExists( + "historical OpenAPI snapshots require a new reviewed version" + ) + version_directory.mkdir(parents=True, exist_ok=True) + rendered = render_openapi_snapshot() + snapshot.write_bytes(rendered) + digest.write_text(f"{sha256(rendered).hexdigest()}\n", encoding="ascii") + + +def _breaking(message: str) -> NoReturn: + raise BreakingContractChange(message) + + +def _schema_map(document: Mapping[str, Any]) -> Mapping[str, Any]: + try: + schemas = document["components"]["schemas"] + except (KeyError, TypeError): + _breaking("candidate removed components.schemas") + if not isinstance(schemas, Mapping): + _breaking("candidate components.schemas is not an object") + return schemas + + +def _first_contract_difference( + accepted: object, + candidate: object, + *, + pointer: str = "$", +) -> str | None: + """Return the first recursive structural difference in stable order.""" + + if type(accepted) is not type(candidate): + return f"{pointer} changed type" + if isinstance(accepted, Mapping) and isinstance(candidate, Mapping): + accepted_keys = set(accepted) + candidate_keys = set(candidate) + removed = sorted(accepted_keys - candidate_keys) + if removed: + return f"{pointer} removed {removed[0]}" + added = sorted(candidate_keys - accepted_keys) + if added: + return f"{pointer} added {added[0]}" + for key in sorted(accepted_keys): + difference = _first_contract_difference( + accepted[key], + candidate[key], + pointer=f"{pointer}.{key}", + ) + if difference is not None: + return difference + return None + if isinstance(accepted, list) and isinstance(candidate, list): + if len(accepted) != len(candidate): + return f"{pointer} changed array length" + for index, accepted_item in enumerate(accepted): + difference = _first_contract_difference( + accepted_item, + candidate[index], + pointer=f"{pointer}[{index}]", + ) + if difference is not None: + return difference + return None + if accepted != candidate: + return f"{pointer} changed value" + return None + + +def assert_no_breaking_changes( + accepted: Mapping[str, Any], + candidate: Mapping[str, Any], +) -> None: + """Reject every recursive mutation of one already-frozen version.""" + + _schema_map(accepted) + _schema_map(candidate) + difference = _first_contract_difference(accepted, candidate) + if difference is not None: + _breaking(f"frozen contract changed at {difference}") + + +def assert_historical_artifacts_unchanged( + *, + current_snapshot: bytes, + current_digest: bytes, + historical_snapshot: bytes | None, + historical_digest: bytes | None, +) -> None: + """Permit first publication, then make the accepted version append-only.""" + + if historical_snapshot is None and historical_digest is None: + return + if historical_snapshot is None or historical_digest is None: + raise SnapshotDrift("historical OpenAPI artifact pair is incomplete") + if current_snapshot != historical_snapshot or current_digest != historical_digest: + raise SnapshotDrift( + "historical OpenAPI version changed; publish a new version directory" + ) + + +def _historical_file( + baseline_ref: str, + path: Path, + *, + repository_root: Path, +) -> bytes | None: + relative_path = path.relative_to(repository_root).as_posix() + result = subprocess.run( + ["git", "show", f"{baseline_ref}:{relative_path}"], + cwd=repository_root, + check=False, + capture_output=True, + ) + if result.returncode == 0: + return result.stdout + return None + + +def check_snapshot( + version_directory: Path = DEFAULT_VERSION_DIRECTORY, + *, + baseline_ref: str | None = None, + repository_root: Path = ROOT, +) -> None: + """Verify digest, compatibility, and exact deterministic server equality.""" + + snapshot_path = version_directory / "openapi.json" + digest_path = version_directory / "openapi.sha256" + accepted_bytes = snapshot_path.read_bytes() + accepted_digest_bytes = digest_path.read_bytes() + accepted_digest = accepted_digest_bytes.decode("ascii") + expected_digest = f"{sha256(accepted_bytes).hexdigest()}\n" + if accepted_digest != expected_digest: + raise SnapshotDrift("accepted OpenAPI checksum does not match the snapshot") + if baseline_ref is not None: + verified_ref = subprocess.run( + ["git", "rev-parse", "--verify", f"{baseline_ref}^{{commit}}"], + cwd=repository_root, + check=False, + capture_output=True, + ) + if verified_ref.returncode != 0: + raise SnapshotDrift("OpenAPI baseline ref is unavailable") + assert_historical_artifacts_unchanged( + current_snapshot=accepted_bytes, + current_digest=accepted_digest_bytes, + historical_snapshot=_historical_file( + baseline_ref, + snapshot_path, + repository_root=repository_root, + ), + historical_digest=_historical_file( + baseline_ref, + digest_path, + repository_root=repository_root, + ), + ) + generated_bytes = render_openapi_snapshot() + accepted = json.loads(accepted_bytes) + candidate = json.loads(generated_bytes) + assert_no_breaking_changes(accepted, candidate) + if generated_bytes != accepted_bytes: + raise SnapshotDrift( + "generated OpenAPI drifted; create a reviewed version instead of " + "mutating v0" + ) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=("check", "generate")) + parser.add_argument( + "--version-directory", + type=Path, + default=DEFAULT_VERSION_DIRECTORY, + ) + parser.add_argument("--baseline-ref") + arguments = parser.parse_args() + if arguments.command == "generate": + write_new_snapshot(arguments.version_directory) + else: + check_snapshot( + arguments.version_directory, + baseline_ref=arguments.baseline_ref, + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/validate_security_catalog.py b/scripts/validate_security_catalog.py index 901fb109..b61b7119 100644 --- a/scripts/validate_security_catalog.py +++ b/scripts/validate_security_catalog.py @@ -254,7 +254,8 @@ "decisionRef", "policySnapshotRef", "policyEpoch", - "sourceDecisionRef", + "sourceAclEvidence", + "citationOpenRef", ) TRANSPORT_CASE_IDS: tuple[str, ...] = ( @@ -1027,7 +1028,7 @@ ], "deferredEvidence": [ "group AudienceSnapshot DeliveryEvidenceRef", - "frozen OpenAPI and generated TypeScript SDK carrier", + "generated TypeScript SDK carrier", "production BotDelivery caller", ], "futureCarriers": [ @@ -1042,7 +1043,6 @@ "production ModelGateway", "ActionPlane", "BotDelivery application", - "OpenAPI compatibility freeze", "generated SDK", ], } @@ -1051,8 +1051,7 @@ "issueRef": "#65", "invariantRef": "EGRESS-011", "carrier": ( - "opaque one-shot model or channel EgressGrant with deterministic " - "boundary spies" + "opaque one-shot model or channel EgressGrant with deterministic boundary spies" ), "status": "active_fail_closed", "policyEpochScope": "organization-v0", @@ -1128,6 +1127,102 @@ ], } +CANONICAL_OPENAPI_V0_ACTIVATION: dict[str, object] = { + "issueRef": "#66", + "invariantRef": "TRANSPORT-UNTRUSTED-008", + "carrier": "frozen public POST /v0/resolve OpenAPI contract", + "status": "active_fail_closed", + "policyEpochScope": "organization-v0", + "controlBoundary": ( + "authenticated HTTP metadata -> closed ResolveWire -> current UserActor " + "and active release observation -> sealed ContextRuntime.resolve -> " + "closed ResolutionOutcome" + ), + "testEvidence": [ + { + "id": "OPENAPI-CONTRACT-066", + "surface": "tests/unit/test_openapi_v0_contract.py", + "oracle": ( + "The frozen document exposes exactly one public versioned " + "operation with a closed Acquire, Continue, or OpenCitation body, " + "closed outcome union, complete ContextPackage, bounded metadata " + "and payloads, generic failure statuses, and no raw trusted " + "identity or audience fields." + ), + }, + { + "id": "OPENAPI-BREAKING-066", + "surface": "tests/unit/test_openapi_v0_snapshot.py", + "oracle": ( + "The deterministic immutable snapshot and SHA-256 checksum gate " + "reject current drift, base-commit mutation, and overwrite, while " + "deliberate security, response, union, required-field, and type " + "mutations prove the recursive gate rejects contract changes." + ), + }, + { + "id": "HTTP-V0-066", + "surface": ( + "tests/unit/test_http_trust_boundary.py::" + "test_trusted_field_injection_is_closed_before_domain_execution " + "tests/unit/test_http_unavailable_capabilities.py::" + "test_accept_005_continue_is_generic_non_retryable_and_zero_io " + "tests/process/test_processes.py::" + "test_http_acquire_smoke_returns_the_empty_package_contract" + ), + "oracle": ( + "Public v0 rejects trusted-field injection and returns generic " + "inactive-carrier outcomes before content work, while the process " + "returns the frozen empty-package contract; a separate focused " + "test proves the hidden v1 bridge shares the same sealed path." + ), + }, + { + "id": "PG-RUNTIME-RELEASE-066", + "surface": ( + "tests/integration/test_runtime_empty_package_integration.py::" + "test_seeded_existing_organization_reaches_http_empty_package " + "tests/integration/test_runtime_empty_package_integration.py::" + "test_public_v0_resolve_without_supported_active_release_" + "fails_before_content " + "tests/integration/test_runtime_authorized_evidence_integration.py::" + "test_real_postgres_http_delivers_only_exact_authorized_evidence_" + "bidirectionally" + ), + "oracle": ( + "Real PostgreSQL proves the Package carries the exact Learning-" + "promoted active manifest, tokenizer, and package schema observed " + "under the current UserActor transaction with read-only Runtime " + "RLS, while a missing or unsupported release returns one generic " + "unavailable outcome before content I/O and without a ContextRun; " + "the public v0 seam also proves CandidateRef through the sealed " + "Kernel to exact AuthorizedProjection with real PostgreSQL." + ), + }, + ], + "deferredEvidence": [ + "generated TypeScript SDK conformance", + "production BotDelivery generated-SDK caller", + "Continue and OpenCitation redemption", + ], + "futureCarriers": [ + "generated TypeScript SDK", + "MCP", + "BotDelivery application", + "Continue redemption", + "OpenCitation redemption", + ], + "notActive": [ + "generated SDK consumer", + "MCP", + "BotDelivery application process", + "continuation issuance or redemption", + "citation persistence or redemption", + "group AudienceSnapshot", + "external effects", + ], +} + CANONICAL_ACTIVATIONS: list[dict[str, object]] = [ CANONICAL_REVOCATION_ACTIVATION, CANONICAL_UNAVAILABLE_CAPABILITY_ACTIVATION, @@ -1137,6 +1232,7 @@ CANONICAL_FIELD_PROJECTION_ACTIVATION, CANONICAL_PRIVATE_DELIVERY_EVIDENCE_ACTIVATION, CANONICAL_EGRESS_GRANT_ACTIVATION, + CANONICAL_OPENAPI_V0_ACTIVATION, ] CANONICAL_ACTIVATION_ISSUE_LIST = ", ".join( f"Issue {activation['issueRef']}" for activation in CANONICAL_ACTIVATIONS @@ -2237,8 +2333,10 @@ def _validate_fixture( else None ) canonical_allowlist = ( - "body.package.organizationRef", + "body.package.packageId", "body.package.decisionRef", + "body.package.policySnapshotRef", + "body.package.runRef", "body.package.asOf", "body.package.expiresAt", "body.package.packageDigest", @@ -2318,28 +2416,37 @@ def _validate_fixture( "must preserve the canonical non-enumerating response headers", ) canonical_empty_package = { - "organizationRef": ("orgpkg_0000000000000000000000000000000a"), + "packageId": ("pkg_0000000000000000000000000000000a"), + "packageDigest": ( + "94d68444d124f453eb6c62e0132ea8e90a3c4017230e8e7b3bfe138d1daa10d1" + ), "purpose": "context.answer", - "ttlSeconds": 30, + "audienceDigest": "a" * 64, + "policyEpoch": 1, + "policySnapshotRef": "policy-snapshot-a", + "decisionRef": "dec_0000000000000000000000000000000a", + "runRef": "run-authorized-a", + "releaseManifestRef": "manifest-m0-empty-v0", + "retentionPolicyRef": "package-digest-only-retention-v1", "asOf": "2026-07-21T09:30:00Z", "expiresAt": "2026-07-21T09:30:30Z", - "decisionRef": "dec_0000000000000000000000000000000a", - "packageDigest": ( - "27f6a284027ab9446aa577125727b33263f24c8f252b8cd4616bd17b8545185e" - ), + "ttlSeconds": 30, + "tokenizerRef": "utf8-byte-budget-v1", + "packageSchemaRef": "context-package-openapi-v0", "blocks": [], "evidence": [], "gaps": [], + "coverage": { + "status": "empty", + "reason": "no_authorized_evidence", + }, "budgetUsage": { "tokens": 0, "providerCalls": 0, "costMicrounits": 0, "elapsedMs": 0, }, - "coverage": { - "status": "empty", - "reason": "no_authorized_evidence", - }, + "continuation": None, } observed_package = ( response_body.get("package") if response_body is not None else None @@ -3136,6 +3243,17 @@ def validate_catalog( _validate_schema(schema, catalog.get("catalogVersion"), collector) if isinstance(schema, Mapping): _validate_schema_instance(catalog, schema, schema, "catalog", collector) + definitions = schema.get("$defs") + if isinstance(definitions, Mapping): + activation_schema = definitions.get("activation") + for index, activation in enumerate(CANONICAL_ACTIVATIONS): + _validate_schema_instance( + activation, + activation_schema, + schema, + f"schema canonical activation[{index}]", + collector, + ) if collector.errors: raise CatalogValidationError(collector.errors) diff --git a/tests/catalog/test_validate_security_catalog.py b/tests/catalog/test_validate_security_catalog.py index 50b4294b..8ef91d66 100644 --- a/tests/catalog/test_validate_security_catalog.py +++ b/tests/catalog/test_validate_security_catalog.py @@ -22,11 +22,13 @@ ACL_PROOF_CASE_IDS, AUDIENCE_ACTION_CASE_IDS, CANONICAL_ACTIVATION_ISSUE_LIST, + CANONICAL_ACTIVATIONS, CANONICAL_CONTEXT_RUN_ACTIVATION, CANONICAL_EGRESS_GRANT_ACTIVATION, CANONICAL_FAIL_CLOSED_OUTCOMES, CANONICAL_FIELD_PROJECTION_ACTIVATION, CANONICAL_INVARIANT_IDS, + CANONICAL_OPENAPI_V0_ACTIVATION, CANONICAL_PRIVATE_DELIVERY_EVIDENCE_ACTIVATION, CANONICAL_REVOCATION_ACTIVATION, CANONICAL_TICKET_AUDIENCE_ACTIVATION, @@ -129,6 +131,33 @@ def object_list_at(mapping: dict[str, object], *keys: str) -> list[dict[str, obj return cast(list[dict[str, object]], current) +def test_active_evidence_surfaces_reference_existing_test_nodes() -> None: + """Canonical active evidence cannot drift to a renamed or deleted test.""" + + for activation in CANONICAL_ACTIVATIONS: + test_evidence = activation["testEvidence"] + assert isinstance(test_evidence, list) + for evidence in test_evidence: + assert isinstance(evidence, dict) + surface = evidence["surface"] + assert isinstance(surface, str) + for reference in surface.split(): + file_ref, separator, node_ref = reference.partition("::") + path = Path(__file__).parents[2] / file_ref + assert path.is_file(), reference + if separator: + source = path.read_text(encoding="utf-8") + assert f"def {node_ref}(" in source, reference + + +def test_reusable_schema_accepts_every_canonical_activation_value() -> None: + """Reusable activation definitions cannot lag canonical frozen records.""" + + catalog = load_document(DEFAULT_CATALOG_PATH) + schema = load_document(DEFAULT_SCHEMA_PATH) + validate_catalog(catalog, schema) + + def make_catalog() -> dict[str, object]: invariants = [] for number, invariant_id in enumerate(CANONICAL_INVARIANT_IDS, start=1): @@ -208,12 +237,20 @@ def make_catalog() -> dict[str, object]: "ACCEPT-011", }: package: dict[str, object] = { - "organizationRef": "orgpkg_0000000000000000000000000000000a", + "packageId": "pkg_0000000000000000000000000000000a", "purpose": "context.answer", - "ttlSeconds": 30, + "audienceDigest": "a" * 64, + "policyEpoch": 1, + "policySnapshotRef": "policy-snapshot-a", + "decisionRef": "dec_0000000000000000000000000000000a", + "runRef": "run-authorized-a", + "releaseManifestRef": "manifest-m0-empty-v0", + "retentionPolicyRef": "package-digest-only-retention-v1", "asOf": "2026-07-21T09:30:00Z", "expiresAt": "2026-07-21T09:30:30Z", - "decisionRef": "dec_0000000000000000000000000000000a", + "ttlSeconds": 30, + "tokenizerRef": "utf8-byte-budget-v1", + "packageSchemaRef": "context-package-openapi-v0", "blocks": [], "evidence": [], "gaps": [], @@ -227,6 +264,7 @@ def make_catalog() -> dict[str, object]: "costMicrounits": 0, "elapsedMs": 0, }, + "continuation": None, } body["package"] = package package_or_error["coverageStatus"] = "empty" @@ -259,7 +297,15 @@ def make_catalog() -> dict[str, object]: "decisionRef": "dec_0000000000000000000000000000000a", "policySnapshotRef": "policy-snapshot-a", "policyEpoch": 1, - "sourceDecisionRef": "source-decision-a", + "sourceAclEvidence": { + "kind": "mirrored", + "projectionRef": "source-decision-a", + "aclAsOf": "2026-07-21T09:30:00Z", + "freshnessProfileRef": ( + "file-source-access-current-transaction-v1" + ), + }, + "citationOpenRef": None, } ] package["coverage"] = {"status": "sufficient"} @@ -271,13 +317,13 @@ def make_catalog() -> dict[str, object]: package_or_error["unauthorizedFieldCount"] = 0 package_or_error["unauthorizedEvidenceRefCount"] = 0 package["packageDigest"] = ( - "60891a2328498f53607c4bb67e0e17804c1e91debdbfb2489f67f681573ffcc7" + "9dbfcc7aa6c6a05acd5d61122fc2b8d6a4741794ac2eff59a1bbbaae2e1c616f" ) if fixture_id in {"ACCEPT-005", "ACCEPT-009"}: body["retryable"] = False if fixture_id == "ACCEPT-011": package["packageDigest"] = ( - "27f6a284027ab9446aa577125727b33263f24c8f252b8cd4616bd17b8545185e" + "94d68444d124f453eb6c62e0132ea8e90a3c4017230e8e7b3bfe138d1daa10d1" ) external_response["headers"] = { "Content-Type": "application/json", @@ -293,8 +339,10 @@ def make_catalog() -> dict[str, object]: "domainOutcome", ] operation["normalizationAllowlist"] = [ - "body.package.organizationRef", + "body.package.packageId", "body.package.decisionRef", + "body.package.policySnapshotRef", + "body.package.runRef", "body.package.asOf", "body.package.expiresAt", "body.package.packageDigest", @@ -516,6 +564,7 @@ def make_catalog() -> dict[str, object]: copy.deepcopy(CANONICAL_FIELD_PROJECTION_ACTIVATION), copy.deepcopy(CANONICAL_PRIVATE_DELIVERY_EVIDENCE_ACTIVATION), copy.deepcopy(CANONICAL_EGRESS_GRANT_ACTIVATION), + copy.deepcopy(CANONICAL_OPENAPI_V0_ACTIVATION), ], "invariants": invariants, "fixtures": fixtures, @@ -586,8 +635,8 @@ def make_schema() -> dict[str, object]: }, "activations": { "type": "array", - "minItems": 8, - "maxItems": 8, + "minItems": 9, + "maxItems": 9, "uniqueItems": True, "prefixItems": [ {"const": copy.deepcopy(CANONICAL_REVOCATION_ACTIVATION)}, @@ -606,6 +655,7 @@ def make_schema() -> dict[str, object]: ) }, {"const": copy.deepcopy(CANONICAL_EGRESS_GRANT_ACTIVATION)}, + {"const": copy.deepcopy(CANONICAL_OPENAPI_V0_ACTIVATION)}, ], "items": False, }, @@ -1071,9 +1121,7 @@ def test_issue_48_accept_002_field_projection_activation_is_frozen(self) -> None self.assertEqual(activation, CANONICAL_FIELD_PROJECTION_ACTIVATION) self.assertEqual(activation["invariantRef"], "SCOPE-INTERSECTION-004") self.assertEqual(activation["policyEpochScope"], "organization-v0") - canonical_test_evidence = CANONICAL_FIELD_PROJECTION_ACTIVATION[ - "testEvidence" - ] + canonical_test_evidence = CANONICAL_FIELD_PROJECTION_ACTIVATION["testEvidence"] assert isinstance(canonical_test_evidence, list) assert all(isinstance(evidence, dict) for evidence in canonical_test_evidence) self.assertEqual( @@ -1428,6 +1476,16 @@ def test_schema_must_freeze_nested_shapes_and_canonical_ids(self) -> None: error.errors, ) + def test_malformed_schema_definitions_fail_with_catalog_error(self) -> None: + schema = load_document(DEFAULT_SCHEMA_PATH) + schema["$defs"] = "not-an-object" + + self.assert_catalog_error( + load_document(DEFAULT_CATALOG_PATH), + "schema.$defs: must be an object", + schema, + ) + def test_schema_hard_oracle_tuple_is_closed(self) -> None: schema = make_schema() hard_oracle_schema = object_at(schema, "properties", "hardOracles") @@ -1662,8 +1720,8 @@ def test_tracked_catalog_freezes_issue_19_authority_and_bounded_scope( self.assertEqual(catalog["catalogVersion"], "1.3.0") self.assertEqual( - issue_refs[-8:], - ["#15", "#16", "#17", "#18", "#19", "#48", "#63", "#65"], + issue_refs[-9:], + ["#15", "#16", "#17", "#18", "#19", "#48", "#63", "#65", "#66"], ) self.assertIn( "docs/decisions/0031-persist-authorized-context-run-lineage.md", @@ -1779,7 +1837,7 @@ def test_tracked_catalog_activates_issue_13_authorized_evidence_carriers( self.assertEqual(accept_011_package["blocks"], []) self.assertEqual(accept_011_package["evidence"], []) - def test_exact_package_examples_are_executable_v2_public_documents(self) -> None: + def test_exact_package_examples_are_executable_v3_public_documents(self) -> None: catalog = load_document(DEFAULT_CATALOG_PATH) fixtures = { fixture["id"]: fixture for fixture in object_list_at(catalog, "fixtures") @@ -1800,8 +1858,13 @@ def test_exact_package_examples_are_executable_v2_public_documents(self) -> None "package", ) public_package = ContextPackageWire.model_validate(package) + observed_package = public_package.model_dump( + mode="json", exclude_none=False + ) + if observed_package["coverage"].get("reason") is None: + del observed_package["coverage"]["reason"] self.assertEqual( - public_package.model_dump(mode="json", exclude_none=True), + observed_package, package, ) @@ -1885,7 +1948,7 @@ def test_issue_13_evidence_rank_lineage_and_reference_mutations_fail( evidence["authorizationAsOf"] = "2026-07-21T09:31:00Z" evidence["decisionRef"] = "dec_0000000000000000000000000000000b" evidence["projectedFields"] = ["private_note"] - del evidence["sourceDecisionRef"] + del evidence["sourceAclEvidence"] object_at(accept_006, "expected", "packageOrError")[ "unauthorizedEvidenceRefCount" ] = 1 @@ -2092,8 +2155,10 @@ def test_tracked_catalog_matches_runtime_outcome_and_timing_authority( self.assertEqual( accept_011["operation"]["normalizationAllowlist"], [ - "body.package.organizationRef", + "body.package.packageId", "body.package.decisionRef", + "body.package.policySnapshotRef", + "body.package.runRef", "body.package.asOf", "body.package.expiresAt", "body.package.packageDigest", diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index f5f60d95..e45af8c1 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -20,11 +20,20 @@ ) from engine.persistence.role_guard import assert_learning_role from engine.runtime.package_digest import QueryDigestKeyring +from tests.support.releases import clear_all_test_runtime_releases ROOT = Path(__file__).parents[2] TEST_QUERY_DIGEST_KEY = b"issue-19-query-digest-test-key!!" +@pytest.fixture(autouse=True) +def clear_openapi_v0_test_release_after_each_test() -> Iterator[None]: + """Keep test-only v0 Runtime history from polluting migration boundaries.""" + + yield + clear_all_test_runtime_releases() + + @pytest.fixture(scope="session") def database_configurations() -> HarnessDatabaseConfigurations: """Load the role-isolated URLs; missing harness state is a hard failure.""" diff --git a/tests/integration/test_file_import_tracer.py b/tests/integration/test_file_import_tracer.py index 42250e59..fccd4c2b 100644 --- a/tests/integration/test_file_import_tracer.py +++ b/tests/integration/test_file_import_tracer.py @@ -98,6 +98,10 @@ ) from tests.support.context_run_operator import exact_test_context_run_operator_read from tests.support.file_source_progress import clear_file_source_progress_projection +from tests.support.releases import ( + clear_test_runtime_release, + ensure_test_runtime_release, +) pytestmark = pytest.mark.integration NOW = datetime.now(UTC).replace(microsecond=0) @@ -865,6 +869,8 @@ def test_registered_file_import_publishes_one_exact_authorized_http_package( }, ) + ensure_test_runtime_release(other_organization_id) + authority = ControlOperatorAuthority( _ControlAuthenticator(organization_id), call_ttl=timedelta(minutes=5), @@ -1019,6 +1025,10 @@ def test_registered_file_import_publishes_one_exact_authorized_http_package( prepared.source_ref, ) ) + ensure_test_runtime_release( + organization_id, + active_revision_refs=(published.candidate_ref.revision_ref,), + ) runtime = Runtime( required_kernel_dependencies(), @@ -1111,9 +1121,7 @@ def test_registered_file_import_publishes_one_exact_authorized_http_package( private_delivery=True, ), organization_authority=_OrganizationAuthority(), - membership_authority=PostgreSQLMembershipAuthority( - guarded_runtime_engine - ), + membership_authority=PostgreSQLMembershipAuthority(guarded_runtime_engine), scope_authority=_ExactScopeAuthority( published.candidate_ref.source_ref, published.candidate_ref.resource_ref, @@ -1440,6 +1448,10 @@ def _assert_structural_file_import_returns_coherent_authorized_units_over_http( "structure-table", ) ) + ensure_test_runtime_release( + scenario.organization_id, + active_revision_refs=(published.candidate_ref.revision_ref,), + ) client = TestClient( create_app( authenticator=_RuntimeAuthenticator( @@ -1549,6 +1561,16 @@ def _assert_structural_file_import_returns_coherent_authorized_units_over_http( assert "Handbook" not in denied.text assert "red-rocket" not in denied.text + with migration_engine.begin() as connection: + connection.execute( + text("DELETE FROM decision_audit WHERE organization_id = :organization_id"), + {"organization_id": scenario.organization_id}, + ) + connection.execute( + text("DELETE FROM context_run WHERE organization_id = :organization_id"), + {"organization_id": scenario.organization_id}, + ) + clear_test_runtime_release(scenario.organization_id) clear_file_source_progress_projection(migration_configuration) with pytest.raises( RuntimeError, @@ -1560,7 +1582,7 @@ def _assert_structural_file_import_returns_coherent_authorized_units_over_http( connection.execute( text("SELECT version_num FROM alembic_version") ).scalar_one() - == "20260723_0020" + == "20260723_0021" ) diff --git a/tests/integration/test_membership_field_projection_integration.py b/tests/integration/test_membership_field_projection_integration.py index fc81954d..a07df96a 100644 --- a/tests/integration/test_membership_field_projection_integration.py +++ b/tests/integration/test_membership_field_projection_integration.py @@ -54,6 +54,10 @@ _open_scope_authority_scope, ) from tests.support.context_run_operator import exact_test_context_run_operator_read +from tests.support.releases import ( + clear_test_runtime_release, + ensure_test_runtime_release, +) from tests.support.security_gate import record_security_oracles pytestmark = pytest.mark.integration @@ -374,6 +378,7 @@ def _seed_fixture(engine: Engine, fixture: FieldProjectionFixture) -> None: def _cleanup_fixture(engine: Engine, fixture: FieldProjectionFixture) -> None: + clear_test_runtime_release(fixture.organization_id) parameters = { "organization_id": fixture.organization_id, "full_user_id": fixture.full.user_id, @@ -574,6 +579,7 @@ def test_accept_002_same_organization_memberships_receive_only_authorized_fields try: _seed_fixture(migration_engine, fixture) + ensure_test_runtime_release(fixture.organization_id) full_response = _resolve( client, @@ -838,6 +844,7 @@ def revoke_private_note() -> None: try: _seed_fixture(migration_engine, fixture) + ensure_test_runtime_release(fixture.organization_id) with ThreadPoolExecutor(max_workers=2) as executor: pending_response = executor.submit( _resolve, diff --git a/tests/integration/test_migrations.py b/tests/integration/test_migrations.py index f125b51c..4354f12c 100644 --- a/tests/integration/test_migrations.py +++ b/tests/integration/test_migrations.py @@ -43,7 +43,7 @@ pytestmark = pytest.mark.integration ROOT = Path(__file__).parents[2] -_HEAD_REVISION = "20260723_0020" +_HEAD_REVISION = "20260723_0021" HEAD_TABLES = [ "active_release_manifest", "alembic_version", @@ -1333,6 +1333,84 @@ def test_empty_content_downgrade_preserves_v2_context_run_history( engine.dispose() +def test_openapi_v0_revision_refuses_downgrade_with_v3_context_run_history( + migration_configuration: DatabaseConfiguration, +) -> None: + """The v0 digest profile cannot be made invalid by a schema rollback.""" + + alembic_configuration = Config(ROOT / "alembic.ini") + identity = LineageIdentity( + organization_id=uuid4(), + user_id=uuid4(), + membership_id=uuid4(), + run_ref="run_" + "b" * 32, + decision_ref="dec_" + "c" * 32, + ) + engine = create_database_engine(migration_configuration) + try: + with engine.begin() as connection: + connection.execute( + text("INSERT INTO organization (organization_id) VALUES (:org)"), + {"org": identity.organization_id}, + ) + connection.execute( + text("INSERT INTO user_account (user_id) VALUES (:user_id)"), + {"user_id": identity.user_id}, + ) + connection.execute( + text( + """ + INSERT INTO membership ( + organization_id, membership_id, user_id, status, + membership_version, valid_from + ) VALUES ( + :org, :membership_id, :user_id, 'active', 1, + statement_timestamp() - interval '1 day' + ) + """ + ), + { + "org": identity.organization_id, + "membership_id": identity.membership_id, + "user_id": identity.user_id, + }, + ) + insert_context_run(connection, identity) + connection.execute( + text( + "UPDATE context_run SET package_digest_profile = " + "'context-package-canonical-json-v3' " + "WHERE organization_id = :org" + ), + {"org": identity.organization_id}, + ) + + with pytest.raises(SQLAlchemyError, match="v3 ContextRun lineage exists"): + command.downgrade(alembic_configuration, "20260723_0020") + assert _revision_rows(migration_configuration) == [_HEAD_REVISION] + finally: + if _revision_rows(migration_configuration) != [_HEAD_REVISION]: + command.upgrade(alembic_configuration, "head") + with engine.begin() as connection: + connection.execute( + text("DELETE FROM context_run WHERE organization_id = :org"), + {"org": identity.organization_id}, + ) + connection.execute( + text("DELETE FROM membership WHERE organization_id = :org"), + {"org": identity.organization_id}, + ) + connection.execute( + text("DELETE FROM user_account WHERE user_id = :user_id"), + {"user_id": identity.user_id}, + ) + connection.execute( + text("DELETE FROM organization WHERE organization_id = :org"), + {"org": identity.organization_id}, + ) + engine.dispose() + + def test_field_projection_downgrade_refuses_populated_content_atomically( migration_configuration: DatabaseConfiguration, ) -> None: diff --git a/tests/integration/test_runtime_authorized_evidence_integration.py b/tests/integration/test_runtime_authorized_evidence_integration.py index b014976b..9e4da4cc 100644 --- a/tests/integration/test_runtime_authorized_evidence_integration.py +++ b/tests/integration/test_runtime_authorized_evidence_integration.py @@ -44,6 +44,10 @@ _open_scope_authority_scope, ) from tests.support.context_run_operator import exact_test_context_run_operator_read +from tests.support.releases import ( + clear_test_runtime_release, + ensure_test_runtime_release, +) from tests.support.security_gate import record_security_oracles pytestmark = pytest.mark.integration @@ -495,6 +499,8 @@ def _persistent_content_snapshot( def _cleanup_fixture(engine: Engine, fixture: RuntimeEvidenceFixture) -> None: + clear_test_runtime_release(fixture.org_a.organization_id) + clear_test_runtime_release(fixture.org_b.organization_id) organizations = { "org_a_id": fixture.org_a.organization_id, "org_b_id": fixture.org_b.organization_id, @@ -697,8 +703,11 @@ def _assert_exact_authorized_http_resolve( ) response = client.post( - "/v1/context:resolve", - headers={"Authorization": f"Bearer {token}"}, + "/v0/resolve", + headers={ + "Authorization": f"Bearer {token}", + "X-Context-Request-Id": request_id, + }, json={"kind": "acquire", "need": {"query": "hostile rank"}}, ) @@ -757,10 +766,11 @@ def _assert_exact_authorized_http_resolve( package_digest = package_document.pop("packageDigest") assert verify_context_package_digest(package_document, package_digest) assert "effects" not in package - assert package["organizationRef"] not in { - str(active.organization_id), - str(other.organization_id), - } + assert "organizationRef" not in package + assert package["packageId"].startswith("pkg_") + assert len(package["packageId"]) == 36 + assert str(active.organization_id) not in response.text + assert str(other.organization_id) not in response.text assert package["purpose"] == "context.answer" assert package["asOf"] == RECEIVED_AT.isoformat().replace("+00:00", "Z") assert package["gaps"] == [] @@ -805,15 +815,22 @@ def _assert_exact_authorized_http_resolve( "decisionRef": package["decisionRef"], "policySnapshotRef": evidence["policySnapshotRef"], "policyEpoch": 1, - "sourceDecisionRef": evidence["sourceDecisionRef"], + "sourceAclEvidence": evidence["sourceAclEvidence"], + "citationOpenRef": None, } for lineage_ref in ( evidence["runRef"], evidence["policySnapshotRef"], - evidence["sourceDecisionRef"], + evidence["sourceAclEvidence"]["projectionRef"], ): assert isinstance(lineage_ref, str) assert lineage_ref + assert evidence["sourceAclEvidence"] == { + "kind": "mirrored", + "projectionRef": evidence["sourceAclEvidence"]["projectionRef"], + "aclAsOf": package["asOf"], + "freshnessProfileRef": "file-source-access-current-transaction-v1", + } response_text = response.text forbidden_values = ( @@ -861,6 +878,8 @@ def test_real_postgres_http_delivers_only_exact_authorized_evidence_bidirectiona migration_engine = create_database_engine(migration_configuration) try: _seed_fixture(migration_engine, fixture) + ensure_test_runtime_release(fixture.org_a.organization_id) + ensure_test_runtime_release(fixture.org_b.organization_id) before = _persistent_content_snapshot(migration_engine, fixture) assert len(before) == 4 diff --git a/tests/integration/test_runtime_empty_package_integration.py b/tests/integration/test_runtime_empty_package_integration.py index 49aefd46..3b50eeab 100644 --- a/tests/integration/test_runtime_empty_package_integration.py +++ b/tests/integration/test_runtime_empty_package_integration.py @@ -46,6 +46,10 @@ verify_context_package_digest, ) from tests.support.context_run_operator import exact_test_context_run_operator_read +from tests.support.releases import ( + clear_test_runtime_release, + ensure_test_runtime_release, +) pytestmark = pytest.mark.integration TOKEN = "seeded-existing-organization" @@ -198,6 +202,7 @@ def test_seeded_existing_organization_reaches_http_empty_package( }, ) assert cast(UUID, inserted) == organization_id + active_release = ensure_test_runtime_release(organization_id) spy = ContentIoSpy() runtime = Runtime( @@ -227,14 +232,22 @@ def test_seeded_existing_organization_reaches_http_empty_package( ) response = client.post( - "/v1/context:resolve", - headers={"Authorization": f"Bearer {TOKEN}"}, + "/v0/resolve", + headers={ + "Authorization": f"Bearer {TOKEN}", + "X-Context-Request-Id": "public-v0-real-pg-root", + }, json={"kind": "acquire", "need": {"query": "real PG root"}}, ) assert response.status_code == 200 package = response.json()["package"] - assert package["organizationRef"] != str(organization_id) + assert package["packageId"].startswith("pkg_") + assert str(organization_id) not in response.text + assert organization_id.hex not in response.text + assert package["releaseManifestRef"] == active_release.manifest_ref + assert package["tokenizerRef"] == active_release.tokenizer_ref + assert package["packageSchemaRef"] == active_release.package_schema_ref assert package["blocks"] == package["evidence"] == package["gaps"] == [] assert package["coverage"] == { "status": "empty", @@ -400,6 +413,7 @@ def test_seeded_existing_organization_reaches_http_empty_package( {"setting_name": setting_name}, ).scalar_one_or_none() in {None, ""} finally: + clear_test_runtime_release(organization_id) with migration_engine.begin() as connection: connection.execute( text( @@ -440,6 +454,163 @@ def test_seeded_existing_organization_reaches_http_empty_package( migration_engine.dispose() +@pytest.mark.parametrize("release_state", ("missing", "unsupported_profile")) +def test_public_v0_resolve_without_supported_active_release_fails_before_content( + migration_configuration: DatabaseConfiguration, + guarded_runtime_engine: Engine, + query_digest_keyring: QueryDigestKeyring, + release_state: str, +) -> None: + """A current UserActor cannot receive a Package from absent/unknown lineage.""" + + organization_id = uuid4() + user_id = uuid4() + membership_id = uuid4() + migration_engine = create_database_engine(migration_configuration) + try: + with migration_engine.begin() as connection: + connection.execute( + text("INSERT INTO organization (organization_id) VALUES (:org)"), + {"org": organization_id}, + ) + connection.execute( + text("INSERT INTO user_account (user_id) VALUES (:user_id)"), + {"user_id": user_id}, + ) + connection.execute( + text( + """ + INSERT INTO membership ( + organization_id, membership_id, user_id, status, + membership_version, valid_from + ) VALUES ( + :org, :membership_id, :user_id, 'active', 1, :valid_from + ) + """ + ), + { + "org": organization_id, + "membership_id": membership_id, + "user_id": user_id, + "valid_from": RECEIVED_AT - timedelta(days=1), + }, + ) + if release_state == "unsupported_profile": + with pytest.raises(ValueError, match="unsupported Runtime profile"): + ensure_test_runtime_release( + organization_id, + runtime_profile_ref="runtime-unsupported-integration-test", + ) + + spy = ContentIoSpy() + response = TestClient( + create_app( + authenticator=SeededAuthenticator( + organization_id, + user_id, + membership_id, + ), + organization_authority=SeededOrganizationAuthority(organization_id), + membership_authority=PostgreSQLMembershipAuthority( + guarded_runtime_engine + ), + runtime=Runtime( + required_kernel_dependencies(), + content_io=RuntimeContentIo( + index=spy, + provider=spy, + source_content=spy, + ), + clock=lambda: RECEIVED_AT, + query_digest_keyring=query_digest_keyring, + ), + clock=lambda: RECEIVED_AT, + ) + ).post( + "/v0/resolve", + headers={ + "Authorization": f"Bearer {TOKEN}", + "X-Context-Request-Id": "public-v0-missing-release", + }, + json={"kind": "acquire", "need": {"query": "no active release"}}, + ) + + assert response.status_code == 503 + assert response.content == b'{"code":"service_unavailable"}' + assert spy.calls == 0 + with migration_engine.connect() as connection: + assert ( + connection.execute( + text( + "SELECT count(*) FROM context_run WHERE organization_id = :org" + ), + {"org": organization_id}, + ).scalar_one() + == 0 + ) + finally: + clear_test_runtime_release(organization_id) + with migration_engine.begin() as connection: + connection.execute( + text("DELETE FROM membership WHERE organization_id = :org"), + {"org": organization_id}, + ) + connection.execute( + text("DELETE FROM user_account WHERE user_id = :user_id"), + {"user_id": user_id}, + ) + connection.execute( + text("DELETE FROM organization WHERE organization_id = :org"), + {"org": organization_id}, + ) + migration_engine.dispose() + + +def test_runtime_release_rls_rejects_arbitrary_organization_guc_without_user_actor( + migration_configuration: DatabaseConfiguration, + guarded_runtime_engine: Engine, +) -> None: + """Runtime credentials alone cannot enumerate another Organization release.""" + + organization_id = uuid4() + migration_engine = create_database_engine(migration_configuration) + try: + with migration_engine.begin() as connection: + connection.execute( + text("INSERT INTO organization (organization_id) VALUES (:org)"), + {"org": organization_id}, + ) + ensure_test_runtime_release(organization_id) + + with guarded_runtime_engine.begin() as connection: + connection.execute( + text("SELECT set_config('app.organization_id', :org, true)"), + {"org": str(organization_id)}, + ) + observed = { + table_name: connection.execute( + text(f"SELECT count(*) FROM {table_name}") + ).scalar_one() + for table_name in ( + "active_release_manifest", + "release_manifest", + ) + } + + assert observed == { + "active_release_manifest": 0, + "release_manifest": 0, + } + finally: + clear_test_runtime_release(organization_id) + with migration_engine.begin() as connection: + connection.execute( + text("DELETE FROM organization WHERE organization_id = :org"), + {"org": organization_id}, + ) + migration_engine.dispose() + + @pytest.mark.security_evidence(id="RUNTIME-RLS-FAIL-CLOSED-003", layer="runtime") def test_real_postgres_http_membership_matrix_is_generic_and_zero_io( migration_configuration: DatabaseConfiguration, @@ -544,6 +715,8 @@ def test_real_postgres_http_membership_matrix_is_generic_and_zero_io( ], ) + ensure_test_runtime_release(organization_a) + spy = ContentIoSpy() runtime = Runtime( required_kernel_dependencies(), @@ -579,8 +752,11 @@ def test_real_postgres_http_membership_matrix_is_generic_and_zero_io( ) ) response = client.post( - "/v1/context:resolve", - headers={"Authorization": f"Bearer {TOKEN}"}, + "/v0/resolve", + headers={ + "Authorization": f"Bearer {TOKEN}", + "X-Context-Request-Id": f"public-v0-membership-{category}", + }, json={"kind": "acquire", "need": {"query": category}}, ) responses[category] = (response.status_code, response.content) @@ -607,6 +783,7 @@ def test_real_postgres_http_membership_matrix_is_generic_and_zero_io( {"setting_name": setting_name}, ).scalar_one_or_none() in {None, ""} finally: + clear_test_runtime_release(organization_a) with migration_engine.begin() as connection: connection.execute( text( diff --git a/tests/integration/test_runtime_non_enumeration_integration.py b/tests/integration/test_runtime_non_enumeration_integration.py index 0a0d297c..4a0d9afd 100644 --- a/tests/integration/test_runtime_non_enumeration_integration.py +++ b/tests/integration/test_runtime_non_enumeration_integration.py @@ -40,6 +40,7 @@ _seed_fixture, ) from tests.support.context_run_operator import exact_test_context_run_operator_read +from tests.support.releases import ensure_test_runtime_release from tests.support.security_gate import record_security_oracles pytestmark = pytest.mark.integration @@ -51,8 +52,10 @@ TOKEN = "non-enumeration-integration-token" NORMALIZATION_ALLOWLIST = ( - "body.package.organizationRef", + "body.package.packageId", "body.package.decisionRef", + "body.package.policySnapshotRef", + "body.package.runRef", "body.package.asOf", "body.package.expiresAt", "body.package.packageDigest", @@ -273,12 +276,19 @@ def _assert_empty_non_enumerating_response( assert response.headers["content-type"] == "application/json" assert response.headers["cache-control"] == "no-store" document = response.json() - assert set(document) == {"kind", "package"} + assert set(document) == {"kind", "package", "egressGrant"} assert document["kind"] == "resolved" + assert document["egressGrant"] is None package = document["package"] assert set(package) == { - "organizationRef", + "packageId", + "audienceDigest", + "policyEpoch", + "policySnapshotRef", + "runRef", + "releaseManifestRef", + "retentionPolicyRef", "purpose", "ttlSeconds", "asOf", @@ -290,6 +300,9 @@ def _assert_empty_non_enumerating_response( "gaps", "budgetUsage", "coverage", + "tokenizerRef", + "packageSchemaRef", + "continuation", } assert package["purpose"] == "context.answer" assert package["blocks"] == [] @@ -343,8 +356,10 @@ def _assert_empty_runtime_outcome(outcome: Resolved) -> None: def _normalized_domain_outcome(outcome: Resolved) -> bytes: document = cast(dict[str, object], asdict(outcome)) package = cast(dict[str, object], document["package"]) - package["organization_ref"] = "" + package["package_id"] = "" package["decision_ref"] = "" + package["policy_snapshot_ref"] = "" + package["run_ref"] = "" package["package_digest"] = "" package["as_of"] = "" package["expires_at"] = "" @@ -440,6 +455,7 @@ def test_real_postgres_http_denied_and_missing_are_externally_equivalent( migration_engine = create_database_engine(migration_configuration) try: _seed_fixture(migration_engine, fixture) + ensure_test_runtime_release(active.organization_id) _assert_non_owner_force_rls(guarded_runtime_engine) responses = tuple( @@ -475,8 +491,10 @@ def test_real_postgres_http_denied_and_missing_are_externally_equivalent( ) assert raw_difference_paths <= set(NORMALIZATION_ALLOWLIST) assert raw_difference_paths == { - "body.package.organizationRef", + "body.package.packageId", "body.package.decisionRef", + "body.package.policySnapshotRef", + "body.package.runRef", "body.package.packageDigest", "headers.X-Context-Request-Id", } diff --git a/tests/integration/test_runtime_policy_epoch_integration.py b/tests/integration/test_runtime_policy_epoch_integration.py index da090452..3b1b67e3 100644 --- a/tests/integration/test_runtime_policy_epoch_integration.py +++ b/tests/integration/test_runtime_policy_epoch_integration.py @@ -36,6 +36,7 @@ _seed_fixture, ) from tests.support.context_run_operator import exact_test_context_run_operator_read +from tests.support.releases import ensure_test_runtime_release pytestmark = pytest.mark.integration QUERY = "same policy epoch revocation probe" @@ -152,6 +153,8 @@ def test_same_http_acquire_revokes_next_delivery_without_candidate_cleanup( ) try: _seed_fixture(migration_engine, fixture) + ensure_test_runtime_release(fixture.org_a.organization_id) + ensure_test_runtime_release(fixture.org_b.organization_id) persistent_before = _persistent_content_snapshot(migration_engine, fixture) assert len(persistent_before) == 4 @@ -278,6 +281,7 @@ def synchronized_epoch_read( ) try: _seed_fixture(migration_engine, fixture) + ensure_test_runtime_release(fixture.org_a.organization_id) persistent_before = _persistent_content_snapshot(migration_engine, fixture) with ThreadPoolExecutor(max_workers=1) as executor: diff --git a/tests/integration/test_z_egress_grant_file.py b/tests/integration/test_z_egress_grant_file.py index f45430a9..30435f57 100644 --- a/tests/integration/test_z_egress_grant_file.py +++ b/tests/integration/test_z_egress_grant_file.py @@ -37,6 +37,10 @@ _run_file_import, _RuntimeAuthenticator, ) +from tests.support.releases import ( + clear_test_runtime_release, + ensure_test_runtime_release, +) pytestmark = pytest.mark.integration @@ -77,6 +81,10 @@ def test_file_http_package_redeems_exact_model_grant_before_gateway_bytes( scenario.token, guarded_worker_engine, ) + ensure_test_runtime_release( + scenario.organization_id, + active_revision_refs=(published.candidate_ref.revision_ref,), + ) migration_engine = create_database_engine(migration_configuration) egress_engine = create_database_engine(egress_configuration) try: @@ -168,7 +176,16 @@ def test_file_http_package_redeems_exact_model_grant_before_gateway_bytes( boundary.transmit(authorized, outcome.egress_grant) assert gateway.request_count == 1 finally: + clear_test_runtime_release(scenario.organization_id) with migration_engine.begin() as connection: + connection.execute( + text("DELETE FROM decision_audit WHERE organization_id = :org"), + {"org": scenario.organization_id}, + ) + connection.execute( + text("DELETE FROM context_run WHERE organization_id = :org"), + {"org": scenario.organization_id}, + ) connection.execute( text("DELETE FROM egress_audit WHERE organization_id = :org"), {"org": scenario.organization_id}, diff --git a/tests/integration/test_zz_file_content_noop.py b/tests/integration/test_zz_file_content_noop.py index dad65249..3058f330 100644 --- a/tests/integration/test_zz_file_content_noop.py +++ b/tests/integration/test_zz_file_content_noop.py @@ -39,6 +39,10 @@ _RuntimeAuthenticator, ) from tests.support.file_source_progress import clear_file_source_progress_projection +from tests.support.releases import ( + clear_test_runtime_release, + ensure_test_runtime_release, +) pytestmark = pytest.mark.integration @@ -53,6 +57,7 @@ def _resolve_lineage( resource_ref: str, request_id: str, ) -> tuple[str, str, str, str, str]: + ensure_test_runtime_release(scenario.organization_id) migration_engine = create_database_engine(migration_configuration) try: with migration_engine.connect() as connection: @@ -246,6 +251,22 @@ def test_repeated_canonically_identical_file_import_is_an_auditable_noop( assert job.effect_count == 0 assert job.revision_id == UUID(first.candidate_ref.revision_ref) + with migration_engine.begin() as connection: + connection.execute( + text( + "DELETE FROM decision_audit " + "WHERE organization_id = :organization_id" + ), + {"organization_id": scenario.organization_id}, + ) + connection.execute( + text( + "DELETE FROM context_run " + "WHERE organization_id = :organization_id" + ), + {"organization_id": scenario.organization_id}, + ) + clear_test_runtime_release(scenario.organization_id) clear_file_source_progress_projection(migration_configuration) with pytest.raises( RuntimeError, @@ -257,7 +278,7 @@ def test_repeated_canonically_identical_file_import_is_an_auditable_noop( connection.execute( text("SELECT version_num FROM alembic_version") ).scalar_one() - == "20260723_0020" + == "20260723_0021" ) diff --git a/tests/integration/test_zz_file_resource_tombstone.py b/tests/integration/test_zz_file_resource_tombstone.py index 57532095..4e733d27 100644 --- a/tests/integration/test_zz_file_resource_tombstone.py +++ b/tests/integration/test_zz_file_resource_tombstone.py @@ -182,10 +182,19 @@ def _stable_empty_package(package: dict[str, Any]) -> dict[str, Any]: stable = dict(package) for field in ( "asOf", + "audienceDigest", "decisionRef", "expiresAt", - "organizationRef", "packageDigest", + "packageId", + "packageSchemaRef", + "policyEpoch", + "policySnapshotRef", + "releaseManifestRef", + "retentionPolicyRef", + "runRef", + "tokenizerRef", + "continuation", ): stable.pop(field) return stable diff --git a/tests/integration/test_zz_file_revision_replacement.py b/tests/integration/test_zz_file_revision_replacement.py index b7e5d2f4..6f143e83 100644 --- a/tests/integration/test_zz_file_revision_replacement.py +++ b/tests/integration/test_zz_file_revision_replacement.py @@ -47,6 +47,7 @@ _run_file_import, _RuntimeAuthenticator, ) +from tests.support.releases import ensure_test_runtime_release pytestmark = pytest.mark.integration @@ -55,12 +56,10 @@ OLD_V1_MARKDOWN = b"# Handbook\n\nOLD marker.\n" NEW_V1_MARKDOWN = b"# Handbook\n\nNEW marker.\n" OLD_CONCURRENT_MARKDOWN = ( - b"# Alpha\n\nOLD alpha.\n\nShared query.\n\n" - b"## Beta\n\nOLD beta.\n\nShared query.\n" + b"# Alpha\n\nOLD alpha.\n\nShared query.\n\n## Beta\n\nOLD beta.\n\nShared query.\n" ) NEW_CONCURRENT_MARKDOWN = ( - b"# Alpha\n\nNEW alpha.\n\nShared query.\n\n" - b"## Beta\n\nNEW beta.\n\nShared query.\n" + b"# Alpha\n\nNEW alpha.\n\nShared query.\n\n## Beta\n\nNEW beta.\n\nShared query.\n" ) UNAFFECTED_MARKDOWN = b"# Reference\n\nUNAFFECTED resource marker.\n" @@ -76,6 +75,7 @@ def _resolve( candidate_index: CandidateIndex | None = None, resource_ref: str | None = None, ) -> dict[str, Any]: + ensure_test_runtime_release(scenario.organization_id) client = TestClient( create_app( authenticator=_RuntimeAuthenticator( @@ -84,9 +84,7 @@ def _resolve( scenario.membership_id, ), organization_authority=_OrganizationAuthority(), - membership_authority=PostgreSQLMembershipAuthority( - guarded_runtime_engine - ), + membership_authority=PostgreSQLMembershipAuthority(guarded_runtime_engine), scope_authority=_ExactScopeAuthority( str(scenario.source_ref.value), resource_ref @@ -825,9 +823,7 @@ def test_ready_replacement_keeps_old_http_package_until_atomic_activation( ) assert supersession.retention_state == "retained_until_explicit_cleanup" assert old_text == OLD_MARKDOWN.decode() - assert activated.active_revision_id == UUID( - second.candidate_ref.revision_ref - ) + assert activated.active_revision_id == UUID(second.candidate_ref.revision_ref) assert (activated.state, activated.effect_count) == ("completed", 1) assert activated.states == ["prepared", "indexed", "active"] finally: @@ -1124,15 +1120,18 @@ def test_replacement_does_not_change_another_organization_resource( engine = create_database_engine(migration_configuration) try: with engine.connect() as connection: - assert connection.execute( - text( - """ + assert ( + connection.execute( + text( + """ SELECT count(*) FROM file_revision_supersession WHERE organization_id = :organization_id """ - ), - {"organization_id": unaffected.organization_id}, - ).scalar_one() == 0 + ), + {"organization_id": unaffected.organization_id}, + ).scalar_one() + == 0 + ) finally: engine.dispose() @@ -1381,20 +1380,26 @@ def test_replacement_stage_rejects_wrong_exact_bindings_with_zero_effect( job_id=prepared.job_id, resource_ref=resource_ref, ) - assert _stage_replacement_direct( - guarded_worker_engine, - claims, - _compile_replacement(replacement_payload, structural=structural), - resource_ref=requested_resource_ref, - revision_id=requested_revision_id, - overrides=overrides, - ) is None - assert _replacement_state( - engine, - scenario, - job_id=prepared.job_id, - resource_ref=resource_ref, - ) == before + assert ( + _stage_replacement_direct( + guarded_worker_engine, + claims, + _compile_replacement(replacement_payload, structural=structural), + resource_ref=requested_resource_ref, + revision_id=requested_revision_id, + overrides=overrides, + ) + is None + ) + assert ( + _replacement_state( + engine, + scenario, + job_id=prepared.job_id, + resource_ref=resource_ref, + ) + == before + ) finally: engine.dispose() @@ -1481,9 +1486,7 @@ def test_replacement_activation_rejects_wrong_exact_bindings_with_zero_effect( elif wrong_binding == "previous_revision": requested_previous_revision_id = UUID(int=previous_revision_id.int ^ 1) elif wrong_binding == "replacement_revision": - requested_replacement_revision_id = UUID( - int=replacement_revision_id.int ^ 1 - ) + requested_replacement_revision_id = UUID(int=replacement_revision_id.int ^ 1) elif wrong_binding == "nonce": overrides["nonce"] = bytes([claims.nonce[0] ^ 1]) + claims.nonce[1:] else: @@ -1497,20 +1500,26 @@ def test_replacement_activation_rejects_wrong_exact_bindings_with_zero_effect( job_id=prepared.job_id, resource_ref=resource_ref, ) - assert _activate_replacement_direct( - guarded_worker_engine, - claims, - resource_ref=requested_resource_ref, - previous_revision_id=requested_previous_revision_id, - replacement_revision_id=requested_replacement_revision_id, - overrides=overrides, - ) is None - assert _replacement_state( - engine, - scenario, - job_id=prepared.job_id, - resource_ref=resource_ref, - ) == before + assert ( + _activate_replacement_direct( + guarded_worker_engine, + claims, + resource_ref=requested_resource_ref, + previous_revision_id=requested_previous_revision_id, + replacement_revision_id=requested_replacement_revision_id, + overrides=overrides, + ) + is None + ) + assert ( + _replacement_state( + engine, + scenario, + job_id=prepared.job_id, + resource_ref=resource_ref, + ) + == before + ) finally: engine.dispose() @@ -1559,13 +1568,16 @@ def test_replacement_activation_rejects_revoked_authority_with_zero_effect( assert _redeem_direct(guarded_worker_engine, claims) is not None resource_ref = first.candidate_ref.resource_ref replacement_revision_id = UUID(int=prepared.job_id.int ^ 1) - assert _stage_replacement_direct( - guarded_worker_engine, - claims, - _compile_replacement(NEW_V1_MARKDOWN, structural=False), - resource_ref=resource_ref, - revision_id=replacement_revision_id, - ) is not None + assert ( + _stage_replacement_direct( + guarded_worker_engine, + claims, + _compile_replacement(NEW_V1_MARKDOWN, structural=False), + resource_ref=resource_ref, + revision_id=replacement_revision_id, + ) + is not None + ) engine = create_database_engine(migration_configuration) try: @@ -1620,19 +1632,25 @@ def test_replacement_activation_rejects_revoked_authority_with_zero_effect( job_id=prepared.job_id, resource_ref=resource_ref, ) - assert _activate_replacement_direct( - guarded_worker_engine, - claims, - resource_ref=resource_ref, - previous_revision_id=UUID(first.candidate_ref.revision_ref), - replacement_revision_id=replacement_revision_id, - ) is None - assert _replacement_state( - engine, - scenario, - job_id=prepared.job_id, - resource_ref=resource_ref, - ) == before + assert ( + _activate_replacement_direct( + guarded_worker_engine, + claims, + resource_ref=resource_ref, + previous_revision_id=UUID(first.candidate_ref.revision_ref), + replacement_revision_id=replacement_revision_id, + ) + is None + ) + assert ( + _replacement_state( + engine, + scenario, + job_id=prepared.job_id, + resource_ref=resource_ref, + ) + == before + ) finally: engine.dispose() @@ -1689,13 +1707,16 @@ def test_replacement_rejects_a_lease_that_expires_at_the_durable_boundary( replacement_revision_id = UUID(int=prepared.job_id.int ^ 1) document = _compile_replacement(replacement_payload, structural=structural) if boundary == "activate": - assert _stage_replacement_direct( - guarded_worker_engine, - claims, - document, - resource_ref=resource_ref, - revision_id=replacement_revision_id, - ) is not None + assert ( + _stage_replacement_direct( + guarded_worker_engine, + claims, + document, + resource_ref=resource_ref, + revision_id=replacement_revision_id, + ) + is not None + ) engine = create_database_engine(migration_configuration) try: @@ -1725,12 +1746,15 @@ def test_replacement_rejects_a_lease_that_expires_at_the_durable_boundary( ) ) assert result is None - assert _replacement_state( - engine, - scenario, - job_id=prepared.job_id, - resource_ref=resource_ref, - ) == before + assert ( + _replacement_state( + engine, + scenario, + job_id=prepared.job_id, + resource_ref=resource_ref, + ) + == before + ) finally: engine.dispose() @@ -1836,19 +1860,25 @@ def test_replacement_stage_rejects_revoked_authority_with_zero_effect( job_id=prepared.job_id, resource_ref=resource_ref, ) - assert _stage_replacement_direct( - guarded_worker_engine, - claims, - _compile_replacement(replacement_payload, structural=structural), - resource_ref=resource_ref, - revision_id=UUID(int=prepared.job_id.int ^ 1), - ) is None - assert _replacement_state( - engine, - scenario, - job_id=prepared.job_id, - resource_ref=resource_ref, - ) == before + assert ( + _stage_replacement_direct( + guarded_worker_engine, + claims, + _compile_replacement(replacement_payload, structural=structural), + resource_ref=resource_ref, + revision_id=UUID(int=prepared.job_id.int ^ 1), + ) + is None + ) + assert ( + _replacement_state( + engine, + scenario, + job_id=prepared.job_id, + resource_ref=resource_ref, + ) + == before + ) finally: engine.dispose() diff --git a/tests/integration/test_zz_file_source_offboarding.py b/tests/integration/test_zz_file_source_offboarding.py index 8bd60881..0eaf29d8 100644 --- a/tests/integration/test_zz_file_source_offboarding.py +++ b/tests/integration/test_zz_file_source_offboarding.py @@ -288,10 +288,19 @@ def _stable_empty_package(package: dict[str, Any]) -> dict[str, Any]: stable = dict(package) for field in ( "asOf", + "audienceDigest", "decisionRef", "expiresAt", - "organizationRef", "packageDigest", + "packageId", + "packageSchemaRef", + "policyEpoch", + "policySnapshotRef", + "releaseManifestRef", + "retentionPolicyRef", + "runRef", + "tokenizerRef", + "continuation", ): stable.pop(field) return stable diff --git a/tests/process/conformance_app.py b/tests/process/conformance_app.py index 0a5f4b84..d980c753 100644 --- a/tests/process/conformance_app.py +++ b/tests/process/conformance_app.py @@ -32,6 +32,7 @@ TEST_QUERY_DIGEST_KEYRING, recording_context_run_session, ) +from tests.support.releases import active_runtime_release PROCESS_VALID_TOKEN = "process-test-credential" PROCESS_ORGANIZATION_REF = "81e18bca-86a1-478a-937d-7675c6fe69b0" @@ -100,6 +101,9 @@ def read_current_epoch(self, organization_id: UUID) -> object: authentication_binding_ref=identity.authentication_binding_ref, checked_at=identity.checked_at, policy_epoch_verification=verification, + active_runtime_release=active_runtime_release( + identity.organization_id + ), context_run_persistence_session=persistence_session, ) finally: diff --git a/tests/process/test_processes.py b/tests/process/test_processes.py index ed9df6bc..f911e9f1 100644 --- a/tests/process/test_processes.py +++ b/tests/process/test_processes.py @@ -10,6 +10,7 @@ from typing import cast from urllib.error import HTTPError from urllib.request import Request, urlopen +from uuid import UUID import pytest @@ -18,6 +19,7 @@ PROCESS_ORGANIZATION_REF, PROCESS_VALID_TOKEN, ) +from tests.support.releases import active_runtime_release ROOT = Path(__file__).parents[2] @@ -32,9 +34,7 @@ def _wait_until_ready(process: subprocess.Popen[str], port: int) -> None: if process.poll() is not None or time.monotonic() >= deadline: process.terminate() output, _ = process.communicate(timeout=5) - raise AssertionError( - f"API failed to become ready:\n{output}" - ) from None + raise AssertionError(f"API failed to become ready:\n{output}") from None time.sleep(0.05) @@ -176,11 +176,12 @@ def test_http_acquire_smoke_returns_the_empty_package_contract() -> None: try: _wait_until_ready(process, port) request = Request( - f"http://127.0.0.1:{port}/v1/context:resolve", + f"http://127.0.0.1:{port}/v0/resolve", data=b'{"kind":"acquire","need":{"query":"process smoke"}}', headers={ "Authorization": f"Bearer {PROCESS_VALID_TOKEN}", "Content-Type": "application/json", + "X-Context-Request-Id": "process-v0-smoke", }, method="POST", ) @@ -191,8 +192,13 @@ def test_http_acquire_smoke_returns_the_empty_package_contract() -> None: assert payload["kind"] == "resolved" package = payload["package"] - assert package["organizationRef"] != PROCESS_ORGANIZATION_REF + assert package["packageId"].startswith("pkg_") + assert PROCESS_ORGANIZATION_REF not in json.dumps(payload) assert package["purpose"] == "context.answer" + release = active_runtime_release(UUID(PROCESS_ORGANIZATION_REF)) + assert package["releaseManifestRef"] == release.manifest_ref + assert package["tokenizerRef"] == release.tokenizer_ref + assert package["packageSchemaRef"] == release.package_schema_ref assert package["blocks"] == [] assert package["evidence"] == [] assert package["gaps"] == [] diff --git a/tests/support/releases.py b/tests/support/releases.py new file mode 100644 index 00000000..61efceda --- /dev/null +++ b/tests/support/releases.py @@ -0,0 +1,470 @@ +"""Explicit test-only Runtime release lineage and real Learning promotion.""" + +from datetime import UTC, datetime, timedelta +from hashlib import sha256 +from uuid import UUID + +from sqlalchemy import text + +from engine.learning import ( + ContentProfileRef, + ContextLearning, + CurationProfileRef, + Gate, + GateEvidence, + GateStatus, + IndexProfileRef, + PromotionAuthorizationRequest, + ReleaseCandidate, + ReleaseEvaluationKeyring, + ReleaseManifest, + ReleaseOperatorAuthenticationRejected, + ReleaseOperatorAuthority, + RuntimeProfileRef, + VerifiedReleaseOperatorIdentity, + release_authority_digest, +) +from engine.persistence import ( + assert_learning_role, + create_database_engine, + load_harness_database_configurations, +) +from engine.persistence.releases import PostgreSQLReleaseStore +from engine.runtime.release_lineage import ( + CONTENT_PROFILE_DIGEST_V0, + CONTENT_PROFILE_REF_V0, + CONTENT_SCHEMA_REF_V0, + CURATION_PROFILE_DIGEST_V0, + CURATION_PROFILE_REF_V0, + INDEX_PROFILE_DIGEST_V0, + INDEX_PROFILE_REF_V0, + INDEX_SCHEMA_REF_V0, + PACKAGE_SCHEMA_REF_V0, + RUNTIME_PROFILE_DIGEST_V0, + RUNTIME_PROFILE_REF_V0, + RUNTIME_TOKENIZER_REF_V0, + ActiveRuntimeRelease, +) + +_SIGNING_KEY = b"openapi-v0-test-release-evaluation-key" +_SIGNING_KEY_VERSION = 66 + + +def _digest(value: str) -> str: + return sha256(value.encode("utf-8")).hexdigest() + + +class _ExactReleaseAuthenticator: + def __init__( + self, + credential: str, + identity: VerifiedReleaseOperatorIdentity, + ) -> None: + self._credential = credential + self._identity = identity + + def authenticate(self, opaque_credential: str) -> VerifiedReleaseOperatorIdentity: + if opaque_credential != self._credential: + raise ReleaseOperatorAuthenticationRejected + return self._identity + + +def active_runtime_release( + organization_id: UUID, + *, + suffix: str = "test-v0", + active_revision_refs: tuple[str, ...] = (), +) -> ActiveRuntimeRelease: + return ActiveRuntimeRelease( + organization_id=organization_id, + manifest_digest=_digest(f"manifest-{suffix}"), + active_generation=1, + content_profile_ref=CONTENT_PROFILE_REF_V0, + content_schema_ref=CONTENT_SCHEMA_REF_V0, + index_profile_ref=INDEX_PROFILE_REF_V0, + index_schema_ref=INDEX_SCHEMA_REF_V0, + runtime_profile_ref=RUNTIME_PROFILE_REF_V0, + runtime_profile_digest=RUNTIME_PROFILE_DIGEST_V0, + content_profile_digest=CONTENT_PROFILE_DIGEST_V0, + index_profile_digest=INDEX_PROFILE_DIGEST_V0, + tokenizer_ref=RUNTIME_TOKENIZER_REF_V0, + package_schema_ref=PACKAGE_SCHEMA_REF_V0, + curation_profile_ref=CURATION_PROFILE_REF_V0, + curation_profile_digest=CURATION_PROFILE_DIGEST_V0, + curation_mode="curation_off", + curation_snapshot_ref=None, + curation_evaluation_digest=None, + compatible_revision_refs=(), + active_revision_refs=active_revision_refs, + ) + + +def ensure_test_runtime_release( + organization_id: UUID, + *, + active_revision_refs: tuple[str, ...] | None = None, + runtime_profile_ref: str = RUNTIME_PROFILE_REF_V0, + tokenizer_ref: str = RUNTIME_TOKENIZER_REF_V0, + package_schema_ref: str = PACKAGE_SCHEMA_REF_V0, +) -> ActiveRuntimeRelease: + """Promote the test profile through ContextLearning when no pointer exists. + + This helper is intentionally integration-only: it provisions the current + test operator grant, then uses the same signed evaluation and sole + ContextLearning promotion owner as production. It never writes the active + pointer directly and never creates a production fallback. + """ + + configurations = load_harness_database_configurations() + migration_engine = create_database_engine(configurations.migration) + learning_engine = create_database_engine(configurations.learning) + suffix = f"openapi-v0-{organization_id.hex}" + advisory_lock_scope = f"context-engine.test-runtime-release:{organization_id}" + lock_connection = migration_engine.connect() + try: + lock_connection.execute( + text( + "SELECT pg_catalog.pg_advisory_lock(" + "pg_catalog.hashtextextended(:scope, 0))" + ), + {"scope": advisory_lock_scope}, + ) + lock_connection.commit() + if active_revision_refs is None: + active_revision_refs = tuple( + str(revision_id) + for revision_id in lock_connection.execute( + text( + """ + SELECT active_revision_id + FROM context_resource + WHERE organization_id = :organization_id + AND active_revision_id IS NOT NULL + AND tombstoned IS FALSE + ORDER BY active_revision_id + """ + ), + {"organization_id": organization_id}, + ).scalars() + ) + lock_connection.commit() + existing = lock_connection.execute( + text( + """ + SELECT active.active_generation, + manifest.manifest_ref, + manifest.manifest_digest, + manifest.content_profile_ref, + manifest.content_schema_ref, + manifest.index_profile_ref, + manifest.index_schema_ref, + manifest.runtime_profile_ref, + manifest.runtime_profile_digest, + manifest.runtime_content_profile_digest, + manifest.runtime_index_profile_digest, + manifest.runtime_tokenizer_ref, + manifest.runtime_package_schema_ref, + manifest.curation_profile_ref, + manifest.curation_profile_digest, + manifest.curation_mode, + manifest.curation_snapshot_ref, + manifest.curation_evaluation_digest, + manifest.compatible_revision_refs, + manifest.active_revision_refs + FROM active_release_manifest AS active + JOIN release_manifest AS manifest + ON manifest.organization_id = active.organization_id + AND manifest.manifest_ref = active.manifest_ref + AND manifest.manifest_digest = active.manifest_digest + WHERE active.organization_id = :organization_id + """ + ), + {"organization_id": organization_id}, + ).one_or_none() + lock_connection.commit() + if existing is not None: + selected_revisions = tuple(existing.active_revision_refs) + if selected_revisions == tuple(sorted(active_revision_refs)): + try: + return ActiveRuntimeRelease( + organization_id=organization_id, + manifest_digest=existing.manifest_digest, + active_generation=existing.active_generation, + content_profile_ref=existing.content_profile_ref, + content_schema_ref=existing.content_schema_ref, + index_profile_ref=existing.index_profile_ref, + index_schema_ref=existing.index_schema_ref, + runtime_profile_ref=existing.runtime_profile_ref, + runtime_profile_digest=existing.runtime_profile_digest, + content_profile_digest=( + existing.runtime_content_profile_digest + ), + index_profile_digest=existing.runtime_index_profile_digest, + tokenizer_ref=existing.runtime_tokenizer_ref, + package_schema_ref=existing.runtime_package_schema_ref, + curation_profile_ref=existing.curation_profile_ref, + curation_profile_digest=existing.curation_profile_digest, + curation_mode=existing.curation_mode, + curation_snapshot_ref=existing.curation_snapshot_ref, + curation_evaluation_digest=( + existing.curation_evaluation_digest + ), + compatible_revision_refs=tuple( + existing.compatible_revision_refs + ), + active_revision_refs=selected_revisions, + ) + except (TypeError, ValueError): + pass + clear_test_runtime_release(organization_id) + + now = datetime.now(UTC).replace(microsecond=0) + operator_ref = f"operator-{suffix}" + authentication_binding_ref = f"authentication-{suffix}" + authority_ref = f"authority-{suffix}" + credential = f"credential-{suffix}" + identity = VerifiedReleaseOperatorIdentity( + organization_id=organization_id, + operator_ref=operator_ref, + authentication_binding_ref=authentication_binding_ref, + authority_ref=authority_ref, + authority_digest=release_authority_digest( + organization_id=organization_id, + operator_ref=operator_ref, + authentication_binding_ref=authentication_binding_ref, + authority_ref=authority_ref, + ), + valid_from=now - timedelta(hours=1), + expires_at=now + timedelta(hours=1), + ) + with migration_engine.begin() as connection: + connection.execute( + text( + """ + INSERT INTO release_operator_grant ( + organization_id, authority_ref, authority_digest, + operator_ref, authentication_binding_ref, + valid_from, expires_at + ) VALUES ( + :organization_id, :authority_ref, :authority_digest, + :operator_ref, :authentication_binding_ref, + :valid_from, :expires_at + ) + """ + ), + { + "organization_id": organization_id, + "authority_ref": identity.authority_ref, + "authority_digest": identity.authority_digest, + "operator_ref": identity.operator_ref, + "authentication_binding_ref": (identity.authentication_binding_ref), + "valid_from": identity.valid_from, + "expires_at": identity.expires_at, + }, + ) + + content = ContentProfileRef( + profile_ref=CONTENT_PROFILE_REF_V0, + profile_digest=CONTENT_PROFILE_DIGEST_V0, + content_schema_ref=CONTENT_SCHEMA_REF_V0, + ) + index = IndexProfileRef( + profile_ref=INDEX_PROFILE_REF_V0, + profile_digest=INDEX_PROFILE_DIGEST_V0, + content_profile_digest=content.profile_digest, + content_schema_ref=content.content_schema_ref, + index_schema_ref=INDEX_SCHEMA_REF_V0, + ) + runtime = RuntimeProfileRef( + profile_ref=runtime_profile_ref, + profile_digest=RUNTIME_PROFILE_DIGEST_V0, + content_profile_digest=content.profile_digest, + index_profile_digest=index.profile_digest, + content_schema_ref=content.content_schema_ref, + index_schema_ref=index.index_schema_ref, + tokenizer_ref=tokenizer_ref, + package_schema_ref=package_schema_ref, + ) + manifest = ReleaseManifest( + organization_id=organization_id, + manifest_ref=f"manifest-{suffix}", + content_profile=content, + index_profile=index, + runtime_profile=runtime, + curation_profile=CurationProfileRef.off( + profile_ref=CURATION_PROFILE_REF_V0, + profile_digest=CURATION_PROFILE_DIGEST_V0, + ), + active_revision_refs=tuple(sorted(active_revision_refs)), + ) + candidate = ReleaseCandidate( + organization_id=organization_id, + candidate_ref=f"candidate-{suffix}", + manifest=manifest, + expected_active_generation=0, + expected_base_manifest_digest=None, + gate_evidence=tuple( + GateEvidence( + gate=gate, + status=GateStatus.PASS, + evidence_digest=_digest(f"{gate.value}-gate-{suffix}"), + ) + for gate in Gate + ), + capability_coverage_digest=_digest(f"capability-coverage-{suffix}"), + fixture_digest=_digest(f"fixture-{suffix}"), + verification_commands=("make check",), + ) + with learning_engine.connect() as connection: + assert_learning_role(connection) + keyring = ReleaseEvaluationKeyring( + active_version=_SIGNING_KEY_VERSION, + keys={_SIGNING_KEY_VERSION: _SIGNING_KEY}, + ) + authority = ReleaseOperatorAuthority( + _ExactReleaseAuthenticator(credential, identity), + call_ttl=timedelta(minutes=5), + clock=lambda: now, + ) + store = PostgreSQLReleaseStore(learning_engine) + learning = ContextLearning( + store=store, + evaluation_keyring=keyring, + promotion_authority=authority, + clock=lambda: now, + ) + store.persist_candidate(candidate) + evaluation = learning.evaluate(candidate.reference()) + request = PromotionAuthorizationRequest( + organization_id=organization_id, + promotion_ref=f"promotion-{suffix}", + candidate=candidate, + evaluation=evaluation, + request_id=f"request-{suffix}", + audit_reason="activate explicit OpenAPI v0 integration test profile", + opaque_credential=credential, + ) + with authority.authorize(request) as call: + receipt = learning.promote(call) + if receipt.manifest_ref != manifest.manifest_ref: + raise AssertionError("test release promotion returned wrong manifest") + return ActiveRuntimeRelease( + organization_id=organization_id, + manifest_digest=manifest.manifest_digest, + active_generation=receipt.active_generation, + content_profile_ref=content.profile_ref, + content_schema_ref=content.content_schema_ref, + index_profile_ref=index.profile_ref, + index_schema_ref=index.index_schema_ref, + runtime_profile_ref=runtime.profile_ref, + runtime_profile_digest=runtime.profile_digest, + content_profile_digest=runtime.content_profile_digest, + index_profile_digest=runtime.index_profile_digest, + tokenizer_ref=runtime.tokenizer_ref, + package_schema_ref=runtime.package_schema_ref, + curation_profile_ref=manifest.curation_profile.profile_ref, + curation_profile_digest=manifest.curation_profile.profile_digest, + curation_mode=manifest.curation_profile.mode.value, + curation_snapshot_ref=manifest.curation_profile.curation_snapshot_ref, + curation_evaluation_digest=manifest.curation_profile.evaluation_digest, + compatible_revision_refs=( + manifest.curation_profile.compatible_revision_refs + ), + active_revision_refs=manifest.active_revision_refs, + ) + finally: + lock_connection.execute( + text( + "SELECT pg_catalog.pg_advisory_unlock(" + "pg_catalog.hashtextextended(:scope, 0))" + ), + {"scope": advisory_lock_scope}, + ) + lock_connection.commit() + lock_connection.close() + learning_engine.dispose() + migration_engine.dispose() + + +def clear_test_runtime_release(organization_id: UUID) -> None: + """Remove only explicit integration-test release rows for fixture teardown.""" + + configuration = load_harness_database_configurations().migration + engine = create_database_engine(configuration) + immutable_tables = ( + "release_promotion_audit", + "release_evaluation", + "release_candidate", + "release_manifest", + ) + try: + with engine.begin() as connection: + for table_name in immutable_tables: + connection.execute( + text( + f"ALTER TABLE {table_name} DISABLE TRIGGER " + f"{table_name}_reject_mutation" + ) + ) + try: + with engine.begin() as connection: + for table_name in ( + "decision_audit", + "context_run", + "active_release_manifest", + "release_promotion_audit", + "release_evaluation", + "release_candidate", + "release_manifest", + "release_operator_grant", + ): + connection.execute( + text( + f"DELETE FROM {table_name} " + "WHERE organization_id = :organization_id" + ), + {"organization_id": organization_id}, + ) + finally: + with engine.begin() as connection: + for table_name in reversed(immutable_tables): + connection.execute( + text( + f"ALTER TABLE {table_name} ENABLE TRIGGER " + f"{table_name}_reject_mutation" + ) + ) + finally: + engine.dispose() + + +def clear_all_test_runtime_releases() -> None: + """Clear every release created by this integration-only helper.""" + + configuration = load_harness_database_configurations().migration + engine = create_database_engine(configuration) + try: + with engine.connect() as connection: + organization_ids = tuple( + connection.execute( + text( + """ + SELECT DISTINCT organization_id + FROM release_manifest + WHERE manifest_ref LIKE 'manifest-openapi-v0-%' + """ + ) + ).scalars() + ) + finally: + engine.dispose() + for organization_id in organization_ids: + clear_test_runtime_release(organization_id) + + +__all__ = [ + "active_runtime_release", + "clear_all_test_runtime_releases", + "clear_test_runtime_release", + "ensure_test_runtime_release", +] diff --git a/tests/unit/test_actor_contracts.py b/tests/unit/test_actor_contracts.py index a947be2f..dfa9d17c 100644 --- a/tests/unit/test_actor_contracts.py +++ b/tests/unit/test_actor_contracts.py @@ -36,6 +36,7 @@ _observe_current_policy_epoch, _open_policy_epoch_authority_scope, ) +from tests.support.releases import active_runtime_release CHECKED_AT = datetime(2026, 7, 21, 6, 0, tzinfo=UTC) ORGANIZATION_ID = UUID("81e18bca-86a1-478a-937d-7675c6fe69b0") @@ -108,6 +109,7 @@ def current_membership_proof( policy_epoch_verification=( epoch_verification or policy_epoch_verification(organization_id) ), + active_runtime_release=active_runtime_release(organization_id), ) @@ -143,6 +145,7 @@ def test_current_membership_proof_is_nominal_frozen_and_scope_lived() -> None: authentication_binding_ref="binding-1", checked_at=CHECKED_AT, policy_epoch_verification=policy_epoch_verification(), + active_runtime_release=active_runtime_release(ORGANIZATION_ID), ) _require_active_current_membership_verification(proof) @@ -209,14 +212,15 @@ def test_current_membership_proof_rejects_forged_or_closed_authority_scope() -> current_membership_proof(scope=closed_scope) -def test_current_membership_proofs_from_distinct_authority_scopes_are_distinct( -) -> None: +def test_current_membership_proofs_from_distinct_authority_scopes_are_distinct() -> ( + None +): first_scope = _open_membership_authority_scope() second_scope = _open_membership_authority_scope() - assert current_membership_proof( - scope=first_scope - ) != current_membership_proof(scope=second_scope) + assert current_membership_proof(scope=first_scope) != current_membership_proof( + scope=second_scope + ) _close_membership_authority_scope(first_scope) _close_membership_authority_scope(second_scope) @@ -238,6 +242,7 @@ def test_user_actor_is_nominal_exact_and_keeps_principal_distinct_from_user() -> authentication_binding_ref="binding-1", checked_at=CHECKED_AT, policy_epoch_verification=policy_epoch_verification(), + active_runtime_release=active_runtime_release(ORGANIZATION_ID), ) actor = _construct_user_actor(proof) @@ -257,8 +262,9 @@ def test_user_actor_is_nominal_exact_and_keeps_principal_distinct_from_user() -> _require_active_user_actor(actor) -def test_verified_authentication_requires_canonical_user_membership_and_version( -) -> None: +def test_verified_authentication_requires_canonical_user_membership_and_version() -> ( + None +): context = verified_authentication_context( user_ref=str(USER_ID).replace("-", "").upper(), membership_ref=str(MEMBERSHIP_ID).replace("-", "").upper(), diff --git a/tests/unit/test_context_run.py b/tests/unit/test_context_run.py index c19eceb3..08bc4784 100644 --- a/tests/unit/test_context_run.py +++ b/tests/unit/test_context_run.py @@ -68,6 +68,7 @@ _construct_trusted_scope_snapshot, _open_scope_authority_scope, ) +from tests.support.releases import active_runtime_release ORGANIZATION_ID = UUID("81e18bca-86a1-478a-937d-7675c6fe69b0") OTHER_ORGANIZATION_ID = UUID("48f519e3-c9f1-4e45-af3a-ef48ca5b23f0") @@ -77,7 +78,7 @@ FINALIZED_AT = ACCEPTED_AT + timedelta(milliseconds=20) EXPIRES_AT = FINALIZED_AT + timedelta(seconds=300) DECISION_REF = "dec_00000000000000000000000000000019" -ORGANIZATION_REF = "orgpkg_00000000000000000000000000000019" +ORGANIZATION_REF = "pkg_00000000000000000000000000000019" EVIDENCE_REF = "ev_" + "a" * 64 QUERY_KEYRING = QueryDigestKeyring(active_version=3, keys={3: b"q" * 32}) EFFECTIVE_BUDGET = PackageBudget( @@ -131,6 +132,10 @@ def _trusted_invocation() -> Iterator[AuthenticatedInvocation]: authentication_binding_ref="binding-context-run-secret", checked_at=ACCEPTED_AT, policy_epoch_verification=epoch, + active_runtime_release=active_runtime_release( + ORGANIZATION_ID, + active_revision_refs=("revision-authorized",), + ), ) scope_snapshot = _construct_trusted_scope_snapshot( authority_scope=scope_authority_scope, @@ -184,7 +189,7 @@ def _trusted_invocation() -> Iterator[AuthenticatedInvocation]: def _provenance() -> DecisionProvenanceReceipt: return DecisionProvenanceReceipt( decision_ref=DECISION_REF, - package_organization_ref=ORGANIZATION_REF, + package_id=ORGANIZATION_REF, organization_id=ORGANIZATION_ID, user_id=USER_ID, membership_id=MEMBERSHIP_ID, @@ -206,7 +211,15 @@ def _provenance() -> DecisionProvenanceReceipt: def _empty_package() -> ContextPackage: return ContextPackage( - organization_ref=ORGANIZATION_REF, + package_id=ORGANIZATION_REF, + audience_digest="a" * 64, + policy_epoch=7, + policy_snapshot_ref="policy_issue_19", + run_ref="run_issue_19", + release_manifest_ref=active_runtime_release(ORGANIZATION_ID).manifest_ref, + retention_policy_ref="package-digest-only-retention-v1", + tokenizer_ref=active_runtime_release(ORGANIZATION_ID).tokenizer_ref, + package_schema_ref=active_runtime_release(ORGANIZATION_ID).package_schema_ref, purpose="context.answer", ttl_seconds=300, as_of=FINALIZED_AT, @@ -250,7 +263,15 @@ def _authorized_package() -> ContextPackage: ) body = "safe authorized text" return ContextPackage( - organization_ref=ORGANIZATION_REF, + package_id=ORGANIZATION_REF, + audience_digest="a" * 64, + policy_epoch=7, + policy_snapshot_ref="policy_issue_19", + run_ref="run_issue_19", + release_manifest_ref=active_runtime_release(ORGANIZATION_ID).manifest_ref, + retention_policy_ref="package-digest-only-retention-v1", + tokenizer_ref=active_runtime_release(ORGANIZATION_ID).tokenizer_ref, + package_schema_ref=active_runtime_release(ORGANIZATION_ID).package_schema_ref, purpose="context.answer", ttl_seconds=300, as_of=FINALIZED_AT, @@ -453,7 +474,7 @@ def test_projection_rejects_evidence_after_final_scope_veto() -> None: {"request_id": "request-other"}, {"purpose": "context.other"}, {"as_of": FINALIZED_AT + timedelta(microseconds=1)}, - {"package_organization_ref": "orgpkg_" + "f" * 32}, + {"package_id": "pkg_" + "f" * 32}, {"decision_ref": "dec_" + "f" * 32}, {"policy_epoch": 8}, {"effective_scope_digest": "f" * 64}, diff --git a/tests/unit/test_database_harness_contract.py b/tests/unit/test_database_harness_contract.py index 32e5f1f6..5db51d85 100644 --- a/tests/unit/test_database_harness_contract.py +++ b/tests/unit/test_database_harness_contract.py @@ -210,13 +210,18 @@ def test_ci_runs_the_same_make_database_contract_as_local() -> None: assert "make db-up" in workflow assert "run: make check" in workflow + assert "fetch-depth: 0" in workflow + assert "OPENAPI_BASELINE_REF:" in workflow + assert "github.event.pull_request.base.sha" in workflow + assert "github.event.before" in workflow assert "if: always()" in workflow assert "make db-down" in workflow assert ( - "check: build lint typecheck test catalog smoke integration security-gate" - in makefile + "check: build lint typecheck openapi-check test catalog smoke " + "integration security-gate" in makefile ) assert "./scripts/database_harness.sh integration" in makefile + assert "--baseline-ref $(OPENAPI_BASELINE_REF)" in makefile def test_ci_runs_and_retains_the_single_m0_security_gate_contract() -> None: @@ -229,8 +234,8 @@ def test_ci_runs_and_retains_the_single_m0_security_gate_contract() -> None: "--output-dir .context-engine/security-gate" in makefile ) assert ( - "check: build lint typecheck test catalog smoke integration security-gate" - in makefile.splitlines() + "check: build lint typecheck openapi-check test catalog smoke " + "integration security-gate" in makefile.splitlines() ) assert "actions/upload-artifact@v4" in workflow assert ".context-engine/security-gate/raw-evidence.json" in workflow diff --git a/tests/unit/test_effective_scope_runtime.py b/tests/unit/test_effective_scope_runtime.py index d6bddded..1e69957b 100644 --- a/tests/unit/test_effective_scope_runtime.py +++ b/tests/unit/test_effective_scope_runtime.py @@ -49,6 +49,7 @@ TEST_QUERY_DIGEST_KEYRING, recording_context_run_session, ) +from tests.support.releases import active_runtime_release AS_OF = datetime(2026, 7, 21, 9, 0, tzinfo=UTC) ORGANIZATION_ID = UUID("81e18bca-86a1-478a-937d-7675c6fe69b0") @@ -141,6 +142,7 @@ def read_current_epoch(self, organization_id: UUID) -> object: authentication_binding_ref="binding-1", checked_at=AS_OF, policy_epoch_verification=policy_epoch_verification, + active_runtime_release=active_runtime_release(ORGANIZATION_ID), context_run_persistence_session=persistence_session, ) scope_snapshot = _construct_trusted_scope_snapshot( @@ -233,8 +235,7 @@ def test_runtime_observes_only_effective_scope_and_returns_empty_package() -> No assert outcome.scope_decision.digest not in serialized_package -def test_agent_ceiling_can_only_reduce_other_trusted_grants( -) -> None: +def test_agent_ceiling_can_only_reduce_other_trusted_grants() -> None: broad_spy = ContentIoSpy() broad_agent = resolve( make_operands( diff --git a/tests/unit/test_egress_grant.py b/tests/unit/test_egress_grant.py index 89bd2f0c..063fa10a 100644 --- a/tests/unit/test_egress_grant.py +++ b/tests/unit/test_egress_grant.py @@ -43,7 +43,15 @@ def _package(*, purpose: str = "answer") -> ContextPackage: return ContextPackage( - organization_ref="orgpkg_" + "1" * 32, + package_id="pkg_" + "1" * 32, + audience_digest="a" * 64, + policy_epoch=1, + policy_snapshot_ref="policy-test", + run_ref="run-test", + release_manifest_ref="manifest-test", + retention_policy_ref="package-digest-only-retention-v1", + tokenizer_ref="utf8-byte-budget-test", + package_schema_ref="context-package-openapi-v0", purpose=purpose, ttl_seconds=300, as_of=NOW, @@ -482,10 +490,7 @@ def test_each_egress_binding_mutation_and_cross_kind_emits_zero_bytes_effects() with pytest.raises(EgressGrantNotAvailable, match="not available"): channel_boundary.preflight(payload, channel_grant) assert ( - sender.preflight_count - == sender.outbound_bytes - == sender.effect_count - == 0 + sender.preflight_count == sender.outbound_bytes == sender.effect_count == 0 ) for wrong_gateway_profile in ( @@ -523,10 +528,7 @@ def test_each_egress_binding_mutation_and_cross_kind_emits_zero_bytes_effects() sender=sender, ) assert ( - sender.preflight_count - == sender.outbound_bytes - == sender.effect_count - == 0 + sender.preflight_count == sender.outbound_bytes == sender.effect_count == 0 ) model_gateway = DeterministicModelGatewaySpy(_model_profile()) diff --git a/tests/unit/test_http_authorized_evidence_contract.py b/tests/unit/test_http_authorized_evidence_contract.py index 5b47ba3c..2c68eda7 100644 --- a/tests/unit/test_http_authorized_evidence_contract.py +++ b/tests/unit/test_http_authorized_evidence_contract.py @@ -35,7 +35,15 @@ def empty_outcome() -> Resolved: package = ContextPackage( - organization_ref="orgpkg_" + "c" * 32, + package_id="pkg_" + "c" * 32, + audience_digest="a" * 64, + policy_epoch=17, + policy_snapshot_ref="policy-snapshot-current", + run_ref="run-authorized-request", + release_manifest_ref="manifest-test", + retention_policy_ref="package-digest-only-retention-v1", + tokenizer_ref="utf8-byte-budget-test", + package_schema_ref="context-package-openapi-v0", purpose="context.answer", ttl_seconds=300, as_of=AS_OF, @@ -82,7 +90,15 @@ def authorized_outcome() -> Resolved: lineage=lineage, ) package = ContextPackage( - organization_ref="orgpkg_" + "c" * 32, + package_id="pkg_" + "c" * 32, + audience_digest="a" * 64, + policy_epoch=17, + policy_snapshot_ref="policy-snapshot-current", + run_ref="run-authorized-request", + release_manifest_ref="manifest-test", + retention_policy_ref="package-digest-only-retention-v1", + tokenizer_ref="utf8-byte-budget-test", + package_schema_ref="context-package-openapi-v0", purpose="context.answer", ttl_seconds=300, as_of=AS_OF, @@ -123,15 +139,23 @@ def test_authorized_package_maps_to_the_exact_closed_public_shape() -> None: assert document == { "kind": "resolved", "package": { - "organizationRef": "orgpkg_" + "c" * 32, + "packageId": "pkg_" + "c" * 32, + "packageDigest": ( + "cab1b244227cbdb1a817d6c102337b819e5e7d12d30b7d9aa9e6be096773b03d" + ), "purpose": "context.answer", - "ttlSeconds": 300, + "audienceDigest": "a" * 64, + "policyEpoch": 17, + "policySnapshotRef": "policy-snapshot-current", + "decisionRef": DECISION_REF, + "runRef": "run-authorized-request", + "releaseManifestRef": "manifest-test", + "retentionPolicyRef": "package-digest-only-retention-v1", "asOf": "2026-07-21T05:00:00Z", "expiresAt": "2026-07-21T05:05:00Z", - "decisionRef": DECISION_REF, - "packageDigest": ( - "4905f3fb20b9d4cc1b78d75dbd1a92bf4fc59a8475a1cf27e9298e2bafc71750" - ), + "ttlSeconds": 300, + "tokenizerRef": "utf8-byte-budget-test", + "packageSchemaRef": "context-package-openapi-v0", "blocks": [ { "blockId": BLOCK_ID, @@ -153,7 +177,14 @@ def test_authorized_package_maps_to_the_exact_closed_public_shape() -> None: "decisionRef": DECISION_REF, "policySnapshotRef": "policy-snapshot-current", "policyEpoch": 17, - "sourceDecisionRef": "source-decision-current", + "sourceAclEvidence": { + "kind": "mirrored", + "projectionRef": "source-decision-current", + "aclAsOf": "2026-07-21T05:00:00Z", + "freshnessProfileRef": ( + "file-source-access-current-transaction-v1" + ), + }, } ], "gaps": [], @@ -178,6 +209,8 @@ def test_authorized_package_maps_to_the_exact_closed_public_shape() -> None: assert forbidden not in serialized package_document = dict(document["package"]) package_digest = package_document.pop("packageDigest") + package_document["evidence"][0]["citationOpenRef"] = None + package_document["continuation"] = None assert verify_context_package_digest(package_document, package_digest) @@ -187,6 +220,8 @@ def test_context_package_wire_requires_exact_block_evidence_closure() -> None: by_alias=True, exclude_none=True, ) + document["evidence"][0]["citationOpenRef"] = None + document["continuation"] = None document["blocks"][0]["evidenceRefs"] = ["ev_" + "d" * 64] document["blocks"][0]["blockId"] = "block_" + "d" * 64 @@ -265,6 +300,8 @@ def test_authorized_budget_usage_allows_tokens_but_no_external_consumption() -> by_alias=True, exclude_none=True, ) + document["evidence"][0]["citationOpenRef"] = None + document["continuation"] = None document["budgetUsage"]["providerCalls"] = 1 with pytest.raises(ValidationError): @@ -277,6 +314,8 @@ def test_authorized_wire_rejects_misaccounted_content_bytes() -> None: by_alias=True, exclude_none=True, ) + document["evidence"][0]["citationOpenRef"] = None + document["continuation"] = None document["budgetUsage"]["tokens"] = 14 with pytest.raises(ValidationError, match="authorized UTF-8 bytes"): @@ -289,6 +328,8 @@ def test_authorized_wire_detects_a_shape_preserving_package_alteration() -> None by_alias=True, exclude_none=True, ) + document["evidence"][0]["citationOpenRef"] = None + document["continuation"] = None document["blocks"][0]["text"] = "altered content" document["budgetUsage"]["tokens"] = len(b"altered content") diff --git a/tests/unit/test_http_trust_boundary.py b/tests/unit/test_http_trust_boundary.py index 703b83a3..ac7d4759 100644 --- a/tests/unit/test_http_trust_boundary.py +++ b/tests/unit/test_http_trust_boundary.py @@ -22,6 +22,7 @@ from adapters.http.organization_authority import ( OrganizationVerificationRejected, ) +from adapters.http.route_policy import ResolveRouteDecision from adapters.http.transport import HttpTransportProfile from engine.persistence.membership_context import ( MembershipAuthorityUnavailable, @@ -76,6 +77,7 @@ TEST_QUERY_DIGEST_KEYRING, recording_context_run_session, ) +from tests.support.releases import active_runtime_release from tests.support.security_gate import record_security_oracles VALID_BODY = { @@ -130,6 +132,20 @@ def authenticate(self, opaque_credential: str) -> VerifiedAuthenticationContext: ) +class FixedRoutePolicy: + def __init__(self, decision: ResolveRouteDecision) -> None: + self.decision = decision + self.calls = 0 + + def decide( + self, + authentication: VerifiedAuthenticationContext, + ) -> ResolveRouteDecision: + assert type(authentication) is VerifiedAuthenticationContext + self.calls += 1 + return self.decision + + class DeterministicMembershipAuthority: """Test twin retaining one nominal proof for the whole Runtime call.""" @@ -187,6 +203,9 @@ def read_current_epoch(self, organization_id: UUID) -> object: authentication_binding_ref=identity.authentication_binding_ref, checked_at=identity.checked_at, policy_epoch_verification=policy_epoch_verification, + active_runtime_release=active_runtime_release( + identity.organization_id + ), context_run_persistence_session=persistence_session, delivery_evidence_redemption_session=( _construct_delivery_evidence_redemption_session( @@ -731,7 +750,6 @@ def test_private_delivery_evidence_is_redeemed_before_runtime_content_work( "binding-from-auth", "chat:private:42", "chat:private:wrong", - valid_port.requests[0].audience_digest, ) public_output = ( valid.text @@ -745,9 +763,7 @@ def test_private_delivery_evidence_is_redeemed_before_runtime_content_work( authenticated_context = DeterministicAuthenticator( private_destination_ref="chat:private:42" ).authenticate(VALID_TOKEN) - ordinary_trace = ( - repr(authenticated_context) + repr(invocations) + repr(outcomes) - ) + ordinary_trace = repr(authenticated_context) + repr(invocations) + repr(outcomes) ordinary_logs = "".join(record.getMessage() for record in caplog.records) for protected_value in protected_values: assert protected_value not in public_output @@ -836,6 +852,7 @@ def test_valid_auth_constructs_exact_trusted_invocation_once() -> None: def test_valid_acquire_returns_canonical_tenant_safe_empty_package() -> None: client = trust_boundary_client(DeterministicAuthenticator(), InvocationSpy()) + release = active_runtime_release(UUID(INTERNAL_ORGANIZATION_REF)) response = client.post( "/v1/context:resolve", @@ -856,29 +873,124 @@ def test_valid_acquire_returns_canonical_tenant_safe_empty_package() -> None: assert response.json() == { "kind": "resolved", "package": { - "organizationRef": response.json()["package"]["organizationRef"], + "packageId": response.json()["package"]["packageId"], + "packageDigest": response.json()["package"]["packageDigest"], "purpose": "context.answer", - "ttlSeconds": 300, + "audienceDigest": response.json()["package"]["audienceDigest"], + "policyEpoch": 7, + "policySnapshotRef": response.json()["package"]["policySnapshotRef"], + "decisionRef": response.json()["package"]["decisionRef"], + "runRef": response.json()["package"]["runRef"], + "releaseManifestRef": release.manifest_ref, + "retentionPolicyRef": "package-digest-only-retention-v1", "asOf": "2026-07-21T05:00:00Z", "expiresAt": "2026-07-21T05:05:00Z", - "decisionRef": response.json()["package"]["decisionRef"], - "packageDigest": response.json()["package"]["packageDigest"], + "ttlSeconds": 300, + "tokenizerRef": release.tokenizer_ref, + "packageSchemaRef": release.package_schema_ref, "blocks": [], "evidence": [], "gaps": [], + "coverage": { + "status": "empty", + "reason": "no_authorized_evidence", + }, "budgetUsage": { "tokens": 0, "providerCalls": 0, "costMicrounits": 0, "elapsedMs": 0, }, - "coverage": { - "status": "empty", - "reason": "no_authorized_evidence", - }, + "continuation": None, }, + "egressGrant": None, } - assert response.json()["package"]["organizationRef"] != (INTERNAL_ORGANIZATION_REF) + assert response.json()["package"]["packageId"] != INTERNAL_ORGANIZATION_REF + + +@pytest.mark.parametrize( + ("decision", "status", "body"), + ( + ( + ResolveRouteDecision.FORBID, + 403, + b'{"code":"application_forbidden"}', + ), + (ResolveRouteDecision.RATE_LIMIT, 429, b'{"code":"rate_limited"}'), + ), +) +def test_authenticated_route_policy_rejects_before_domain_work( + decision: ResolveRouteDecision, + status: int, + body: bytes, +) -> None: + policy = FixedRoutePolicy(decision) + spy = InvocationSpy() + client = TestClient( + create_app( + authenticator=DeterministicAuthenticator(), + organization_authority=DeterministicOrganizationAuthority(), + membership_authority=DeterministicMembershipAuthority(), + route_policy=policy, + invocation_observer=spy.observe, + clock=lambda: RECEIVED_AT, + ) + ) + + response = client.post( + "/v0/resolve", + headers={ + "Authorization": f"Bearer {VALID_TOKEN}", + "X-Context-Request-Id": "route-policy-test", + }, + json=VALID_BODY, + ) + + assert response.status_code == status + assert response.content == body + assert policy.calls == 1 + assert spy.invocations == [] + + +def test_public_v0_and_hidden_v1_bridge_share_one_semantic_runtime_path() -> None: + v0_spy = InvocationSpy() + v1_spy = InvocationSpy() + v0 = trust_boundary_client(DeterministicAuthenticator(), v0_spy) + v1 = trust_boundary_client(DeterministicAuthenticator(), v1_spy) + headers = { + "Authorization": f"Bearer {VALID_TOKEN}", + "X-Context-Request-Id": "compatibility-request", + } + + public = v0.post("/v0/resolve", headers=headers, json=VALID_BODY) + legacy = v1.post("/v1/context:resolve", headers=headers, json=VALID_BODY) + + assert public.status_code == legacy.status_code == 200 + public_body = public.json() + legacy_body = legacy.json() + for body in (public_body, legacy_body): + body["package"].pop("packageId") + body["package"].pop("packageDigest") + body["package"].pop("decisionRef") + body["package"].pop("policySnapshotRef") + body["package"].pop("runRef") + assert public_body == legacy_body + assert len(v0_spy.invocations) == len(v1_spy.invocations) == 1 + + +def test_public_v0_requires_request_id_after_authentication_before_runtime() -> None: + spy = InvocationSpy() + client = trust_boundary_client(DeterministicAuthenticator(), spy) + + response = client.post( + "/v0/resolve", + headers={"Authorization": f"Bearer {VALID_TOKEN}"}, + json=VALID_BODY, + ) + + assert response.status_code == 422 + assert response.content == b'{"code":"invalid_request"}' + assert spy.invocations == [] def test_valid_http_acquire_reaches_the_single_runtime_entry_exactly_once() -> None: @@ -1206,8 +1318,11 @@ def test_budget_and_narrowing_wire_variants_are_strictly_closed( client = trust_boundary_client(DeterministicAuthenticator(), spy) response = client.post( - "/v1/context:resolve", - headers={"Authorization": f"Bearer {VALID_TOKEN}"}, + "/v0/resolve", + headers={ + "Authorization": f"Bearer {VALID_TOKEN}", + "X-Context-Request-Id": "public-v0-injection-matrix", + }, json=body, ) @@ -1254,7 +1369,7 @@ def test_authentication_failures_are_generic_and_call_no_domain_seam( headers["Authorization"] = authorization response = client.post( - "/v1/context:resolve", + "/v0/resolve", headers=headers, json=VALID_BODY, ) @@ -1291,7 +1406,7 @@ def test_invalid_authenticator_output_is_a_generic_authentication_failure( ) response = client.post( - "/v1/context:resolve", + "/v0/resolve", headers={"Authorization": f"Bearer {VALID_TOKEN}"}, json=VALID_BODY, ) @@ -1377,8 +1492,11 @@ def test_trusted_field_injection_is_closed_before_domain_execution( target[field_name] = field_value response = client.post( - "/v1/context:resolve", - headers={"Authorization": f"Bearer {VALID_TOKEN}"}, + "/v0/resolve", + headers={ + "Authorization": f"Bearer {VALID_TOKEN}", + "X-Context-Request-Id": "public-v0-schema-matrix", + }, json=body, ) @@ -1425,8 +1543,11 @@ def test_closed_acquire_shape_rejects_every_schema_violation( client = trust_boundary_client(DeterministicAuthenticator(), spy) response = client.post( - "/v1/context:resolve", - headers={"Authorization": f"Bearer {VALID_TOKEN}"}, + "/v0/resolve", + headers={ + "Authorization": f"Bearer {VALID_TOKEN}", + "X-Context-Request-Id": "public-v0-schema-matrix", + }, json=body, ) @@ -1454,10 +1575,11 @@ def test_duplicate_json_keys_cannot_shadow_injected_or_unknown_fields( client = trust_boundary_client(DeterministicAuthenticator(), spy) response = client.post( - "/v1/context:resolve", + "/v0/resolve", headers={ "Authorization": f"Bearer {VALID_TOKEN}", "Content-Type": "application/json", + "X-Context-Request-Id": "public-v0-duplicate-json", }, content=raw_body, ) @@ -1480,10 +1602,11 @@ def test_non_standard_json_numbers_fail_at_the_transport_boundary( ) response = client.post( - "/v1/context:resolve", + "/v0/resolve", headers={ "Authorization": f"Bearer {VALID_TOKEN}", "Content-Type": "application/json", + "X-Context-Request-Id": "public-v0-non-finite-json", }, content=raw_body, ) @@ -1497,15 +1620,18 @@ def test_non_standard_json_numbers_fail_at_the_transport_boundary( def test_invalid_json_and_media_type_use_generic_transport_error() -> None: spy = InvocationSpy() client = trust_boundary_client(DeterministicAuthenticator(), spy) - headers = {"Authorization": f"Bearer {VALID_TOKEN}"} + headers = { + "Authorization": f"Bearer {VALID_TOKEN}", + "X-Context-Request-Id": "public-v0-transport-matrix", + } malformed = client.post( - "/v1/context:resolve", + "/v0/resolve", headers={**headers, "Content-Type": "application/json"}, content=b'{"kind":"acquire",', ) wrong_media_type = client.post( - "/v1/context:resolve", + "/v0/resolve", headers={**headers, "Content-Type": "text/plain"}, content=b'{"kind":"acquire","need":{"query":"probe"}}', ) @@ -1522,10 +1648,11 @@ def test_invalid_utf8_json_uses_the_documented_generic_transport_error() -> None client = trust_boundary_client(DeterministicAuthenticator(), spy) response = client.post( - "/v1/context:resolve", + "/v0/resolve", headers={ "Authorization": f"Bearer {VALID_TOKEN}", "Content-Type": "application/json", + "X-Context-Request-Id": "public-v0-invalid-utf8", }, content=b'{"kind":"acquire","need":{"query":"\xff"}}', ) @@ -1560,15 +1687,16 @@ def test_resolve_body_limit_is_enforced_before_authentication() -> None: headers = { "Authorization": f"Bearer {VALID_TOKEN}", "Content-Type": "application/json", + "X-Context-Request-Id": "public-v0-body-limit", } exact = exact_client.post( - "/v1/context:resolve", + "/v0/resolve", headers=headers, content=raw_body, ) rejected = rejected_client.post( - "/v1/context:resolve", + "/v0/resolve", headers=headers, content=raw_body, ) @@ -1594,10 +1722,11 @@ def test_chunked_body_cannot_bypass_the_receive_limit() -> None: ) response = client.post( - "/v1/context:resolve", + "/v0/resolve", headers={ "Authorization": f"Bearer {VALID_TOKEN}", "Content-Type": "application/json", + "X-Context-Request-Id": "public-v0-chunked-limit", }, content=iter( [ @@ -1864,20 +1993,23 @@ def test_transport_syntax_precedes_authentication_and_schema_follows_it() -> Non authenticator = DeterministicAuthenticator() spy = InvocationSpy() client = trust_boundary_client(authenticator, spy) - invalid_auth = {"Authorization": "Bearer invalid-credential"} + invalid_auth = { + "Authorization": "Bearer invalid-credential", + "X-Context-Request-Id": "public-v0-auth-order", + } wrong_media_type = client.post( - "/v1/context:resolve", + "/v0/resolve", headers={**invalid_auth, "Content-Type": "text/plain"}, content=b"not-json", ) malformed_json = client.post( - "/v1/context:resolve", + "/v0/resolve", headers={**invalid_auth, "Content-Type": "application/json"}, content=b"{", ) schema_injection = client.post( - "/v1/context:resolve", + "/v0/resolve", headers=invalid_auth, json={**VALID_BODY, "organizationId": "injected"}, ) @@ -1892,6 +2024,29 @@ def test_transport_syntax_precedes_authentication_and_schema_follows_it() -> Non assert spy.invocations == [] +@pytest.mark.parametrize("authorization", (None, "Bearer invalid-credential")) +def test_public_v0_authentication_precedes_required_request_id( + authorization: str | None, +) -> None: + authenticator = DeterministicAuthenticator() + spy = InvocationSpy() + client = trust_boundary_client(authenticator, spy) + headers = {} + if authorization is not None: + headers["Authorization"] = authorization + + response = client.post( + "/v0/resolve", + headers=headers, + json=VALID_BODY, + ) + + assert response.status_code == 401 + assert response.content == b'{"code":"authentication_failed"}' + assert response.headers["www-authenticate"] == "Bearer" + assert spy.invocations == [] + + def test_default_application_rejects_all_credentials() -> None: client = TestClient(create_app()) @@ -1927,229 +2082,35 @@ def test_injected_authenticator_runs_only_the_real_sealed_runtime() -> None: def test_openapi_body_is_closed_and_contains_no_trusted_fields() -> None: - client = trust_boundary_client(DeterministicAuthenticator(), InvocationSpy()) - schema = client.get("/openapi.json").json() - operation = schema["paths"]["/v1/context:resolve"]["post"] - + schema = create_app().openapi() + assert set(schema["paths"]) == {"/v0/resolve"} + operation = schema["paths"]["/v0/resolve"]["post"] assert operation["security"] == [{"ContextEngineBearer": []}] - assert schema["components"]["securitySchemes"]["ContextEngineBearer"] == { - "type": "http", - "scheme": "bearer", - "bearerFormat": "opaque", - } - correlation_parameter = next( - parameter - for parameter in operation["parameters"] - if parameter["name"] == "X-Context-Request-Id" - ) - correlation_schema = correlation_parameter["schema"]["anyOf"][0] - assert correlation_schema["maxLength"] == 256 - request_schema = operation["requestBody"]["content"]["application/json"]["schema"] reachable = reachable_schemas(request_schema, schema["components"]["schemas"]) - assert set(reachable) == { - "ResolveWire", - "AcquireWire", - "ContinueWire", - "OpenCitationWire", - "ContextNeedWire", - "PackageBudgetWire", - "RequestNarrowingWire", - } - assert reachable["AcquireWire"]["properties"].keys() == { - "kind", - "need", - "packageBudget", - "requestNarrowing", - } - assert reachable["ContinueWire"]["properties"].keys() == { - "kind", - "continuationToken", - "packageBudget", - } - assert reachable["OpenCitationWire"]["properties"].keys() == { - "kind", - "citationOpenRef", - } - assert reachable["ContextNeedWire"]["properties"].keys() == {"query"} - assert reachable["PackageBudgetWire"]["properties"].keys() == { - "maxTokens", - "maxProviderCalls", - "maxCostMicrounits", - "maxElapsedMs", - } - assert reachable["RequestNarrowingWire"]["properties"].keys() == { - "sourceRefs", - "resourceRefs", - } - narrowing_properties = reachable["RequestNarrowingWire"]["properties"] - for field_name in ("sourceRefs", "resourceRefs"): - narrowing_schema = narrowing_properties[field_name]["anyOf"][0] - assert narrowing_schema["maxItems"] == 64 - assert narrowing_schema["items"]["maxLength"] == 256 - assert all( - document["additionalProperties"] is False - for name, document in reachable.items() - if name != "ResolveWire" - ) - serialized_request_graph = repr(reachable).casefold() for forbidden in ( "organization", - "tenant", "principal", - "user", "membership", - "agentversion", "purpose", "audience", "acl", "sql", - "placement", "bypass", - "authenticatedinvocation", - "trusteddeliverycontext", - "principalgrants", - "agentceiling", - "membershiprights", - "sourcenativeacl", - "resourceacl", - "purposepolicy", - "precomputedscope", - "effectivescope", ): assert forbidden not in serialized_request_graph - - assert set(operation["responses"]) == {"200", "400", "401", "422", "503"} - assert response_schema_name(operation, 400) == "InvalidRequestWire" - assert response_schema_name(operation, 401) == "AuthenticationFailureWire" - assert response_schema_name(operation, 422) == "InvalidRequestWire" - assert response_schema_name(operation, 503) == "ServiceUnavailableWire" - assert response_schema_name(operation, 200) == "ResolutionOutcomeWire" - response_schema = operation["responses"]["200"]["content"]["application/json"][ - "schema" - ] - response_models = reachable_schemas( - response_schema, - schema["components"]["schemas"], - ) - assert set(response_models) == { - "ResolutionOutcomeWire", - "ResolvedWire", - "RequestNotAvailableWire", - "CitationNotAvailableWire", - "ContextPackageWire", - "BlockWire", - "EvidenceWire", - "BudgetUsageWire", - "CoverageWire", - "ModelEgressGrantWire", - "ChannelEgressGrantWire", - } - resolved_schema = response_models["ResolvedWire"] - assert set(resolved_schema["properties"]) == { - "kind", - "package", - "egressGrant", - } - assert response_models["ModelEgressGrantWire"]["properties"]["value"][ - "pattern" - ] == "^egrm_[0-9a-f]{64}$" - assert response_models["ChannelEgressGrantWire"]["properties"]["value"][ - "pattern" - ] == "^egrc_[0-9a-f]{64}$" - package_schema = response_models["ContextPackageWire"] - assert package_schema["additionalProperties"] is False - assert package_schema["required"] == [ - "organizationRef", - "purpose", - "ttlSeconds", - "asOf", - "expiresAt", - "decisionRef", - "packageDigest", - "blocks", - "evidence", - "gaps", - "budgetUsage", - "coverage", - ] - assert package_schema["properties"]["blocks"]["items"] == { - "$ref": "#/components/schemas/BlockWire" + assert set(operation["responses"]) == { + "200", + "400", + "401", + "403", + "422", + "429", + "503", } - assert package_schema["properties"]["evidence"]["items"] == { - "$ref": "#/components/schemas/EvidenceWire" - } - assert package_schema["properties"]["gaps"]["maxItems"] == 0 - assert package_schema["properties"]["organizationRef"]["pattern"] == ( - "^orgpkg_[0-9a-f]{32}$" - ) - assert package_schema["properties"]["decisionRef"]["pattern"] == ( - "^dec_[0-9a-f]{32}$" - ) - assert package_schema["properties"]["packageDigest"]["pattern"] == ( - "^[0-9a-f]{64}$" - ) - block_schema = response_models["BlockWire"] - assert block_schema["required"] == ["blockId", "text", "evidenceRefs"] - assert block_schema["properties"]["evidenceRefs"]["minItems"] == 1 - assert block_schema["properties"]["evidenceRefs"]["maxItems"] == 1 - evidence_schema = response_models["EvidenceWire"] - assert set(evidence_schema["properties"]) == { - "evidenceRef", - "sourceRef", - "resourceRef", - "revisionRef", - "fragmentRef", - "projectedFields", - "runRef", - "purpose", - "authorizationAsOf", - "decisionRef", - "policySnapshotRef", - "policyEpoch", - "sourceDecisionRef", - } - assert evidence_schema["properties"]["projectedFields"]["minItems"] == 1 - assert evidence_schema["properties"]["projectedFields"]["maxItems"] == 64 - assert all( - response_model["additionalProperties"] is False - for name, response_model in response_models.items() - if name != "ResolutionOutcomeWire" - ) - serialized_response_graph = repr(response_models).casefold() - for forbidden in ( - "effectivescope", - "scopedecision", - "scopetarget", - "targetcount", - "principalref", - "candidate", - "organizationid", - "denied", - "principalgrants", - "agentceiling", - "membershiprights", - "sourcenativeacl", - "resourceacl", - "purposepolicy", - ): - assert forbidden not in serialized_response_graph assert "HTTPValidationError" not in schema["components"]["schemas"] - for name, code in ( - ("InvalidRequestWire", "invalid_request"), - ("AuthenticationFailureWire", "authentication_failed"), - ("ServiceUnavailableWire", "service_unavailable"), - ): - error_schema = schema["components"]["schemas"][name] - assert error_schema["additionalProperties"] is False - assert error_schema["required"] == ["code"] - assert error_schema["properties"]["code"]["const"] == code - serialized_error_schema = repr(error_schema).casefold() - assert "scope" not in serialized_error_schema - assert "digest" not in serialized_error_schema - @pytest.mark.parametrize("header_value", ["", " "]) def test_correlation_header_must_be_non_empty_if_present(header_value: str) -> None: diff --git a/tests/unit/test_http_unavailable_capabilities.py b/tests/unit/test_http_unavailable_capabilities.py index 5d40b3c2..037a146e 100644 --- a/tests/unit/test_http_unavailable_capabilities.py +++ b/tests/unit/test_http_unavailable_capabilities.py @@ -37,6 +37,11 @@ reachable_schemas, ) +PUBLIC_V0_HEADERS = { + "Authorization": f"Bearer {VALID_TOKEN}", + "X-Context-Request-Id": "unavailable-http-request", +} + class ProhibitedScopeAuthority: def __init__(self) -> None: @@ -118,8 +123,8 @@ def test_unavailable_variants_skip_scope_authority_before_generic_outcome( ) response = client.post( - "/v1/context:resolve", - headers={"Authorization": f"Bearer {VALID_TOKEN}"}, + "/v0/resolve", + headers=PUBLIC_V0_HEADERS, json=body, ) @@ -141,8 +146,8 @@ def test_active_acquire_still_requires_the_configured_scope_authority() -> None: ) response = client.post( - "/v1/context:resolve", - headers={"Authorization": f"Bearer {VALID_TOKEN}"}, + "/v0/resolve", + headers=PUBLIC_V0_HEADERS, json=VALID_BODY, ) @@ -166,8 +171,8 @@ def test_accept_005_continue_is_generic_non_retryable_and_zero_io( client, content_io, runtime, invocations = client_for() response = client.post( - "/v1/context:resolve", - headers={"Authorization": f"Bearer {VALID_TOKEN}"}, + "/v0/resolve", + headers=PUBLIC_V0_HEADERS, json={ "kind": "continue", "continuationToken": token, @@ -176,9 +181,7 @@ def test_accept_005_continue_is_generic_non_retryable_and_zero_io( ) assert response.status_code == 200 - assert response.content == ( - b'{"kind":"request_not_available","retryable":false}' - ) + assert response.content == (b'{"kind":"request_not_available","retryable":false}') assert response.headers["cache-control"] == "no-store" assert response.headers["x-context-request-id"] == "unavailable-http-request" assert token not in response.text @@ -189,8 +192,7 @@ def test_accept_005_continue_is_generic_non_retryable_and_zero_io( unauthorized_evidence_count = int("evidence" in response_document) wrong_organization_effect_count = content_io.total_calls missing_context_fallback_count = int( - response_document - != {"kind": "request_not_available", "retryable": False} + response_document != {"kind": "request_not_available", "retryable": False} ) assert unauthorized_evidence_count == 0 assert wrong_organization_effect_count == 0 @@ -217,8 +219,8 @@ def test_accept_010_open_citation_is_generic_and_zero_io( client, content_io, runtime, invocations = client_for() response = client.post( - "/v1/context:resolve", - headers={"Authorization": f"Bearer {VALID_TOKEN}"}, + "/v0/resolve", + headers=PUBLIC_V0_HEADERS, json={"kind": "open_citation", "citationOpenRef": locator}, ) @@ -270,15 +272,13 @@ def test_accept_009_server_owned_unavailable_source_paths_are_generic_and_zero_i ) response = client.post( - "/v1/context:resolve", - headers={"Authorization": f"Bearer {VALID_TOKEN}"}, + "/v0/resolve", + headers=PUBLIC_V0_HEADERS, json=VALID_BODY, ) assert response.status_code == 200 - assert response.content == ( - b'{"kind":"request_not_available","retryable":false}' - ) + assert response.content == (b'{"kind":"request_not_available","retryable":false}') assert case_id not in response.text assert content_io.index_calls == 0 assert content_io.provider_calls == 0 @@ -291,8 +291,7 @@ def test_accept_009_server_owned_unavailable_source_paths_are_generic_and_zero_i content_io.provider_calls + content_io.source_content_calls ) missing_context_fallback_count = int( - response_document - != {"kind": "request_not_available", "retryable": False} + response_document != {"kind": "request_not_available", "retryable": False} ) assert unauthorized_evidence_count == 0 assert wrong_organization_effect_count == 0 @@ -332,8 +331,8 @@ def test_unknown_variants_and_caller_authored_capabilities_are_422_before_runtim client, content_io, runtime, invocations = client_for() response = client.post( - "/v1/context:resolve", - headers={"Authorization": f"Bearer {VALID_TOKEN}"}, + "/v0/resolve", + headers=PUBLIC_V0_HEADERS, json=body, ) @@ -359,8 +358,8 @@ def test_query_parameters_are_rejected_as_closed_schema_violations( client, content_io, runtime, invocations = client_for() response = client.post( - f"/v1/context:resolve?{query}", - headers={"Authorization": f"Bearer {VALID_TOKEN}"}, + f"/v0/resolve?{query}", + headers=PUBLIC_V0_HEADERS, json=VALID_BODY, ) @@ -375,8 +374,11 @@ def test_known_unavailable_variant_still_requires_transport_authentication() -> client, content_io, runtime, invocations = client_for() response = client.post( - "/v1/context:resolve", - headers={"Authorization": "Bearer invalid"}, + "/v0/resolve", + headers={ + "Authorization": "Bearer invalid", + "X-Context-Request-Id": "unavailable-http-request", + }, json={"kind": "continue", "continuationToken": "opaque-token"}, ) @@ -392,8 +394,8 @@ def test_refusal_audit_retains_only_the_safe_internal_typed_category() -> None: opaque_value = "secret-opaque-capability-value" response = client.post( - "/v1/context:resolve", - headers={"Authorization": f"Bearer {VALID_TOKEN}"}, + "/v0/resolve", + headers=PUBLIC_V0_HEADERS, json={"kind": "continue", "continuationToken": opaque_value}, ) @@ -421,16 +423,14 @@ def test_opaque_wire_models_redact_capability_values_from_repr() -> None: assert opaque_locator not in repr(citation) -def test_openapi_freezes_the_closed_three_variant_request_and_outcome_unions( -) -> None: +def test_openapi_freezes_the_closed_three_variant_request_and_outcome_unions() -> None: client, _, _, _ = client_for() schema = client.get("/openapi.json").json() - operation = schema["paths"]["/v1/context:resolve"]["post"] + assert set(schema["paths"]) == {"/v0/resolve"} + operation = schema["paths"]["/v0/resolve"]["post"] components = schema["components"]["schemas"] - request_schema = operation["requestBody"]["content"]["application/json"][ - "schema" - ] + request_schema = operation["requestBody"]["content"]["application/json"]["schema"] request_union_name = request_schema["$ref"].rsplit("/", maxsplit=1)[-1] assert request_union_name == "ResolveWire" request_union_schema = components[request_union_name] @@ -470,9 +470,9 @@ def test_openapi_freezes_the_closed_three_variant_request_and_outcome_unions( ): assert forbidden not in request_graph - response_schema = operation["responses"]["200"]["content"][ - "application/json" - ]["schema"] + response_schema = operation["responses"]["200"]["content"]["application/json"][ + "schema" + ] response_union_name = response_schema["$ref"].rsplit("/", maxsplit=1)[-1] assert response_union_name == "ResolutionOutcomeWire" assert components[response_union_name]["discriminator"]["propertyName"] == "kind" @@ -511,8 +511,8 @@ def test_existing_http_acquire_remains_a_resolved_package() -> None: client, content_io, runtime, _ = client_for() response = client.post( - "/v1/context:resolve", - headers={"Authorization": f"Bearer {VALID_TOKEN}"}, + "/v0/resolve", + headers=PUBLIC_V0_HEADERS, json=VALID_BODY, ) diff --git a/tests/unit/test_membership_context.py b/tests/unit/test_membership_context.py index e9df40a0..367e49b2 100644 --- a/tests/unit/test_membership_context.py +++ b/tests/unit/test_membership_context.py @@ -27,6 +27,21 @@ _require_active_materialized_projection_session, ) from engine.runtime.policy_epoch import PolicyEpochAuthorityUnavailable +from engine.runtime.release_lineage import ( + CONTENT_PROFILE_DIGEST_V0, + CONTENT_PROFILE_REF_V0, + CONTENT_SCHEMA_REF_V0, + CURATION_PROFILE_DIGEST_V0, + CURATION_PROFILE_REF_V0, + INDEX_PROFILE_DIGEST_V0, + INDEX_PROFILE_REF_V0, + INDEX_SCHEMA_REF_V0, + PACKAGE_SCHEMA_REF_V0, + RUNTIME_PROFILE_DIGEST_V0, + RUNTIME_PROFILE_REF_V0, + RUNTIME_TOKENIZER_REF_V0, + public_release_manifest_ref, +) CHECKED_AT = datetime(2026, 7, 21, 8, 0, tzinfo=UTC) @@ -50,6 +65,30 @@ def __init__(self, user_id: UUID) -> None: self.user_id = user_id +class _ActiveReleaseRow: + def __init__(self, organization_id: UUID) -> None: + self.organization_id = organization_id + self.active_generation = 1 + self.manifest_digest = "a" * 64 + self.content_profile_ref = CONTENT_PROFILE_REF_V0 + self.content_schema_ref = CONTENT_SCHEMA_REF_V0 + self.index_profile_ref = INDEX_PROFILE_REF_V0 + self.index_schema_ref = INDEX_SCHEMA_REF_V0 + self.runtime_profile_ref = RUNTIME_PROFILE_REF_V0 + self.runtime_profile_digest = RUNTIME_PROFILE_DIGEST_V0 + self.runtime_content_profile_digest = CONTENT_PROFILE_DIGEST_V0 + self.runtime_index_profile_digest = INDEX_PROFILE_DIGEST_V0 + self.runtime_tokenizer_ref = RUNTIME_TOKENIZER_REF_V0 + self.runtime_package_schema_ref = PACKAGE_SCHEMA_REF_V0 + self.curation_profile_ref = CURATION_PROFILE_REF_V0 + self.curation_profile_digest = CURATION_PROFILE_DIGEST_V0 + self.curation_mode = "curation_off" + self.curation_snapshot_ref = None + self.curation_evaluation_digest = None + self.compatible_revision_refs: list[str] = [] + self.active_revision_refs: list[str] = [] + + class _ProjectionRowsResult: def __init__(self, rows: tuple[SimpleNamespace, ...] = ()) -> None: self._rows = rows @@ -75,6 +114,19 @@ def execute( return _ProjectionRowsResult((self._row,)) +class _ReleaseConnection: + def __init__(self, row: _ActiveReleaseRow) -> None: + self._row = row + + def execute( + self, + statement: object, + parameters: dict[str, object] | None = None, + ) -> _ScalarResult: + del statement, parameters + return _ScalarResult(self._row) + + class _FakeConnection: def __init__( self, @@ -169,6 +221,11 @@ def execute( RuntimeError("secret backend epoch diagnostic"), ) return _ScalarResult(self._policy_epoch) + if "FROM active_release_manifest AS active" in sql: + assert parameters is not None + return _ScalarResult( + _ActiveReleaseRow(cast(UUID, parameters["organization_id"])) + ) if self._fail_on_query: raise OperationalError("query", {}, RuntimeError("database unavailable")) return _ScalarResult(self._row) @@ -304,6 +361,56 @@ def test_postgres_projection_absorbs_malformed_structured_field_values( assert connection.calls == 2 +@pytest.mark.parametrize( + ("field_name", "invalid_value"), + ( + ("runtime_profile_ref", "unknown-runtime-profile"), + ("content_profile_ref", "unknown-content-profile"), + ("content_schema_ref", "unknown-content-schema"), + ("index_profile_ref", "unknown-index-profile"), + ("index_schema_ref", "unknown-index-schema"), + ("runtime_profile_digest", "b" * 64), + ("runtime_content_profile_digest", "c" * 64), + ("runtime_index_profile_digest", "d" * 64), + ("curation_profile_ref", "unknown-curation-profile"), + ("curation_profile_digest", "e" * 64), + ("curation_mode", "curation_on"), + ("curation_snapshot_ref", "unexpected-snapshot"), + ("compatible_revision_refs", ["revision-b", "revision-a"]), + ("runtime_tokenizer_ref", "unknown-tokenizer"), + ("runtime_package_schema_ref", "unknown-package-schema"), + ("manifest_digest", "A" * 64), + ("active_revision_refs", ["revision-b", "revision-a"]), + ), +) +def test_active_release_observation_fails_closed_for_unrecognized_lineage( + field_name: str, + invalid_value: object, +) -> None: + organization_id = uuid4() + row = _ActiveReleaseRow(organization_id) + setattr(row, field_name, invalid_value) + + observed = membership_context_module._observe_active_runtime_release( + cast(Connection, _ReleaseConnection(row)), + organization_id, + ) + + assert observed is None + + +def test_public_release_ref_is_opaque_and_generation_bound() -> None: + manifest_digest = "a" * 64 + + first = public_release_manifest_ref(manifest_digest, 1) + rollback = public_release_manifest_ref(manifest_digest, 3) + + assert first.startswith("rel_") + assert rollback.startswith("rel_") + assert first != rollback + assert manifest_digest not in first + rollback + + def test_current_membership_transaction_binds_every_actor_fact_before_lookup() -> None: expected = identity() fake_engine = _FakeEngine(_MembershipRow(expected.user_id)) @@ -340,8 +447,18 @@ def test_current_membership_transaction_binds_every_actor_fact_before_lookup() - for index, event in enumerate(fake_engine.events) if "context-engine.file-publication:" in event ) + release_barrier_position = next( + index + for index, event in enumerate(fake_engine.events) + if "context-engine.release:" in event + ) runtime_position = fake_engine.events.index("runtime-resolve") - assert lookup_position < publication_barrier_position < runtime_position + assert ( + lookup_position + < publication_barrier_position + < release_barrier_position + < runtime_position + ) assert fake_engine.events[-2:] == ["runtime-resolve", "commit"] assert fake_engine.settings == { "app.organization_id": str(expected.organization_id), @@ -372,8 +489,7 @@ def test_missing_or_mismatched_membership_is_one_generic_denial( assert fake_engine.events[-1] == "rollback" assert all( - "context-engine.file-publication:" not in event - for event in fake_engine.events + "context-engine.file-publication:" not in event for event in fake_engine.events ) assert rejection.value.audit_receipt == MembershipRejectionAuditReceipt( category=MembershipRejectionCategory.NOT_CURRENT, @@ -447,9 +563,7 @@ def test_policy_epoch_database_fault_is_normalized_at_the_final_gate() -> None: with authority.current_user_actor(expected) as verification: fake_engine.connection.fail_policy_epoch_reads() with pytest.raises(PolicyEpochAuthorityUnavailable) as rejection: - PolicyEpochGate().is_current( - verification.policy_epoch_verification - ) + PolicyEpochGate().is_current(verification.policy_epoch_verification) rendered = (str(rejection.value), repr(rejection.value)) assert rendered == ( @@ -462,8 +576,7 @@ def test_policy_epoch_database_fault_is_normalized_at_the_final_gate() -> None: assert rejection.value.__suppress_context__ is True -def test_initial_policy_epoch_database_fault_remains_membership_unavailable( -) -> None: +def test_initial_policy_epoch_database_fault_remains_membership_unavailable() -> None: expected = identity() fake_engine = _FakeEngine(_MembershipRow(expected.user_id)) fake_engine.connection.fail_policy_epoch_reads() diff --git a/tests/unit/test_openapi_v0_contract.py b/tests/unit/test_openapi_v0_contract.py new file mode 100644 index 00000000..038e126e --- /dev/null +++ b/tests/unit/test_openapi_v0_contract.py @@ -0,0 +1,279 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any, cast + +from fastapi.testclient import TestClient + +from adapters.http.app import create_app + + +def _reachable_schemas( + root: Mapping[str, object], + schemas: Mapping[str, object], +) -> dict[str, Mapping[str, object]]: + pending: list[object] = [root] + reachable: dict[str, Mapping[str, object]] = {} + while pending: + value = pending.pop() + if isinstance(value, Mapping): + reference = value.get("$ref") + if isinstance(reference, str) and reference.startswith( + "#/components/schemas/" + ): + name = reference.rsplit("/", 1)[-1] + if name not in reachable: + document = schemas[name] + assert isinstance(document, Mapping) + reachable[name] = document + pending.append(document) + else: + pending.extend(value.values()) + elif isinstance(value, list): + pending.extend(value) + return reachable + + +def _response_schema_name(operation: Mapping[str, object], status: int) -> str: + responses = operation["responses"] + assert isinstance(responses, Mapping) + response = responses[str(status)] + assert isinstance(response, Mapping) + content = response["content"] + assert isinstance(content, Mapping) + json_response = content["application/json"] + assert isinstance(json_response, Mapping) + schema = json_response["schema"] + assert isinstance(schema, Mapping) + reference = schema["$ref"] + assert isinstance(reference, str) + return reference.rsplit("/", 1)[-1] + + +def test_openapi_v0_exposes_one_versioned_resolve_operation() -> None: + schema = TestClient(create_app()).get("/openapi.json").json() + + assert schema["info"]["version"] == "0.0.0" + assert set(schema["paths"]) == {"/v0/resolve"} + operation = schema["paths"]["/v0/resolve"]["post"] + assert operation["operationId"] == "resolveContextV0" + assert operation["security"] == [{"ContextEngineBearer": []}] + assert schema["components"]["securitySchemes"]["ContextEngineBearer"] == { + "type": "http", + "scheme": "bearer", + "bearerFormat": "opaque", + } + + parameters = {parameter["name"]: parameter for parameter in operation["parameters"]} + assert set(parameters) == { + "X-Context-Request-Id", + "X-Context-Delivery-Evidence-Ref", + } + assert parameters["X-Context-Request-Id"]["in"] == "header" + assert parameters["X-Context-Request-Id"]["required"] is True + assert parameters["X-Context-Delivery-Evidence-Ref"]["required"] is False + evidence_ref_schema = parameters["X-Context-Delivery-Evidence-Ref"]["schema"] + assert evidence_ref_schema["anyOf"][0]["pattern"] == r"^\S+$" + + assert set(operation["responses"]) == { + "200", + "400", + "401", + "403", + "422", + "429", + "503", + } + expected_response_models = { + 200: "ResolutionOutcomeWire", + 400: "InvalidRequestWire", + 401: "AuthenticationFailureWire", + 403: "ApplicationForbiddenWire", + 422: "InvalidRequestWire", + 429: "RateLimitedWire", + 503: "ServiceUnavailableWire", + } + assert { + status: _response_schema_name(operation, status) + for status in expected_response_models + } == expected_response_models + + +def test_openapi_v0_request_is_the_closed_untrusted_union() -> None: + schema = TestClient(create_app()).get("/openapi.json").json() + operation = schema["paths"]["/v0/resolve"]["post"] + root = operation["requestBody"]["content"]["application/json"]["schema"] + reachable = _reachable_schemas(root, schema["components"]["schemas"]) + + assert set(reachable) == { + "ResolveWire", + "AcquireWire", + "ContinueWire", + "OpenCitationWire", + "ContextNeedWire", + "PackageBudgetWire", + "RequestNarrowingWire", + } + assert set(cast(Mapping[str, object], reachable["AcquireWire"]["properties"])) == { + "kind", + "need", + "packageBudget", + "requestNarrowing", + } + assert set(cast(Mapping[str, object], reachable["ContinueWire"]["properties"])) == { + "kind", + "continuationToken", + "packageBudget", + } + assert set( + cast(Mapping[str, object], reachable["OpenCitationWire"]["properties"]) + ) == { + "kind", + "citationOpenRef", + } + assert all( + document["additionalProperties"] is False + for name, document in reachable.items() + if name != "ResolveWire" + ) + + serialized = repr(reachable).casefold() + for forbidden in ( + "organization", + "tenant", + "principal", + "membership", + "actorcontext", + "purpose", + "audiencesnapshot", + "audiencemembers", + "sourceaclevidence", + "egressgrant", + "sql", + "filterbypass", + "preauthorized", + "authorizedprojection", + ): + assert forbidden not in serialized + + +def test_openapi_v0_freezes_the_complete_context_package() -> None: + schema = TestClient(create_app()).get("/openapi.json").json() + operation = schema["paths"]["/v0/resolve"]["post"] + root = operation["responses"]["200"]["content"]["application/json"]["schema"] + reachable = _reachable_schemas(root, schema["components"]["schemas"]) + + assert set(reachable) == { + "ResolutionOutcomeWire", + "ResolvedWire", + "RequestNotAvailableWire", + "CitationNotAvailableWire", + "ContextPackageWire", + "BlockWire", + "EvidenceWire", + "SourceAclEvidenceWire", + "LiveSourceAclEvidenceWire", + "MirroredSourceAclEvidenceWire", + "WeakSourceAclEvidenceWire", + "GapWire", + "BudgetUsageWire", + "CoverageWire", + "ContinuationOfferWire", + "ModelEgressGrantWire", + "ChannelEgressGrantWire", + } + package = cast(dict[str, Any], reachable["ContextPackageWire"]) + resolved = cast(dict[str, Any], reachable["ResolvedWire"]) + assert "egressGrant" in resolved["required"] + assert package["required"] == [ + "packageId", + "packageDigest", + "purpose", + "audienceDigest", + "policyEpoch", + "policySnapshotRef", + "decisionRef", + "runRef", + "releaseManifestRef", + "retentionPolicyRef", + "asOf", + "expiresAt", + "ttlSeconds", + "tokenizerRef", + "packageSchemaRef", + "blocks", + "evidence", + "gaps", + "coverage", + "budgetUsage", + "continuation", + ] + assert package["properties"]["packageId"]["pattern"] == (r"^pkg_[0-9a-f]{32}$") + assert "organizationRef" not in package["properties"] + assert package["properties"]["audienceDigest"]["pattern"] == (r"^[0-9a-f]{64}$") + + evidence = cast(dict[str, Any], reachable["EvidenceWire"]) + assert set(evidence["properties"]) == { + "evidenceRef", + "sourceRef", + "resourceRef", + "revisionRef", + "fragmentRef", + "projectedFields", + "runRef", + "purpose", + "authorizationAsOf", + "decisionRef", + "policySnapshotRef", + "policyEpoch", + "sourceAclEvidence", + "citationOpenRef", + } + source_acl = cast(dict[str, Any], reachable["SourceAclEvidenceWire"]) + assert set(source_acl["discriminator"]["mapping"]) == { + "live", + "mirrored", + "weak", + } + coverage = cast(dict[str, Any], reachable["CoverageWire"]) + assert coverage["properties"]["status"]["enum"] == [ + "empty", + "partial", + "sufficient", + ] + gap = cast(dict[str, Any], reachable["GapWire"]) + assert gap["properties"]["category"]["enum"] == [ + "source_unavailable", + "stale_evidence", + "budget_exhausted", + "capability_unsupported", + ] + budget_usage = cast(dict[str, Any], reachable["BudgetUsageWire"]) + for field_name in ( + "tokens", + "providerCalls", + "costMicrounits", + "elapsedMs", + ): + assert budget_usage["properties"][field_name]["minimum"] == 0 + assert "const" not in budget_usage["properties"][field_name] + + serialized = repr(reachable).casefold() + for forbidden in ( + "organizationid", + "principalref", + "userid", + "membershipid", + "authenticatedinvocation", + "trusteddeliverycontext", + "candidate", + "denied", + ): + assert forbidden not in serialized + + +def test_openapi_generation_is_deterministic_in_process() -> None: + first = create_app().openapi() + second = create_app().openapi() + + assert first == second diff --git a/tests/unit/test_openapi_v0_snapshot.py b/tests/unit/test_openapi_v0_snapshot.py new file mode 100644 index 00000000..0e01c475 --- /dev/null +++ b/tests/unit/test_openapi_v0_snapshot.py @@ -0,0 +1,158 @@ +from __future__ import annotations + +import json +import subprocess +from copy import deepcopy +from hashlib import sha256 +from pathlib import Path +from typing import Any, cast + +import pytest + +from scripts.freeze_openapi import ( + BreakingContractChange, + SnapshotAlreadyExists, + SnapshotDrift, + assert_historical_artifacts_unchanged, + assert_no_breaking_changes, + check_snapshot, + render_openapi_snapshot, + write_new_snapshot, +) + +ROOT = Path(__file__).parents[2] +SNAPSHOT = ROOT / "openapi" / "v0" / "openapi.json" +DIGEST = ROOT / "openapi" / "v0" / "openapi.sha256" + + +def test_checked_in_v0_snapshot_and_digest_match_deterministic_generation() -> None: + generated = render_openapi_snapshot() + + assert generated == SNAPSHOT.read_bytes() + assert DIGEST.read_text(encoding="ascii") == f"{sha256(generated).hexdigest()}\n" + + +def test_historical_snapshot_cannot_be_overwritten(tmp_path: Path) -> None: + version_directory = tmp_path / "v0" + version_directory.mkdir() + (version_directory / "openapi.json").write_text("{}\n", encoding="utf-8") + + with pytest.raises(SnapshotAlreadyExists): + write_new_snapshot(version_directory) + + +def test_breaking_change_gate_rejects_a_deliberate_required_field_removal() -> None: + accepted = create_contract_document() + candidate = deepcopy(accepted) + typed_candidate = cast(dict[str, Any], candidate) + required = typed_candidate["components"]["schemas"]["ContextPackageWire"][ + "required" + ] + required.remove("audienceDigest") + + with pytest.raises(BreakingContractChange, match="ContextPackageWire"): + assert_no_breaking_changes(accepted, candidate) + + +@pytest.mark.parametrize( + "mutation", + ( + "security", + "response", + "outcome_union", + "field_type", + ), +) +def test_recursive_gate_rejects_security_response_union_and_type_changes( + mutation: str, +) -> None: + accepted = create_contract_document() + candidate = cast(dict[str, Any], deepcopy(accepted)) + operation = candidate["paths"]["/v0/resolve"]["post"] + schemas = candidate["components"]["schemas"] + if mutation == "security": + operation.pop("security") + elif mutation == "response": + operation["responses"].pop("401") + elif mutation == "outcome_union": + schemas["ResolutionOutcomeWire"]["oneOf"].pop() + else: + schemas["ContextPackageWire"]["properties"]["ttlSeconds"]["type"] = "string" + + with pytest.raises(BreakingContractChange): + assert_no_breaking_changes(accepted, candidate) + + +def test_historical_artifact_pair_is_append_only_after_first_publication() -> None: + snapshot = b'{"openapi":"3.1.0"}\n' + digest = f"{sha256(snapshot).hexdigest()}\n".encode() + assert_historical_artifacts_unchanged( + current_snapshot=snapshot, + current_digest=digest, + historical_snapshot=None, + historical_digest=None, + ) + + with pytest.raises(SnapshotDrift, match="historical OpenAPI version changed"): + assert_historical_artifacts_unchanged( + current_snapshot=snapshot + b" ", + current_digest=digest, + historical_snapshot=snapshot, + historical_digest=digest, + ) + + +def test_snapshot_check_rejects_mutation_against_the_git_baseline( + tmp_path: Path, +) -> None: + repository = tmp_path / "repository" + version_directory = repository / "openapi" / "v0" + version_directory.mkdir(parents=True) + snapshot_path = version_directory / "openapi.json" + digest_path = version_directory / "openapi.sha256" + accepted = SNAPSHOT.read_bytes() + snapshot_path.write_bytes(accepted) + digest_path.write_text(f"{sha256(accepted).hexdigest()}\n", encoding="ascii") + for arguments in ( + ("init", "--quiet"), + ("config", "user.email", "contract-test@example.invalid"), + ("config", "user.name", "Contract Test"), + ("add", "openapi/v0/openapi.json", "openapi/v0/openapi.sha256"), + ("commit", "--quiet", "-m", "freeze v0"), + ): + subprocess.run( + ("git", *arguments), + cwd=repository, + check=True, + capture_output=True, + ) + + mutated_document = json.loads(accepted) + mutated_document["info"]["description"] = "mutated historical contract" + mutated = ( + json.dumps( + mutated_document, + ensure_ascii=False, + indent=2, + sort_keys=True, + separators=(",", ": "), + ) + + "\n" + ).encode() + snapshot_path.write_bytes(mutated) + digest_path.write_text(f"{sha256(mutated).hexdigest()}\n", encoding="ascii") + + with pytest.raises(SnapshotDrift, match="historical OpenAPI version changed"): + check_snapshot( + version_directory, + baseline_ref="HEAD", + repository_root=repository, + ) + + +def create_contract_document() -> dict[str, object]: + from json import loads + + document = loads(render_openapi_snapshot()) + assert isinstance(document, dict) + return document diff --git a/tests/unit/test_package_digest.py b/tests/unit/test_package_digest.py index 481f13c8..33d8e716 100644 --- a/tests/unit/test_package_digest.py +++ b/tests/unit/test_package_digest.py @@ -30,7 +30,7 @@ def test_context_package_digest_has_a_fixed_canonical_unicode_vector() -> None: "blocks": [{"ordinal": 1, "body": "你好, 🌍"}], } - assert PACKAGE_DIGEST_PROFILE == "context-package-canonical-json-v2" + assert PACKAGE_DIGEST_PROFILE == "context-package-canonical-json-v3" assert context_package_digest(document) == ( "630ba3a578634388e9d107f318a9ba7e2f7c2b9313f8c1bd9034e9325797aa43" ) diff --git a/tests/unit/test_runtime_authorized_evidence.py b/tests/unit/test_runtime_authorized_evidence.py index 857bb287..4e471a26 100644 --- a/tests/unit/test_runtime_authorized_evidence.py +++ b/tests/unit/test_runtime_authorized_evidence.py @@ -78,6 +78,7 @@ RecordingContextRunPort, recording_context_run_session, ) +from tests.support.releases import active_runtime_release from tests.support.security_gate import record_security_oracles AS_OF = datetime(2026, 7, 21, 10, 0, tzinfo=UTC) @@ -321,6 +322,20 @@ def trusted_operands( authentication_binding_ref="binding-authorized-evidence", checked_at=AS_OF, policy_epoch_verification=policy_epoch_verification, + active_runtime_release=active_runtime_release( + ORGANIZATION_ID, + active_revision_refs=tuple( + sorted( + { + AUTHORIZED.revision_ref, + AUTHORIZED_SECOND.revision_ref, + CROSS_ORGANIZATION.revision_ref, + DENIED.revision_ref, + MISSING.revision_ref, + } + ) + ), + ), materialized_projection_session=projection_session, context_run_persistence_session=persistence_session, ) @@ -439,8 +454,7 @@ def test_hostile_candidate_order_delivers_only_exact_authorized_evidence( ): assert forbidden not in rendered unauthorized_evidence_count = sum( - item.fragment_ref - in {DENIED.fragment_ref, CROSS_ORGANIZATION.fragment_ref} + item.fragment_ref in {DENIED.fragment_ref, CROSS_ORGANIZATION.fragment_ref} for item in package.evidence ) wrong_organization_effect_count = sum( @@ -901,7 +915,7 @@ def test_empty_decision_audit_is_generic_and_retains_no_denied_detail() -> None: receipt = DecisionAuditGate().record( DecisionProvenanceReceipt( decision_ref="dec_" + "a" * 32, - package_organization_ref="orgpkg_" + "b" * 32, + package_id="pkg_" + "b" * 32, organization_id=ORGANIZATION_ID, user_id=USER_ID, membership_id=MEMBERSHIP_ID, @@ -1195,8 +1209,7 @@ def test_request_narrowing_filters_candidate_before_body_projection( AUTHORIZED.source_ref, ) unauthorized_evidence_count = sum( - item.source_ref == excluded.source_ref - for item in outcome.package.evidence + item.source_ref == excluded.source_ref for item in outcome.package.evidence ) wrong_organization_effect_count = 0 missing_context_fallback_count = int( diff --git a/tests/unit/test_runtime_contracts.py b/tests/unit/test_runtime_contracts.py index 7dab6a34..feb9db25 100644 --- a/tests/unit/test_runtime_contracts.py +++ b/tests/unit/test_runtime_contracts.py @@ -78,7 +78,15 @@ def make_package(**changes: object) -> ContextPackage: values: dict[str, object] = { - "organization_ref": "orgpkg_00000000000000000000000000000001", + "package_id": "pkg_00000000000000000000000000000001", + "audience_digest": "a" * 64, + "policy_epoch": 1, + "policy_snapshot_ref": "policy-current", + "run_ref": "run-current", + "release_manifest_ref": "manifest-test-v0", + "retention_policy_ref": "package-digest-only-retention-v1", + "tokenizer_ref": "utf8-byte-budget-test-v0", + "package_schema_ref": "context-package-openapi-test-v0", "purpose": "direct_agent_context", "ttl_seconds": 300, "as_of": AS_OF, @@ -300,13 +308,21 @@ def test_context_package_is_the_tenant_safe_evidence_free_deliverable() -> None: assert package.ttl_seconds == 300 assert package.expires_at > package.as_of assert package.package_digest == ( - "3e454e57a97eb4bb47bde1af0d6c7817b080630ecbc88275837329cbd2c4a4a5" + "0628cc729689b617aa77a6e4a6df0eadd398d85dbab1cccfde572b12c46da517" ) assert not hasattr(package, "denied_count") assert not hasattr(package.coverage, "details") assert {field.name for field in fields(package)} == { - "organization_ref", + "package_id", "purpose", + "audience_digest", + "policy_epoch", + "policy_snapshot_ref", + "run_ref", + "release_manifest_ref", + "retention_policy_ref", + "tokenizer_ref", + "package_schema_ref", "ttl_seconds", "as_of", "expires_at", @@ -320,7 +336,7 @@ def test_context_package_is_the_tenant_safe_evidence_free_deliverable() -> None: } with pytest.raises(FrozenInstanceError): - package.organization_ref = "other" # type: ignore[misc] + package.package_id = "other" # type: ignore[misc] def test_context_package_accepts_only_closed_exact_authorized_content() -> None: @@ -408,10 +424,10 @@ def test_context_package_rejects_incomplete_or_misaccounted_content( @pytest.mark.parametrize( "changes", [ - {"organization_ref": ""}, - {"organization_ref": 42}, - {"organization_ref": "81e18bca-86a1-478a-937d-7675c6fe69b0"}, - {"organization_ref": "orgpkg_0000000000000000000000000000000A"}, + {"package_id": ""}, + {"package_id": 42}, + {"package_id": "81e18bca-86a1-478a-937d-7675c6fe69b0"}, + {"package_id": "pkg_0000000000000000000000000000000A"}, {"purpose": " "}, {"purpose": True}, {"decision_ref": ""}, diff --git a/tests/unit/test_runtime_empty_package.py b/tests/unit/test_runtime_empty_package.py index 7569b92a..05779d1a 100644 --- a/tests/unit/test_runtime_empty_package.py +++ b/tests/unit/test_runtime_empty_package.py @@ -2,6 +2,7 @@ from collections.abc import Iterator from contextlib import contextmanager +from dataclasses import replace from datetime import UTC, datetime, timedelta from typing import Any, cast from uuid import UUID @@ -20,6 +21,8 @@ from engine.runtime.budget import PackageBudget, PackageBudgetRequest from engine.runtime.construction import ( AuthorizationKernel, + DecisionProvenanceReceipt, + EgressGate, Runtime, required_kernel_dependencies, ) @@ -35,6 +38,7 @@ _construct_private_delivery_context, ) from engine.runtime.egress import ( + INTERNAL_ONLY_EGRESS_PROFILE, ChannelEgressGrant, ChannelEgressProfile, EgressGrantIssuanceUnavailable, @@ -54,11 +58,13 @@ _observe_current_policy_epoch, _open_policy_epoch_authority_scope, ) +from engine.runtime.scope import ScopeSet, ScopeTarget from tests.support.context_run import ( TEST_QUERY_DIGEST_KEYRING, recording_context_run_session, ) from tests.support.egress import recording_egress_issuance_session +from tests.support.releases import active_runtime_release AS_OF = datetime(2026, 7, 21, 5, 0, tzinfo=UTC) INTERNAL_ORGANIZATION_REF = "81e18bca-86a1-478a-937d-7675c6fe69b0" @@ -100,9 +106,7 @@ def total_calls(self) -> int: def trusted_operands( *, egress_enabled: bool = False, -) -> Iterator[ - tuple[AuthenticatedInvocation, TrustedDeliveryContext] -]: +) -> Iterator[tuple[AuthenticatedInvocation, TrustedDeliveryContext]]: authority_scope = _open_membership_authority_scope() policy_epoch_scope = _open_policy_epoch_authority_scope() @@ -125,9 +129,10 @@ def read_current_epoch(self, organization_id: UUID) -> object: verified_at=AS_OF, ) try: - with recording_context_run_session() as (persistence_session, _), ( - recording_egress_issuance_session() - ) as (egress_session, _): + with ( + recording_context_run_session() as (persistence_session, _), + recording_egress_issuance_session() as (egress_session, _), + ): membership_verification = _construct_current_membership_verification( authority_scope=authority_scope, organization_id=UUID(INTERNAL_ORGANIZATION_REF), @@ -139,6 +144,9 @@ def read_current_epoch(self, organization_id: UUID) -> object: authentication_binding_ref="binding-internal", checked_at=AS_OF, policy_epoch_verification=policy_epoch_verification, + active_runtime_release=active_runtime_release( + UUID(INTERNAL_ORGANIZATION_REF) + ), context_run_persistence_session=persistence_session, egress_grant_issuance_session=( egress_session if egress_enabled else None @@ -238,6 +246,53 @@ def test_runtime_issues_one_model_grant_only_after_final_package_policy() -> Non assert type(outcome.egress_grant) is ModelEgressGrant +def test_final_egress_veto_rejects_package_epoch_that_disagrees_with_actor() -> None: + with trusted_operands() as (invocation, delivery): + outcome = runtime().resolve( + invocation, + delivery, + Acquire(need=ContextNeed(query="reject mismatched final epoch")), + ) + assert type(outcome) is Resolved + package = replace( + outcome.package, + policy_epoch=invocation.policy_epoch + 1, + ) + provenance = DecisionProvenanceReceipt( + decision_ref=package.decision_ref, + package_id=package.package_id, + organization_id=invocation.user_actor.organization_id, + user_id=invocation.user_actor.user_id, + membership_id=invocation.user_actor.membership_id, + membership_version=invocation.user_actor.membership_version, + principal_ref=invocation.principal_ref, + agent_version_ref=invocation.agent_version_ref, + authenticated_application_ref=invocation.authenticated_application_ref, + authentication_binding_ref=invocation.authentication_binding_ref, + effective_scope_digest=outcome.scope_decision.digest, + request_id=invocation.request_id, + purpose=package.purpose, + as_of=package.as_of, + run_ref=package.run_ref, + policy_snapshot_ref=package.policy_snapshot_ref, + policy_epoch=package.policy_epoch, + source_acl_decision_ref="sourceacl_final-egress-epoch-veto", + ) + + with pytest.raises( + EgressGrantIssuanceUnavailable, + match="final egress policy", + ): + EgressGate().finalize( + invocation=invocation, + delivery_context=delivery, + provenance=provenance, + package=package, + profile=INTERNAL_ONLY_EGRESS_PROFILE, + issued_at=package.as_of, + ) + + def test_channel_grant_requires_exact_redeemed_private_destination_and_consumer( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -356,9 +411,9 @@ def test_resolve_returns_one_tenant_safe_empty_package() -> None: assert outcome.kind == "resolved" package = outcome.package - assert package.organization_ref.startswith("orgpkg_") - assert len(package.organization_ref) == len("orgpkg_") + 32 - assert package.organization_ref != INTERNAL_ORGANIZATION_REF + assert package.package_id.startswith("pkg_") + assert len(package.package_id) == len("pkg_") + 32 + assert package.package_id != INTERNAL_ORGANIZATION_REF assert package.purpose == "context.answer" assert package.ttl_seconds == 300 assert package.as_of == AS_OF @@ -389,6 +444,37 @@ def test_empty_path_performs_zero_index_provider_or_source_content_io() -> None: assert spy.total_calls == 0 +def test_missing_active_release_stops_before_nonempty_scope_candidate_io() -> None: + spy = ContentIoSpy() + with trusted_operands() as (invocation, delivery): + target = ScopeTarget( + UUID(INTERNAL_ORGANIZATION_REF), + "source-release-preflight", + "resource-release-preflight", + ) + scope = ScopeSet(frozenset({target})) + for operand_name in ( + "organization_boundary", + "membership_rights", + "principal_grants", + "agent_ceiling", + "source_native_acl", + "resource_acl", + "purpose_policy", + ): + object.__setattr__(invocation.trusted_scope_snapshot, operand_name, scope) + object.__setattr__(invocation.user_actor, "active_runtime_release", None) + + with pytest.raises(RuntimeError, match="active release"): + runtime(spy).resolve( + invocation, + delivery, + Acquire(need=ContextNeed(query="missing release before content")), + ) + + assert spy.total_calls == 0 + + def test_content_io_spy_would_detect_every_runtime_dependency_call() -> None: spy = ContentIoSpy() candidate = runtime(spy) @@ -553,11 +639,11 @@ def test_runtime_issues_closed_fresh_server_refs_without_factory_injection() -> first = first_outcome.package second = second_outcome.package - assert first.organization_ref != second.organization_ref + assert first.package_id != second.package_id assert first.decision_ref != second.decision_ref - assert UUID(INTERNAL_ORGANIZATION_REF).hex not in first.organization_ref + assert UUID(INTERNAL_ORGANIZATION_REF).hex not in first.package_id assert UUID(INTERNAL_ORGANIZATION_REF).hex not in first.decision_ref - assert "organization_ref_factory" not in Runtime.__init__.__annotations__ + assert "package_id_factory" not in Runtime.__init__.__annotations__ assert "decision_ref_factory" not in Runtime.__init__.__annotations__ diff --git a/tests/unit/test_runtime_unavailable_capabilities.py b/tests/unit/test_runtime_unavailable_capabilities.py index b05674ca..c02f4f61 100644 --- a/tests/unit/test_runtime_unavailable_capabilities.py +++ b/tests/unit/test_runtime_unavailable_capabilities.py @@ -71,6 +71,7 @@ TEST_QUERY_DIGEST_KEYRING, recording_context_run_session, ) +from tests.support.releases import active_runtime_release AS_OF = datetime(2026, 7, 21, 10, 0, tzinfo=UTC) ORGANIZATION_ID = UUID("81e18bca-86a1-478a-937d-7675c6fe69b0") @@ -114,6 +115,7 @@ def trusted_operands( epoch_scope = _open_policy_epoch_authority_scope() trusted_scope = _open_scope_authority_scope() try: + class CurrentEpochPort: def read_current_epoch(self, organization_id: UUID) -> object: assert organization_id == ORGANIZATION_ID @@ -126,13 +128,11 @@ def read_current_epoch(self, organization_id: UUID) -> object: port=CurrentEpochPort(), ) ) - organization_verification = ( - _construct_existing_http_organization_verification( - organization_id=ORGANIZATION_ID, - request_id="unavailable-request", - authentication_binding_ref="unavailable-binding", - verified_at=AS_OF, - ) + organization_verification = _construct_existing_http_organization_verification( + organization_id=ORGANIZATION_ID, + request_id="unavailable-request", + authentication_binding_ref="unavailable-binding", + verified_at=AS_OF, ) membership_verification = _construct_current_membership_verification( authority_scope=membership_scope, @@ -145,6 +145,7 @@ def read_current_epoch(self, organization_id: UUID) -> object: authentication_binding_ref="unavailable-binding", checked_at=AS_OF, policy_epoch_verification=epoch_verification, + active_runtime_release=active_runtime_release(ORGANIZATION_ID), context_run_persistence_session=context_run_persistence_session, ) scope_identity = ScopeAuthorityIdentity( @@ -418,8 +419,9 @@ def test_unavailable_request_rejects_forged_runtime_operands_before_minting_outc assert twin.calls == (0, 0, 0) -def test_unavailable_request_runs_runtime_clock_provenance_and_policy_epoch_gate( -) -> None: +def test_unavailable_request_runs_runtime_clock_provenance_and_policy_epoch_gate() -> ( + None +): twin = ContentIoTwin() selected_runtime = runtime(twin) clock_calls = 0 @@ -464,12 +466,16 @@ def test_replacing_the_mandatory_capability_gate_is_rejected_before_io() -> None @pytest.mark.security_evidence(id="PROP-CITATION-AUTH-010", layer="property") -def test_capability_declarations_are_closed_and_m0_does_not_false_green_carriers( -) -> None: +def test_capability_declarations_are_closed_and_m0_does_not_false_green_carriers() -> ( + None +): assert capability_module.__all__ == ["RuntimeCapability"] - assert RuntimeCapabilityDeclaration( - available=frozenset({RuntimeCapability.MATERIALIZED_ACQUIRE}) - ) == M0_RUNTIME_CAPABILITY_DECLARATION + assert ( + RuntimeCapabilityDeclaration( + available=frozenset({RuntimeCapability.MATERIALIZED_ACQUIRE}) + ) + == M0_RUNTIME_CAPABILITY_DECLARATION + ) assert not { RuntimeCapability.CONTINUE, RuntimeCapability.OPEN_CITATION, diff --git a/tests/unit/test_schema_security_manifest.py b/tests/unit/test_schema_security_manifest.py index 4deeff16..dc2f4a7d 100644 --- a/tests/unit/test_schema_security_manifest.py +++ b/tests/unit/test_schema_security_manifest.py @@ -183,9 +183,12 @@ def test_issue_24_structural_markdown_contract_is_versioned_and_function_only() ], } structural_function = "EXECUTE context_worker_publish_structural_file_import_v2" - assert structural_function in entries["file_revision_snapshot"][ - "permittedOperations" - ]["context_engine_worker"] + assert ( + structural_function + in entries["file_revision_snapshot"]["permittedOperations"][ + "context_engine_worker" + ] + ) recovery_steps = { "EXECUTE context_worker_acquire_file_publication", "EXECUTE context_worker_prepare_file_publication", @@ -285,9 +288,7 @@ def test_issue_26_file_replacement_contract_is_staged_and_function_only() -> Non assert operation["stageDatabaseFunctions"] == { "markdown-config-v1": "context_worker_stage_file_replacement", - "markdown-config-v2": ( - "context_worker_stage_structural_file_replacement" - ), + "markdown-config-v2": ("context_worker_stage_structural_file_replacement"), } assert operation["activateDatabaseFunction"] == ( "context_worker_activate_file_replacement" @@ -315,13 +316,12 @@ def test_issue_26_file_replacement_contract_is_staged_and_function_only() -> Non assert stage_functions <= set( entries[table]["functionOnlyMutation"]["databaseFunctions"] ) - assert { - f"EXECUTE {function}" for function in stage_functions - } <= set(entries[table]["permittedOperations"]["context_engine_worker"]) + assert {f"EXECUTE {function}" for function in stage_functions} <= set( + entries[table]["permittedOperations"]["context_engine_worker"] + ) assert operation["directTableMutationAllowed"] is False assert operation["retention"] == ( - "superseded Revisions remain immutable and " - "retained_until_explicit_cleanup" + "superseded Revisions remain immutable and retained_until_explicit_cleanup" ) plan = entries["file_revision_replacement_plan"] @@ -372,9 +372,9 @@ def test_issue_27_file_recovery_contract_is_generation_fenced_and_auditable() -> "content_identity_digest", "publication_payload_digest", ] - assert "context_worker_issue_file_import_lease" not in operation[ - "databaseFunctions" - ] + assert ( + "context_worker_issue_file_import_lease" not in operation["databaseFunctions"] + ) assert lease_issue["atomicWrites"] == [ "file_import_job", "file_import_job_event", @@ -407,9 +407,7 @@ def test_issue_27_file_recovery_contract_is_generation_fenced_and_auditable() -> assert database_function in causal assert ( f"EXECUTE {database_function}" - in entries[table_name]["permittedOperations"][ - "context_engine_worker" - ] + in entries[table_name]["permittedOperations"]["context_engine_worker"] ) @@ -512,12 +510,8 @@ def test_issue_30_file_source_offboarding_is_atomic_and_function_only() -> None: if value["name"] == "offboard_file_source" ) - assert operation["databaseFunction"] == ( - "context_control_offboard_file_source" - ) - assert operation["definerRole"] == ( - "context_engine_access_policy_definer" - ) + assert operation["databaseFunction"] == ("context_control_offboard_file_source") + assert operation["definerRole"] == ("context_engine_access_policy_definer") assert operation["directTableMutationAllowed"] is False assert operation["idempotencyBinding"] == ["organization_id", "source_id"] assert operation["atomicWrites"] == [ @@ -554,17 +548,15 @@ def test_issue_30_file_source_offboarding_is_atomic_and_function_only() -> None: "physicalCleanupCompletion": "not active in Issue #30", "sourceContent": "none", } - assert entries["context_source"]["permittedOperations"][ - "context_engine_runtime" - ] == [] + assert ( + entries["context_source"]["permittedOperations"]["context_engine_runtime"] == [] + ) resource_policy = next( policy for policy in entries["context_resource"]["rowLevelSecurity"]["policies"] if policy["name"] == "context_resource_current_user_actor" ) - assert "context_runtime_file_source_lifecycle_allows" in ( - resource_policy["using"] - ) + assert "context_runtime_file_source_lifecycle_allows" in (resource_policy["using"]) for policy in entries["file_import_job"]["rowLevelSecurity"]["policies"]: if policy["roles"] == ["context_engine_worker_lease_definer"] and ( policy["command"] in {"SELECT", "UPDATE"} @@ -773,6 +765,7 @@ def test_issue_19_lineage_manifest_is_closed_and_role_separated() -> None: "context-query-json-hmac-sha256-v1", "context-package-canonical-json-v1", "context-package-canonical-json-v2", + "context-package-canonical-json-v3", "digest_only", "delivered_authorized", "delivered_empty", @@ -1752,12 +1745,8 @@ def test_policy_epoch_manifest_seals_runtime_reads_and_control_mutation() -> Non "context_engine_worker": [], } if entry["name"] == "organization_policy_epoch": - expected_operations[ - "context_engine_delivery_evidence_definer" - ] = ["SELECT"] - expected_operations["context_engine_egress_grant_definer"] = [ - "SELECT" - ] + expected_operations["context_engine_delivery_evidence_definer"] = ["SELECT"] + expected_operations["context_engine_egress_grant_definer"] = ["SELECT"] expected_operations["context_engine_control"].append( "EXECUTE context_control_tombstone_file_resource" ) @@ -2142,9 +2131,44 @@ def test_release_force_rls_and_grants_match_the_promotion_boundary() -> None: assert definer_policy["using"] == definer_policy["withCheck"] assert "app.organization_id" in definer_policy["using"] assert entry["permittedOperations"]["context_engine_control"] == [] - assert entry["permittedOperations"]["context_engine_runtime"] == [] + assert entry["permittedOperations"]["context_engine_runtime"] == ( + ["SELECT"] + if name in {"release_manifest", "active_release_manifest"} + else [] + ) assert entry["permittedOperations"]["context_engine_worker"] == [] assert entry["permittedOperations"]["context_engine_security_operator"] == [] + runtime_policies = [ + policy + for policy in rls["policies"] + if policy["roles"] == ["context_engine_runtime"] + ] + if name in {"release_manifest", "active_release_manifest"}: + assert len(runtime_policies) == 1 + runtime_policy = runtime_policies[0] + assert runtime_policy["name"] == f"{name}_runtime_select" + assert runtime_policy["command"] == "SELECT" + assert runtime_policy["roles"] == ["context_engine_runtime"] + using = runtime_policy["using"] + assert f"{name}.organization_id" in using + for required_boundary in ( + "app.organization_id", + "app.actor_kind", + "app.user_id", + "app.membership_id", + "app.membership_version", + "app.principal_ref", + "app.request_id", + "app.authentication_binding_ref", + "app.checked_at", + "public.membership", + "status = 'active'", + "valid_from", + "valid_until", + ): + assert required_boundary in using + else: + assert runtime_policies == [] if name in lineage_names: learning_policies = { diff --git a/tests/unit/test_ticket_audience_separation.py b/tests/unit/test_ticket_audience_separation.py index 37e97394..030d0ca8 100644 --- a/tests/unit/test_ticket_audience_separation.py +++ b/tests/unit/test_ticket_audience_separation.py @@ -61,6 +61,7 @@ TicketRejectionAuditReceipt, TicketRejectionCategory, ) +from tests.support.releases import active_runtime_release from tests.support.security_gate import record_security_oracles NOW = datetime(2026, 7, 22, 8, 0, tzinfo=UTC) @@ -84,10 +85,8 @@ def _decode_ticket(value: str) -> tuple[dict[str, object], dict[str, object]]: def _flip_one_ascii_bit(value: str) -> str: for index, character in enumerate(value): replacement = chr(ord(character) ^ 1) - if replacement.isascii() and ( - replacement.isalnum() or replacement in "-_" - ): - return f"{value[:index]}{replacement}{value[index + 1:]}" + if replacement.isascii() and (replacement.isalnum() or replacement in "-_"): + return f"{value[:index]}{replacement}{value[index + 1 :]}" raise AssertionError("fixture has no base64url character with a safe bit peer") @@ -224,6 +223,7 @@ def _trusted_inputs( authentication_binding_ref="binding-a", checked_at=NOW, policy_epoch_verification=epoch, + active_runtime_release=active_runtime_release(organization_id), ) try: scope_identity = ScopeAuthorityIdentity( @@ -453,8 +453,7 @@ def test_mismatched_trusted_invocation_and_delivery_cannot_build_identity() -> N ) -def test_signed_ticket_schemas_bind_distinct_domains_audiences_and_identity( -) -> None: +def test_signed_ticket_schemas_bind_distinct_domains_audiences_and_identity() -> None: with _identity() as identity: read_ticket = ContextAccessTicketIssuer( keyring=KEYRING, @@ -552,8 +551,7 @@ def test_pre_source_binding_ticket_remains_only_an_unbound_synthetic_ticket() -> assert provider.effects == 1 -def test_ticket_targets_are_bound_to_a_trusted_organization_configuration( -) -> None: +def test_ticket_targets_are_bound_to_a_trusted_organization_configuration() -> None: other_organization = UUID("115f61f7-9006-44ba-bd82-d395c3bc57df") provider = _Provider() channel = _Channel() @@ -633,8 +631,7 @@ def test_forged_exact_identity_is_normalized_before_any_effect() -> None: @pytest.mark.security_evidence(id="RUNTIME-ACTION-SEPARATION-014", layer="runtime") -def test_each_ticket_is_rejected_by_the_other_plane_and_deserializer( -) -> None: +def test_each_ticket_is_rejected_by_the_other_plane_and_deserializer() -> None: provider = _Provider() channel = _Channel() @@ -678,9 +675,7 @@ def test_each_ticket_is_rejected_by_the_other_plane_and_deserializer( lambda: ContextAccessTicket.deserialize( action_ticket.serialize(), keyring=KEYRING ), - lambda: ActionTicket.deserialize( - read_ticket.serialize(), keyring=KEYRING - ), + lambda: ActionTicket.deserialize(read_ticket.serialize(), keyring=KEYRING), ) rejections: list[TicketNotAvailable] = [] for rejected_use in rejected_uses: @@ -764,9 +759,7 @@ def test_one_bit_tamper_in_each_signed_segment_is_rejected_before_effect( ).issue(identity) read_segments = read_ticket.serialize().split(".") action_segments = action_ticket.serialize().split(".") - read_segments[segment_index] = _flip_one_ascii_bit( - read_segments[segment_index] - ) + read_segments[segment_index] = _flip_one_ascii_bit(read_segments[segment_index]) action_segments[segment_index] = _flip_one_ascii_bit( action_segments[segment_index] ) @@ -1038,8 +1031,7 @@ def test_deep_validly_signed_json_is_normalized_before_effect() -> None: assert provider.effects == 0 -def test_tickets_for_target_a_or_at_expiry_are_rejected_at_target_b( -) -> None: +def test_tickets_for_target_a_or_at_expiry_are_rejected_at_target_b() -> None: provider_b = _Provider() channel_b = _Channel() @@ -1114,8 +1106,7 @@ def test_ticket_rejection_is_one_closed_non_enumerating_result() -> None: TicketRejectionAuditReceipt(denied_detail_count=1) # type: ignore[arg-type] -def test_public_ticket_authority_objects_are_redacted_and_not_serializable( -) -> None: +def test_public_ticket_authority_objects_are_redacted_and_not_serializable() -> None: with _identity() as identity: read_ticket = ContextAccessTicketIssuer( keyring=KEYRING,