Status: Active Derives from: ADR-0070 Owned Tenant BFF Sessions, ADR-0033 Audit Durability Model (supersedes ADR-0016, which remains the subsystem's context), ADR-0044 The Audit Write Path, ADR-0017 Tenant + Organization Hierarchy, 11-security.md § Audit Log, 01-architecture-standards.md. Producer additions derive from ADR-0057. Delivery/recovery additions derive from ADR-0046. Authenticated assertion admission derives from ADR-0065; its implementation and local proofs are delivered in the remediation record. Job additions derive from ADR-0047 (accepted 2026-10-15; P02b-4 runtime and enforcement implemented; the phase status owns hosted qualification). Global identity creation and contextual foundation authority derive from Accepted ADR-0072 and ADR-0073. Live authorization evidence derives from jointly Accepted ADR-0076 and ADR-0077. The phase Status block owns qualification. Native entry/administration and replay additions derive from jointly Accepted ADR-0078 and ADR-0079. The internal fixed-seed prerequisite boundary additionally derives from ADR-0080. The separate fixed-origin completion purpose derives from ADR-0081. Invitation grant, policy and automatic submission additions derive from ADR-0093; its new consumers remain planned until implemented.
This standard defines which operations must be audited, what an audit entry
contains, how long entries are retained, and how each module signs up for its
own coverage. The AuditEntry aggregate itself is defined in
02-domain-model.md § Audit and the subsystem deep
dive is in 31-audit-subsystem.md; this
document is the rule that prevents the audit story from drifting.
- A breach investigator or regulator should be able to answer "who did what, to which resource, when, from where, with what outcome" for every meaningful state change.
- If omitting an audit entry would embarrass a compliance officer, it MUST be audited.
- Audit entries are append-only and immutable. Ordinary entries are tenant-scoped;
the global identity creation class is the separately
admitted sentinel population beside platform-scope rows.
audit_logis org-scoped, and the row's organization is the one the ambient context announced:AuditIntentcarriesTenantIdandOrganizationId?, both resolved byAuditLogBehaviorat step 3 (ADR-0044 Amendment 3 § 2) — which is before the handler runs, so it is the request's organization and never one read back off the resource. Entries are queryable by tenant admins for their own tenant, and by org admins for their own organization (ADR-0017). - Every module owns a Resource × Operation classification table for its resources — the audit verb is not the permission action (ADR-0044 § 6). The matrix is reviewed when the module is built and again when it is extended.
- Coverage is configured in the catalog (
AuditConfigper-tenant override of the module/operation MUST/SHOULD/MAY mapping) and enforced by the MediatRAuditLogBehaviorfor requests. Accepted ADR-0057 gives non-MediatR owners the same classification/entry lifecycle through the reusable coordinator. Modules never callIAuditStoredirectly.
Tenant BFF exception — ADR-0070, Accepted 2026-10-23. Provider authentication events are stored by the tenant development Keycloak realm under Security 11, not written through a new LearnStack session-audit API. Local expiry, unreceived refresh and local logout during provider outage have only closed lifecycle diagnostics. Retained provider facts use the ADR-0097 mirror, not invented local-session facts. This explicitly scopes the generic login/token-revocation examples below; no durable local BFF ledger or atomic provider/BFF commit is promised. Existing LearnStack MUST operations, baseline coverage and tenant override limits remain unchanged. Seven-day development provider retention is not the application's security-event retention.
ADR-0098 includes native notification accepted/duplicate/refused/unavailable within the existing Tenant BFF exception above: closed local diagnostics only, no new durable operation, session ledger or atomic provider/BFF commit. The retained provider mirror remains independent; no tenant is invented for ACKs. Keep bridge transport outcomes distinct from native token-processing outcomes using a closed boundary label. Structural, capacity and failed native-forwarding paths retain their own refused/unavailable evidence without raw request or error values; a forwarded 200 does not count as a second native token acceptance.
This standard uses OperationType to mean what kind of operation produced the
audit row — distinct from OperationClass in ADR-0016,
which carries the MUST/SHOULD/MAY audit-coverage tier. Both fields live on
AuditEntry (see 31-audit-subsystem.md).
| OperationType | Meaning | Default audit classification (OperationClass) |
|---|---|---|
create |
New aggregate row written | SHOULD |
update |
Existing aggregate mutated | MUST when status, permission, money, content-publication, or consent fields change |
delete |
Aggregate removed or soft-deleted | MUST |
read-sensitive |
Read of another user's PII, financial data, learner progress, recording, or consent state | MUST |
security-event |
Login, MFA challenge, role grant/revoke, permission change, tenant impersonation, token revocation, RLS bypass | MUST |
platform-admin |
Any operation performed by a platform admin against a tenant they are not a member of | MUST |
action |
A genuine in-tenant non-CRUD act that fits none of the rows above — recording start where no consent state changes is the example ADR-0016's 2026-05-19 amendment gives | SHOULD, unless § Baseline Coverage names the operation |
platform-admin does not subsume action.
ADR-0016's 2026-05-19 amendment adds platform-admin
beside action — "the Action value remains for genuine in-tenant non-CRUD
actions" — and calls the resulting seven-member enum binding. The table above is the
catalogue that enum is compared against by
OperationType_Enum_Matches_Catalog,
so a member missing from either side fails the build; adding an eighth type is a change
to this table first.
The row labels above are documentation slugs, not the stored value. What reaches
audit_log.operation_type — and what the audit query API accepts and returns — is the
C# enum member name: ReadSensitive for read-sensitive, SecurityEvent for
security-event. operation_class stores Must / Should / May the same way. That is
the relationship the shipped ck_tenants_status already has to TenantStatus, and it is
why neither column needs a custom value converter. OperationType_Enum_Matches_Catalog
compares members, not spellings. outcome is the one closed set that does not follow this
rule: ADR-0044 § 5 fixes its four values in
lowercase and puts them in the column's CHECK.
read-sensitive is not "any GET request" — it's the read paths a regulator would ask about. Examples: guardian viewing a student's grades; instructor exporting a class roster with PII; admin viewing learner email list; admin downloading a recording.
Every module ships this table in its module spec under docs/modules/<module>/audit.md (or equivalent). The matrix is part of the module's PR; reviewers refuse merges without it. The docs/modules/ directory was created with the first module spec — Tenancy, in Phase 02a Packet 6.
One row per audited resource — or one row per group of its operations that share a
class and a reason, the Operation cell then carrying each of their slugs separated by
/. That grammar is permitted, and the parser reads every slug in a cell; the three
shipped matrices — Tenancy,
Customization and Audit
— use its one-slug-per-row form:
| Resource | Operation | Class | Why |
|---|---|---|---|
ResourceA |
module.resource_a.create |
MUST | What the row lets a reader reconstruct |
ResourceA |
module.resource_a.rename |
SHOULD | Presentational |
ResourceB |
module.resource_b.archive / module.resource_b.soft_delete |
MUST | Deletes are always MUST, and two operations that share a class and a reason share a row |
ResourceC |
module.resource_c.publish (planned) |
MUST | Classified ahead of the command that will raise it; the marker is what scopes the join |
Legend: MUST = audit entry required for every admitted event. General mutation coverage admits every classified occurrence. The only bounded assertion-admission exception is stated in § Baseline Coverage below. SHOULD = audit by default; module may justify an opt-out per-operation. MAY = audit is allowed but not required. – = operation does not apply.
The Operation cell carries catalogue slugs, plus the (planned) and (off-path)
markers § The join below defines
(ADR-0044 § 6 and Amendment 3 § 1):
- The slug is
{module}.{resource}.{verb}—tenancy.tenant.create,customization.content_type.publish. It borrows the shape of a permission key from 19-permissions.md — three segments, lowercase, singular resource, snake_case inside a segment — and its first two segments match the permission key that gates the same resource. That is the part a cross-reference needs, and the only part required to match. - The third segment is not the permission action set. Permissions close at
read | write | delete | admin; audit verbs come from this matrix —create,publish,revise,rename,soft_delete,toggle— because a permission bounds what a principal may do and an audit operation records what happened. A closed set would record a rename and a publication as onewrite. - No domain terms, in any segment (ADR-0018).
The matrix is the prose artifact; the catalogue is the executable one. Each module
registers its defaults in code through IAuditCatalogSource.Describe(IAuditCatalogBuilder),
discovered from DI and keyed by request type, mapping one request type to one or more
(operation, OperationType, OperationClass) triples. Neither artifact is parsed from the
other, and
Every_TenantOwned_Command_HasAuditCoverage
joins them catalogue → matrix and
Every_Matrix_Row_Whose_Command_Exists_Is_Registered
matrix → catalogue, each reading a cell as the list of slugs it holds. Neither can see a
request type nobody registered when another request shares its slug, which is why
Every_Shipped_Request_Is_Registered
asks the catalogue for every request type with a handler and every concrete
integration-event handler type, including Off coordinators. Two handlers for
one event are two subjects; classifying the shared event type covers neither.
P02b-3 Step 6 checks both API and Seeder catalogues against fail-loud discovery
and an omitted-Off control whose operation entries remain unchanged. A module
with only integration handlers still requires its own matrix.
It has two directions, and they have different domains (ADR-0044 Amendment 3 § 1). A single rule reading "a matrix row with no catalogue entry fails, and a catalogue entry with no matrix row fails" is unsatisfiable while a module classifies operations ahead of the commands that will raise them — which this standard requires it to do.
- Catalogue → matrix is total. Every entry a module's
IAuditCatalogSourceregisters has a row in that module's matrix carrying the same slug — that module's, and no other's. There is no exemption: shipped code auditing an operation no matrix classifies is the drift worth failing a build over, and adding the row always satisfies it. Aplatform.*operation has no module of its own, so its one row sits in the matrix of the module that writes it — Tenancy's, forplatform.admin_scope.enter. Test-only request types register in their own fixtures rather than in a module source, and are outside this direction. - Matrix → catalogue binds to what exists. A matrix row fails only when a request type
that raises it exists and no catalogue entry names it. A row classified ahead of its
command is not drift; it carries
(planned)in theOperationcell beside its slug. (planned)is re-checked, not an escape. A row still marked(planned)whose command has since shipped fails. The marker is a claim the rule tests on every run, which is what stops the scoping from becoming a hole.(off-path)is for operations that are not MediatR requests at all. These sit outside the request-type join in both directions and register by slug throughDeclareOffPathwhen their writer ships. The module matrices own the population, including platform entry/terminal operations, assertion events, global identity creation and privileged Audit maintenance. P03-2 Step 4 registers authorization-denial and claim-context assertion events beside their central writers; API/application composition supplies their trusted sources.- One operation, one row. A slug is classified in exactly one row across every matrix. A copy is a second answer that passes every comparison the moment it agrees, so the matrix → catalogue direction refuses it, and the catalogue → matrix direction compares every row that carries a slug rather than the first.
- A row can carry both markers.
tenancy.entitlement.refreshis(off-path)because its writer is a port method rather than a request, and(planned)because no real provider exists yet.tenancy.killswitch.togglecarried both until P03-9 Step 1 shipped its writer (ADR-0101 § 13); it keeps(off-path)because the write runs inside the platform scope rather than through the pipeline. The controlled issuer rebind's two rows,identity.authority.rebind_attemptandidentity.authority.rebind(ADR-0104 § 8), are(off-path)for the same reason one step further: they are written by an offline tool on its own role through two witness-bound methods, under the platform sentinel, with no actor and the ticket inmetadata.operator. The operator recovery operations of ADR-0103 are(off-path)too:platform.delivery.inspectis the admitted operation whose reasondelivery_inspectthe platform scope's entry row carries, andplatform.delivery.replayandplatform.delivery.resetare written on the dispatcher's outbox-role transaction through one witness-bound method, under the real event tenant, with no actor, the operator attribution and the fence inmetadata, and no ticket, because a tenant can read the row. The operator federation operations of ADR-0099 Amendment 10 and 11 are(off-path)as well:platform.federation.reportis audited by the platform scope's entry row, andplatform.federation.removeandplatform.federation.disableeach write an intent row on their_attemptslug at the scope handle's checkpoint, with the outcomeindeterminate, committed before the provider call (ADR-0044 Amendment 18), and a completion row on their own slug. Both rows name the tenant the owner marker names and carry no ticket and no tenant-authored text.
The following operations are MUST-audit across LearnStack regardless of which
module owns them. Module matrices and tenant AuditConfig overrides cannot
remove anything in this list. ADR-0065
names a narrow event-admission exception for authenticated rejected assertions:
600 standalone write attempts per independently defended host tenant per API
instance per first-request-anchored monotonic minute, shared across actors,
subjects, dimensions and sources. Every admitted event remains MUST-class and
failed writes consume allowance. Suppressed occurrences retain their refusal,
mismatch counter and one attributed Warning, with no audit-store I/O. No tenant
configuration overrides this budget. Anonymous bursts and tenantless refusals
retain their separate contracts; general mutation MUST durability is unchanged.
An attacker may exhaust the shared allowance, so later actors can have no durable
record for that window. Real-time log volume remains unbounded. ADR-0065 owns the
explicit evidence-loss and illustrative capacity costs; acceptance alone does
not prove implementation or production fit.
| Domain | MUST-audit operation |
|---|---|
| Identity | Membership created / removed (per (user_id, tenant_id, organization_id)); role assigned / revoked; permission set changed; protected-act authorization denied under trusted resolved tenant (identity.authorization.deny, ADR-0077); invitation created / reissued / accepted / revoked and its consequential email preparation/submission outcome (ADR-0093); platform-admin tenant access; Hub operator access to a tenant resource. |
| Tenancy | Tenant created / suspended / deleted; organization created / archived; tenant setting changed; custom domain added / verified / removed; feature flag toggled; entitlement projection refresh (tenancy.entitlement.refresh); killswitch toggled (tenancy.killswitch.toggle). |
| Customization | TenantContentType / TenantPageBlock / TenantLessonItemType / TenantLevelTaxonomy / TenantScoringRule / TenantCompletionRule / TenantCustomFieldDef / TenantTemplateLibrary created / updated / deleted (schema changes are MUST; both before and after snapshots required). |
| Content / Pages | Page published / unpublished; content type schema changed; redirect created / changed. |
| Catalog / Learning | Course published / unpublished; CourseVersion published; lesson item replaced post-publish. |
| Enrollment | Enrollment created / suspended / cancelled / completed; entitlement granted / revoked. |
| Assessment | Attempt graded; score published; question added/removed from a published assessment. |
| Scheduling | LiveSession scheduled / rescheduled / cancelled; booking created / cancelled. |
| Classroom | Room opened / ended; participant joined / left (security-event); join token issued; consent state changed. |
| Recording | Recording started / stopped; recording downloaded; retention policy changed; legal hold applied / removed. |
| Billing | Order paid / refunded; subscription created / cancelled; payment provider account changed. |
| Hub contract | Inbound Hub command received (tenancy.tenant.create_from_hub, and the entitlement push, which is the Tenancy row's tenancy.entitlement.refresh — one operation, one slug); outbound usage report (platform.usage.report); license verification result. |
| Notifications | Template changed; outbound delivery to a recipient (SHOULD for non-PII channels; MUST for password reset / invitation / billing). ADR-0093's bounded P03-4 invitation submission belongs to Identity before the Phase 08a notification engine; no new module or second audit owner is implied. |
| Integrations | External provider credential created / rotated / revoked; webhook secret rotated. |
| Security | Login failure burst beyond rate limit; MFA challenge failed; admin override of any guard; mTLS / signed-JWT / HMAC verification failure on /api/internal/*; admitted cross-tenant assertion mismatch carrying a validated principal (tenancy.tenant_assertion.reject, bounded admission under ADR-0065); anonymous assertion-mismatch burst beyond threshold (tenancy.tenant_assertion.anonymous_burst); a header conflicting with successfully confirmed ClaimAndMembership context (tenancy.assertion.reject_claim_context, ADR-0077; no host allowance). |
There are no vertical modules. Tenant-specific extensions land as data via the Customization aggregates and inherit the MUST-audit rules above for schema changes.
The example illustrates ordinary audit fields; it is not an HTTP response DTO or a caller-authored draft. The mapping rules below and the trusted provenance contract govern persisted fields and enrichment; their implementation state is explicit.
{
"id": "01H...",
"occurredAt": "2026-05-18T12:34:56.789Z",
"tenantId": "ten_01H...",
"organizationId": "org_01H...",
"actor": {
"userId": "usr_01J..."
},
"operation": {
"key": "enrollment.enrollment.create",
"module": "enrollment",
"resource": "Enrollment",
"resourceId": "enr_01K...",
"operationType": "Create",
"class": "Must"
},
"request": {
"correlationId": "01H...",
"sourceIp": "203.0.113.4",
"userAgent": "Mozilla/5.0 ..."
},
"outcome": "success",
"before": null,
"after": { "courseVersionId": "...", "userId": "...", "status": "active" },
"changes": [
{ "path": "/Enrollment/status", "before": null, "after": "active" }
],
"reason": null,
"metadata": null
}Rules:
beforeandafterare mandatory forupdateon permission, money, content-publication, recording-policy, and consent fields. Snapshots are JSON, redacted for PII fields the module marks as[PiiSensitive].operation.keyis the catalogue slug of § Classification Matrix Template, andoperation.classis the MUST / SHOULD / MAY tier — not a repeat ofoperationType, which carries one of the seven values of § Operation Types. Both render as the enum member name on the wire and in the column, which is why the example above readsCreateandMustwhere the tables readcreateand MUST.outcomeis one ofsuccess,denied,failed,indeterminate(ADR-0044 § 5; ADR-0016'sis_success booleanis superseded, because a boolean cannot carrydenied).deniedis used when an authorisation check rejects the operation — these MUST be audited so we can detect probing. A Platform operator admission refusal is tenantless and outside that population: it leaves a counter and a Warning log (ADR-0101 § 11), and an authorization refusal of an operator act inside the pipeline leaves a countedrefusedoutcome and a Warning, event 7109, with no durable row (ADR-0033 Amendment 14). A business refusal of an admitted operator act writes the ordinaryfailedrow in the target tenant, withactor_user_idNULL, the closed reason slug andmetadata.operator.indeterminateis the commit whose server-side outcome is unknown: the standalone re-write carries the sameidas the in-transaction attempt, and the pair is what a reviewer reads as one commit in doubt.PostgresAuditStoresuppliesoccurredAtfromIClock— the intent's declaration time in the transaction, a fresh reading for a standalone re-write — which is what keeps that pair legal under the composite primary key(id, timestamp). This describes ordinary resource reconciliation; trusted denial occurrences instead retain one fixed key, timestamp and draft.reasonis required when the operator is a platform admin acting on a tenant they are not a member of. It is the closed reason slug of the registered operator operation (PlatformOperation.ReasonSlug) — never caller-supplied text — and it is surfaced in the tenant admin's audit view when the row targets that tenant. Rows under the platform sentinel are visible to no tenant (ADR-0101 § 9, § 10). A refusal's cause is not areason: it is the refusal's message key, in theerror_keycolumn.correlationIdmatches the trace id in logs and the value in the Problem Details response for failures.changesis always a JSON array of{ path, before, after }, never the polymorphic object-or-array shape ADR-0016 described. A reader that has to branch on the shape gets it wrong once.pathis instance-qualified —/{EntityType}/{EntityId}and then an RFC 6901 pointer into that instance's snapshot,/TenantLevelTaxonomy/0190…/Items/b2/DisplayName— because one row can carry two instances of a type: a publication records the successor it activated and the incumbent it retired (ADR-0044 Amendment 6 § 5).- One row is about one instance.
entity_id,before_stateandafter_statedescribe the operation's subject. A handler that writes two instances of the aggregate its operation declares names the subject throughIAuditSubject.Designate, and the other instance stays inchanges; undesignated, the pair is refused rather than guessed between. An entity contained by its aggregate — a band in a taxonomy — is recorded in the aggregate's row, not in one of its own (ADR-0044 Amendment 6 §§ 1, 4). - A module that holds a PII column names it in that module's audit spec. The pipeline
redacts rather than strips: a property marked
[PiiSensitive], or matched by the shippedSensitiveTokenCatalog, keeps its place inbefore,afterandchangesand loses its value toSensitiveTokenCatalog.RedactedValue, so the diff still records that it changed. Name the constant, never the string: the shipped value is***REDACTED***. - Not every field above is a column. The
audit_logDDL (31-audit-subsystem.md § 7) carriesoccurredAtastimestamp,resource/resourceIdasentity_type/entity_id,sourceIpasip_address, andoperation.keyasoperation. Membership/Role references, privileged flags and route identity have no column of their own. The composer keeps email null. Its central owner attaches bounded trusted provenance undermetadata.authorization, with IP/user agent in their existing columns. An exact invocation binds its own resource frame; a direct inner act without a new frame cannot replace its parent's context, while a fresh post-lock recheck of that same act can update it. The canonical evidence rules below define its sources and limits.
-
One global
audit_logtable. Phase 02a Packet 9 ships it plain and unpartitioned; monthly partitioning bytimestamp— the column's name in ADR-0033's DDL — the retention job and the lifecycle policy of ADR-0028 arrive in Phase 11. "Monthly from day one" was the earlier plan and ADR-0033 changed it: PostgreSQL has noALTER TABLE … PARTITION BY, so the conversion is a new table either way, and partitioning on day one would force every partition-key column into the primary key before the schema that shape has to serve exists. The policy shape is the same in both. -
Table class and chain.
audit_logis tenant-owned, org-scoped. Its ordinary tenant/org policy semantics come from Database Standards § Tenant-Owned and Organization-Scoped Tables with the accepted global identity branch, implemented in Step 3. The reusable template stays unchanged; the applied audit policy includes only the qualified global extension.audit_configis tenant-owned, tenant-wide: it has noorganization_id, so it takes the same shape with the organization half omitted and no restrictive guards — there is no organization to guard (ADR-0044 Amendment 1). No document hand-writes either a second time. They ship in a fourth migration chain owned byLearnStack.Modules.Audit.Infrastructure'sAuditDbContext.audit_logcarries no foreign key totenants: the platform sentinel has notenantsrow by construction, and the record of what happened to a tenant has to outlive the tenant.audit_configkeeps its FK — it is live configuration, not history (ADR-0044 § 9). -
Append-only, enforced in three layers, each stopping a different actor — measured on PostgreSQL 18.6 (ADR-0044 § 9):
- The grant.
learnstack_appholdsSELECT, INSERTonaudit_logand nothing else, so anUPDATEorDELETEfrom the runtime role raises42501before any policy or trigger runs. Onaudit_configboth roles holdSELECTonly. - The column-level grant.
learnstack_platformholdsSELECT, INSERT, DELETEandUPDATE (actor_email, ip_address, user_agent, before_state, after_state, changes), so anUPDATEtouching any other column is refused by the grant, before the trigger runs. - The trigger. The table owner holds every privilege implicitly, and under
FORCEthe policy constrains it by tenant rather than by immutability — measured: an ownerUPDATEreturnsUPDATE 0with no tenant announced andUPDATE 1with one.audit_log_append_only_guardis the only layer that bindslearnstack_migration. It is not redundant with the grant — it is what stops the one actor the grants cannot.
The aggregate carries its own half:
AuditEntryinheritsEntity<TId>notAuditableEntity<T>and exposes no mutators, andIAuditStorehas no update method (its fourth write method is a different thing — see § Required Behaviours). Exactly two mutating paths exist, both owned by the Audit module, both running aslearnstack_platformthrough the auditedEnterPlatformAdminScope(reason)path:- GDPR redaction — an
UPDATEthat may change onlyactor_email,ip_address,user_agent,before_state,after_stateandchanges. The trigger rejects anUPDATEaltering any other column, includingactor_user_id,operation,outcomeandtimestamp. - Retention purge — a
DELETEof rows past their tenant's and class's retention. It stays a row-levelDELETEafter Phase 11 partitioning: one monthly partition holds many tenants and several retention classes, so a partition cannot be dropped while any row in it is still inside its window. Dropping a whole partition is the separate partition-management job, and only past the platform's maximum retention (ADR-0028).
A rule that forbade every
UPDATEandDELETEwould have made both shipped-by-design paths unimplementable. See 31-audit-subsystem.md § 7 Data model → Append-only enforcement for the trigger and § 10 for the redaction path. - The grant.
-
Tenant admins query their own tenant's entries through a paginated, indexed view. Org admins additionally filter by
organization_id. Platform admins query across tenants through a separate read role. Hub operators are platform admins from this surface's perspective and their reads are themselves audited. -
The audit log is never the source of truth for application state; downstream consumers project from integration events, not from audit entries.
-
Snapshots are bounded, never silently truncated. Each of
before_state,after_stateandchangesis capped independently atJsonValue.MaxRowBytes(256 KiB). Above the cap the value becomes an explicit elision record —{"_elided": true, "bytes": <n>, "sha256": "<hex>"}— which preserves the column's JSON type: an elidedchangesis[{"_elided": …}], an elidedbefore_stateorafter_stateis the object form, so a reader parses one contract either side of the cap. There is no external blob pointer (ADR-0044 § 8). -
Capture pipeline — decide → write → reconcile (ADR-0033, ADR-0044):
AuditLogBehavior(step 3) classifies and declares one MUST-class intent per audited(resource, operation)inIAuditStateCapture's ordered list —ProvisionTenantCommanddeclares two;AuditChangeTrackerInterceptorsnapshots eachSaveChangesinto the same buffer and writes nothing; the transaction owner drains successful domain events and checks producer invariants before callingIAuditStore.WritePendingAsyncimmediately beforeCOMMIT, inserting every pending intent as a complete row on the ambient transaction, and then records whether the commit succeeded;AuditLogBehaviorreconciles on the way out, re-writing standalone whichever rows the transaction did not carry. Only the owning unit-of-work frame (IUnitOfWorkScope.IsOwner) writes pending MUST rows, reports the commit boundary and cleans up domain-event collector/source state; a joiner does none of the three, because a joiner that reportedCommittedwould claim durability for a row nothing has committed and a joiner that cleared domain events would erase the owner's work. Only the outermostAuditExecutionCoordinatorframe reconciles standalone rows and callsIAuditStateCapture.Clear(). Accepted ADR-0057 separates audit ownership from per-invocation producer receipts. A controlled direct owner proves common entry in P02b-1; production delivery opens it before handler construction in P02b-3 under ADR-0046, refuses an unregistered mutating handler and declares direct one-root intents. Nested commands keep their own intents without a duplicate business row. Modules see none of this plumbing; the MUST floor and standalone refusal posture survive. -
The interceptor captures every
ChangeTrackerentry in stateAdded,ModifiedorDeleted, minus a named exclusion list —OutboxMessage,IdempotencyKey,InboxMessageandEventDelivery(machinery) andAuditEntry/AuditConfig(the audit tables themselves; ADR-0044 Amendment 11). The "AuditableEntity<>descendants only" predicate is withdrawn: it was blind to the seven plain classes the modules ship —PlatformHostMapping,TenantLocale,TenantFeatureFlag,PlatformEntitlementandPlatformKillswitchin Tenancy,CustomizationGenerationandTenantLevelTaxonomyItemin Customization — and could snapshot none of them. Five are MUST: the host mapping, the feature flag, the entitlement refresh and the killswitch toggle on rows of their own in the Tenancy matrix, and the taxonomy band inside its aggregate's rows.TenantLocaleis SHOULD, and the generation counter is deliberately unaudited — bumped by one raw statement, so it is never aChangeTrackerentry at all. The host mapping is the one the Tenancy matrix singles out as mattering most. This list is the canonical one; a document that names these classes links here rather than counting them again. A module opts no entity in, and the interceptor constructs no row and issues no SQL.
| Class | Default retention target | Notes |
|---|---|---|
security-event |
7 years | KVKK / GDPR / sector compliance baseline |
platform-admin |
7 years | Cross-tenant operations |
Financial (Billing.*) |
7 years | Tax and invoice retention |
read-sensitive |
2 years | Sufficient for typical investigation cycles |
create / update / delete / action (other domains) |
2 years | Tenant-configurable down to 6 months or up to 7 years |
| Recording-policy and consent changes | 7 years | Lives with the recording itself if longer. Note: this is the retention of the audit-log entry about a recording policy or consent change — not the retention of the recording file itself. Recording files follow the per-tenant retention policy declared in 16-media-pipeline.md § Recordings (default 30 days; tenant-configurable up to the platform cap). The two retentions are independent: the audit entry persists for compliance reconstruction even after the recording file is purged. |
A tenant cannot reduce retention below the platform-defined floor for security-event, platform-admin, or financial entries. Phase 11 owns enforcement by a daily Hangfire job; its deletions must be batched, logged, and themselves audited (security-event).
This schedule is not implemented today. Packet 9 ships audit_log with no retention
column, no purge job and no per-tenant override, and audit_config carries classification
overrides only. The daily learnstack:audit:retention-purge job, the per-tenant override
and the partition lifecycle are owned by
Phase 11
(ADR-0044 § What we explicitly punted on,
ADR-0028 Amendment 2026-09-07). The
table above is the policy those deliverables implement, not a description of today.
Rows, including retained authorization metadata, can outlive these targets until
that separately admitted machinery exists. Each row follows its OperationType
and applicable domain policy, not a blanket retention for all MUST rows.
- Every command that mutates a MUST-audit resource has its audit row written in the
same transaction as the state change, per
ADR-0033. Atomicity comes from the
transaction, not from sharing a
SaveChangescall. If the row cannot be written, the business transaction fails closed: it rolls back and the caller receives503 audit_unavailablerather than committing unaudited. ADR-0016's "audit never blocks business logic" now applies to SHOULD/MAY-class entries only. - A committed audit row and a committed business row are the same event. "Inserted"
is not "committed": if the transaction rolls back — including on the ordinary path where
a handler saves and then returns a failure
Result— the audit row goes with it and is re-written standalone with outcomefailed. A MUST-class operation is never left with no row. - MUST-class events with no committed business transaction — a pipeline
short-circuit at step 4 or 5, a non-mutating security event, a non-MediatR caller
such as
TenantAssertionMiddleware, and the reconcile re-write after a rollback or an indeterminate commit — are written standalone, in a short transaction on a connection outside any business transaction. That writer announces both session variables from the draft —app.tenant_idandapp.organization_id— as its first statements:audit_logis org-scoped, so a row whoseorganization_idis non-null while the organization GUC is unset failsWITH CHECK(ADR-0033 Amendment 2 § 5). Three things are not on this path: a grantedread-sensitivequery, which rides the in-transaction path becauseTransactionBehaviorhas no request-kind gate (Amendment 2 § 7);EnterPlatformAdminScope, whose row takes the fourth write method below; and a validation refusal at step 1, which writes no row at all — validation runs outside the audit step, so the request is refused before anything has classified it (ADR-0033 Amendment 7). - A standalone MUST-class write failure changes the response only when the operation
would otherwise have succeeded
(ADR-0033 Amendment 1). A row recording
an access being granted still rejects with
503 audit_unavailable; a row recording an operation already being refused — adeniedauthorisation outcome, a rejected tenant assertion — keeps its own403/404, because the refusal is the security outcome and downgrading it hands an anonymous caller an availability signal it controls. Either way the failure logs atCritical, increments the standalone-write-failure counter and marks the audit health check unhealthy. The in-transaction class is untouched: its failure still rolls the operation back and answers503. - Classification does not read the database on the request path. The MUST/SHOULD/MAY
catalogue is in-process; per-tenant
audit_configoverrides are a cached projection whose loader sets its own tenant GUC. A failure to read a tenant override falls back to the catalogue — which carries the MUST floor, so nothing proceeds unaudited — and is logged atError. It does not move the audit health check, which answers only whether a MUST-class row can be written (ADR-0033 Amendment 6). An operation the catalogue does not classify at all is rejected with500 audit_unclassified_operation(09-error-handling.md): everyIRequest<Result<T>>that reaches step 3 must be classified,Offincluded, there is no residualRequestKind.Other, and test-only request types register through the same builder in their fixture (ADR-0044 § 6). A tenant override may narrow SHOULD/MAY coverage and may never remove baseline MUST coverage. - Two enums carry one distinction
(ADR-0044 Amendment 3 § 4).
OperationClass { Must, Should, May }is the tier the catalogue and the matrix declare;AuditClassification { Off, May, Should, Must, Unclassified }is whatIAuditConfigService.ClassifyAsyncreturns, once the tenant'saudit_configoverride and the MUST floor have been applied.Offis how a request that writes no row is registered — a builder call rather than a convention, which is what makes "classified,Offincluded" checkable — andUnclassifiedis the rejection above.OperationClassgains no fourth member: it is the persisted tier, and no row can hold a value meaning "no row". - Fan-out to external sinks rides the outbox and is best-effort; the local audit row is not.
- Failed
deniedoutcomes are audited even though no state changed; the trusted authorization evidence contract defines the separate P03-2 event population and pre-success barrier. - Background jobs that mutate MUST-audit resources use the runtime-stamped SystemActor under ADR-0047. A nullable causal human is separate attribution, never execution authority. The authoritative job envelope supplies identity; opaque Hangfire wakeups carry no actor or tenant payload. P02b-4 implements this accepted contract before any production job definition.
- Integration event handlers that mutate state are treated as actors of type
systemand audited accordingly. - Platform-bypass code paths (
IgnoreQueryFilters()etc.) write asecurity-evententry on every invocation, with ADR-0046's confined routine dispatcher exception: polling/claim/mark uses exact grant confinement, bounded structured attempt outcomes, metrics/health and MUST-audited terminal transitions. This exception changes no platform-admin pre-entry audit or other bypass operation. Accepted ADR-0047 adds only the named job/recurrence routing/status extension, conditional on exact grants/caller censuses, bounded diagnostics, metrics/health and same-transaction terminal MUST audit; the canonical job obligations name their owners and proofs. Ordinary business mutations and privileged maintenance remain audited under their existing contracts. - Accepted ADR-0047's sixth currently shipped
WriteJobTerminalAsyncmethod accepts only the actual fenced job-transition witness and matching caller connection/transaction. It validates stored tenant/organization/job/definition/attempt/acquisition values, MUST/SecurityEvent classification and the exactplatform.job.dead_letterdraft. It opens or commits no transaction; failed audit rolls back terminal state. The event seam and original four writes retain their contracts. WriteEventTerminalAsync(AuditEntryDraft, EventTerminalTransition, DbConnection, DbTransaction, CancellationToken)is the narrow fifth write. Only a successful fenced UPDATE result mints the restricted witness binding actual tenant/org/event/acquisition/kind/reason/attempts/subscription and live transaction. Validate declared MUST/SecurityEvent operation and matching draft before INSERT; mismatch rolls back both writes. No transaction is opened or committed by the seam.PostgresAuditStoreremains the sole audit SQL writer. Tenancy owns off-pathplatform.outbox.dead_letter(P02b-2) andplatform.delivery.dead_letter(P02b-3 Step 4); each is registered with its writer. Outcome success records terminal state, not publication. Invalid causal metadata is omitted and a fresh validated attempt trace is used. Absent optional causal IDs are valid; SQL NULL alone does not invalidate a stored trace. Closed terminal values live in bounded metadata;AuditEntryDraft.Reasonremains for platform entry. Audit refusal retries terminalization without delivery. Because the bypass role ignores RLS, witness/call-path proof binds identity, not announced GUCs.- Entering
EnterPlatformAdminScope(reason)writes that row throughIAuditStore.WritePlatformScopeAsync— a fourth write method, not an update method — on the scope's own platform-role connection and before the operation runs, so an operation that later fails is still recorded (ADR-0044 § 10). TheDbTransactionthat method takes is the audit write's own, begun and committed on that connection before the scope's working transaction begins — never the handle's transaction, which a frame disposed withoutCommitAsyncrolls back, taking the record of the bypass with it. That is the row Database Standards § HowEnterPlatformAdminScope(reason)reacheslearnstack_platformcalls "committed on its own". - An ordinary audit intent's tenant is the tenant the ambient transaction
announced, never a value off
the request payload:
ITenantContext.TenantIdunder a resolved context,IProvisionsTenant.ProvisioningTenantIdfor provisioning under an unresolved one, andTenantId.PlatformSentinel— the reserved00000000-0000-7000-8000-000000000002, not the nil UUID — for a platform-scope operation with no resolvable tenant. An ordinary unresolved, non-provisioning context writes no row: there is no tenant whose admin could read it, and ADR-0036 forbids inventing one (ADR-0044 § 1, § 2).AuditLogBehaviordecides it at step 3 and puts it on theAuditIntent, which is the only point at which all four cases are decidable; the store composes the row from the intent and resolves no tenant of its own (ADR-0044 Amendment 3 § 2). Accepted ADR-0072 adds only the exact global creation class below; an unresolved marker, generic metadata or SystemActor does not enroll it. - The sentinel has an enforcer, not only a constraint. Packet 9 puts the guard where
the value enters:
SetProvisioningTenantContextAsyncrefusesTenantId.PlatformSentinelas it already refusesGuid.Empty, andTenant.Createrefuses it in the factory. ThetenantsCHECK is the backstop — a constraint cannot stop a GUC from being announced (ADR-0044 Amendment 3 § 5). - The outbox dispatcher attaches the actor and the correlation id to every event it dispatches.
Derives from: ADR-0097.
ProviderEventObservationHandler alone mints ProviderEventAuditEvidence after
the transport's actual inbox claim and an exact enqueued tenant-target read.
AuditStateCapture.AttachProviderEvent binds it once to that invocation's sole
audit.provider_event.observe intent. AuditDraftComposer validates its closed
shape and owns the final row. This adds one provider-observation evidence producer;
the HTTP, seed, integration-delivery and job authorization sources remain unchanged.
- The row is tenant-wide SecurityEvent/Must, Actor SystemActor, logical subject
User/affected UserId. No User aggregate is mutated or captured. - Version-one
metadata.provider_eventcontains only authority/realm/source event, receipt, target and affected User identifiers, normalized kind, source time and provider outcome. No raw subject, IP, name, detail dictionary or provider error survives. - Audit outcome and row timestamp describe processing; source outcome/time remain separate. Account history is not evidence of a login in a particular tenant.
- The central MUST write and inbox/delivery completion share the business transaction. Duplicate deliveries cannot create another successful observation.
- Global admission receipts are operational records, not global Audit rows. Tenant targets, delivery envelopes and Audit retain their independent replay/ retention dependencies; expiry of global receipts does not erase those links.
Central evidence ownership and pre-success barriers are implemented. Accepted ADR-0076 and ADR-0077 add central evidence ownership without changing ordinary resource classifications or the pipeline order. The phase Status block owns delivery state.
| Decided act | Required population |
|---|---|
| HTTP protected-policy rejection under a trusted resolved tenant | One MUST/SecurityEvent identity.authorization.deny; no handler dispatch or invented resource attempt. |
| Application/resource capability or ownership rejection | One denial event for that invocation, plus each normally declared resource intent at its existing classification/outcome. |
| HTTP allow, then application/resource deny | Only the rejecting act supplies a denial event; the HTTP allow supplies none. |
| Nested refusal absorbed by an outer success | The inner denial remains denied and independently required; the outer capture's Committed flag cannot suppress it. |
| Successful ClaimAndMembership resolution, then conflicting tenant/org header | One MUST/SecurityEvent tenancy.assertion.reject_claim_context under the confirmed tenant; no host-budget debit. |
| Successful administrative membership directory read | MUST/ReadSensitive identity.membership.list on the ordinary ReadWrite owner, committed before any result disclosure. |
An Off operation has no resource intent but still owes its denial event; SHOULD, MAY and tenant override-Off never remove this MUST floor. Plural resource intents remain plural. The denial event is a separate population, not an ordinary intent or a promotion of successful operations to MUST. Fixed policy/operation IDs come from the protected policy catalogue; callers cannot choose slugs, attribution, tenants or arbitrary subject payloads. Module matrices own the sole operation rows.
Each policy invocation has its own occurrence. Sharing the same decided reference between HTTP/application adapters cannot create another event; a genuine nested act or reevaluation is a new occurrence. Correlation, request and route IDs are not occurrence identities. The common owner captures/cleans this state, including Off and absorbed nested refusals; a joiner neither commits nor clears it.
The common owner retains a private audit-only observation while consuming an admitted invocation's result. Cancellation revokes execution authority but does not erase that act's already-decided refusal. The observation binds the exact request and lexical owner and cannot be reused after that owner closes. Current invocation, candidate and read-witness authority still require their live checks.
Earlier credential, unknown-host, malformed assertion and validation refusals keep their existing contracts. Public anonymous/tenantless refusals invent no tenant or sentinel. Resolver row 7 retains its host recorder, row 10 remains unaudited, and refused row 14 remains diagnostic-only. AccountSite success stays Off; live membership denial attributable to its resolved tenant owes the denial event. This is not a generic audit of all 401/403/404 responses.
The claim-context assertion event requires actual successful production-reader ClaimAndMembership resolution, never a candidate, raw claim or asserted header. Its fixed source is membership-confirmed header assertion. Capture confirmed scope/admitted actor and only the fixed tenant/org dimension and mismatch reason; copy no asserted UUID into audit or diagnostics. Host-backed rejection keeps its existing separate source/budget. This event is neither refused-row-14 evidence nor a host-tenant rejection.
| Actual enclosing owner/outcome | Barrier and failure posture |
|---|---|
| Otherwise-successful ReadWrite owner | Insert every unresolved denial on the business transaction after domain-event draining and before final event/job commit admission. Failure rolls back business state and yields 503 audit_unavailable. |
| Otherwise-successful physical ReadOnly or ownerless execution | Acknowledge every unresolved event in its own short evidence transaction before completion/disclosure. Failure yields 503 audit_unavailable; no INSERT or mode upgrade on the read-only transaction. |
| Actual HTTP/application refusal with no business owner | Attempt standalone before returning; audit failure preserves the decided 403/404. |
| Refusal, exception, cancellation or rollback | Final reconciliation attempts unresolved events standalone and preserves the actual refusal/exception. |
| Unknown business COMMIT acknowledgement | Reconcile the same fixed denial occurrence. Exact event evidence proves only the event, never business COMMIT success. |
Track pending/written, acknowledged, rolled-back and uncertain state per event and actual owner generation, independently of normal capture state. An in-transaction event is acknowledged only by confirmed enclosing commit; standalone acknowledgement survives a later outer failure. The barrier preserves the existing no-await gap between final event/job commit admission and physical completion. It is never a finally-only write after an otherwise-successful business commit.
The central owner mints one opaque reference containing an AuditEntryId, trusted
UTC decision timestamp normalized once to PostgreSQL microseconds, and frozen
complete draft: scope, actor, policy/subject/reason and bounded provenance.
All admitted writes/reconciliation of that occurrence reuse the same (id,timestamp)
and fields. Serialize reentry with the same reference. New HTTP requests, event/job
executions and real nested evaluations receive new references; no restart ledger
or persistent replay identity is introduced.
Confined denial methods on existing IAuditStore/PostgresAuditStore reuse the
single INSERT/binder, catalogue and failure signals. They do not use generic
WriteStandaloneAsync's broad 23505 acceptance. Only a duplicate of
audit_log_pkey for the expected (id,timestamp) permits verification. Dispose
the failed INSERT transaction first; a clean physical READ ONLY transaction under
captured tenant/org RLS compares every persisted draft field, including the fixed
event discriminator/outcome, using null-safe and typed JSONB equality. A missing,
mismatched, foreign-scope or unreadable row fails. No new SELECT grant, global
function, sentinel or bypass is admitted. Ordinary plural resource reconciliation
keeps its different-timestamp semantics. Later privileged redaction can make an
exact match fail; this is no indefinitely replayable original-row witness.
An acknowledged ReadWrite commit carries its denial even if the process exits immediately afterward. ReadOnly/ownerless success waits for standalone acknowledgement. A crash before any applicable write commits can lose an uncompleted in-memory refusal. Already-refused audit-outage paths retain their explicit evidence-loss posture; no durable recovery queue or universal crash-proof collection is claimed.
The Standard 05 source ledger owns the independent four-slot authorization/two-slot evidence sources, retained cleanup, shared five-second evidence I/O deadline, tracked job lanes and downstream reservation/progress proofs. Evidence saturation is audit-unavailable, never event suppression or permission to report outer success. No new aggregate suppression budget applies. At 600 denied acts/minute one subject can generate 864,000 denial rows/day plus resource attempts; an illustrative 1,000 bytes/row is about 864 MB/day before indexes/WAL/replication. This is a cost illustration, not production sizing. Phase 11 owns measured capacity, distributed admission and alert/runbook hardening; reducing coverage or retention requires reopening the decision.
Trusted HTTP, seed, event and job adapters supply a typed immutable snapshot; handlers cannot write or replace arbitrary audit context. The central composer merges source provenance with each invocation's exact policy/subject facts before INSERT. An early frame may declare intents before authorization; central ownership attaches evidence when that act's decision exists. No enrichment UPDATE or second Identity audit table is admitted.
- Effective actor comes from verified binding or the finite trusted source owner; event/job IDs and causal human remain separate from effective actor. A SystemActor UUID or provider claim grants no authority or privileged flag. A finite seed owner's known absence of a principal remains null; provenance does not invent SystemActor or a human actor for it.
- At most two contributing Membership IDs and eight contributing built-in Role IDs come only from the live decision, sorted canonically. Excess or ambiguous evidence fails closed; never silently truncate an authority set.
- A typed versioned
metadata.authorizationholds those references, fixed policy/ route identifiers and source kind. No grant graph, body, query string, raw path, provider claim or credential belongs there. An inner operation retains its own policy/subject; child scopes cannot inherit another actor's evidence. - Route is an admitted template/descriptor bounded to 128 characters. Direct non-HTTP execution invents no route/IP/user agent. The source/caller census names finite population and cleanup sites; unknown/untrusted sources forge nothing.
- Reuse the admitted visitor/transport snapshot's effective address, with physical
peer fallback, without reparsing forwarded headers. The existing
inet/user-agent columns carry these redactable values. User agent is untrusted descriptive data: remove controls, bound to 256 characters, and never use it for authority or labels. - ActorEmail stays null until P03-6/G10 or a separately accepted earlier source/ freshness contract. P03-9 owns actual Platform/operator population.
- Membership/Role references remain personal linkage. Each row retains its own retention target: denial/assertion SecurityEvent seven years; directory ReadSensitive two years. Automatic purge, retention columns and tenant retention overrides remain unimplemented until Phase 11, so rows can outlive targets. Metadata stays outside the six-column redaction grant. P03-10's Audit participant locates it through retained actor/subject attribution and reports surviving references under Data Protection, without new metadata UPDATE authority or an anonymisation claim.
Store failure retains existing Critical/counter/audit-health signals. Independent composer refusal emits one fixed Critical signal, without raw provider/database exception details. Observability owns diagnostic rules; the phase delivery record owns actual fault/crash receipts and review state.
Implemented under ADR-0072 in P03-1 Step 3. The
Phase 03 Status block owns current
qualification and review state.
identity.user.create is MUST/SecurityEvent under the central baseline catalogue,
independent of tenant AuditConfig and ADR-0065's host-tenant assertion allowance.
Ordinary existing-binding reads declare no mutation intent. The exact
Database contract owns global
discrimination, policy/guard/evidence predicates and prepared owner sequencing.
The common audit/transaction coordinators retain ownership. Extend AuditIntent,
captured attribution and shared composition with a closed typed global-creation
value; central composition derives its bounded metadata and creation reference.
No handler submits arbitrary metadata or an AuditEntryDraft. Before an actor
exists, the authenticated audit principal is NULL and the proposed target actor
is separate; seed adoption attributes its fixed SystemActor. Raw issuer/subject,
credentials and token values enter neither metadata nor snapshots. Retained
subject-key metadata remains linkable personal data under existing retention.
WriteGlobalIdentityPending and ReconcileGlobalIdentity extend the earlier six
central write seams to eight implemented seams, without another SQL INSERT owner.
Success shares the first User's physical transaction; non-success reconciliation
uses captured evidence and preserves failure/unknown-COMMIT semantics. Ordinary
pending explicitly refuses sentinel/global intents and global enrollment. A
scoped read-only enrollment reader preserves the lazy application-source boundary. Platform, event and job seams keep their distinct scopes.
No global audit read endpoint or P03-1 HTTP creation route follows. Registered
Identity audit controls now exercise actual app-role, clean/dirty and physical
COMMIT-boundary paths. Later contextual writers and HTTP activation remain separate.
Accepted contract; implementation/proof pending. Identity and Tenancy's module matrices own the exact request/slug/resource bindings. Every human wrapper has its own classification/policy; reusing business logic never fabricates Seed provenance or invokes a Seed-only command.
Initial selection and explicit switch commit ordinary ReadWrite MUST/SecurityEvent
identity.membership.admit_session_scope, attributed to the actual Membership,
before returning a publication witness. The row proves API approval, not browser
cookie delivery. Failed INSERT/constraint/COMMIT cannot publish success; unknown
COMMIT remains unknown. This is not a standalone denial-lane event.
Ordinary refresh runs ValidateRefreshedScope: Off GET self followed by Off
AccountSite on the same new held token and original context. It creates no new
admission event or User. GET self/contexts and current own capability/profile
navigation are explicitly Off and no-store; personal relationship disclosure is
limited to the verified person's own records. Other people's member data and
Role/permission configuration reads retain MUST sensitive-read coverage. Failed
capability previews do not emit denial evidence; actual protected acts do.
Protected successful receipt replay is a fresh MUST sensitive read of its original immutable target under current disclosure authority, separate from the original mutation's event. Its read audit commits before stored bytes. A failed guard/audit preserves the retained completion. Do not replay original audit evidence or re-run a successful mutation to authorize a receipt.
Fixed management-origin adoption uses one Tenant-root marker change and its host
projection on the same common transaction with declared plural MUST evidence.
Both qualified 0→2 and 1→2 transitions retain those two MUST intents; an exact
existing mapping is designated as an unchanged projection without a fictitious
UPDATE. The runner verifies marker 2 and its exact live mapping, then stops
before mutation dispatch, witness minting, temporary widening or another MUST
intent. Marker 2 records historical qualified adoption, not current mutable-graph
or provider eligibility. There is no second aggregate writer or private Seeder
audit table. Successful warm no-write checks declare no new mutation intent.
Real seed/adoption races,
unknown creation, replay failure and refresh zero-event-delta proofs are required.
The closed fixed-seed prerequisite check is internal to the classified seed act. Its metadata projection is not an externally callable directory or a disclosure under the other-person sensitive-read rule above; it adds no audit classification or separate successful read event. The eight temporary-read consumers and twelve ordinary-scope content writers retain their existing mutation classifications and MUST floors. Refusal retains the act's existing failed/denied audit and genuine unknown-COMMIT reconciliation. Editor IDs and relationship metadata remain personal data, internal to the check; no raw editor evidence enters results, diagnostics or durable receipts. An independently callable or value-disclosing reader requires separate sensitive-read classification before activation. Acceptance supplies no new runtime qualification; the phase Status block remains authoritative.
The separately closed fixed-origin completion check
has the same internal admission/refusal audit boundary. Its sole consumer is
AdoptSeedAdministrationOriginCommand; it does not join the eight pristine
consumers. Owning completion readers disclose no values or relationships, so no
independent successful sensitive-read event, new Off request or durable receipt
is added. Completion refusal retains the adoption act's failed/denied evidence
and unknown-COMMIT contract; successful transitions retain plural MUST rollback.
Standard 05 owns the separate source, restoration, marker/repeat and recovery
rules. Acceptance does not qualify these new controls.
The seven-/two-year retention periods above remain policy targets, not an implemented automatic purge. Phase 11 owns enforcement and production volume qualification. New relationship/target/subject links remain personal data under the Data Protection inventory; ordinary redaction grants are not widened.
The P03-4 contract derives from ADR-0093. Identity's matrix and Tenancy's policy binding own exact operations/resources. Rows and new request bindings remain planned until their consumers and catalogue entries exist. A decision or diagram is not an implemented catalogue population.
- Create, reissue, revoke and accept are MUST security events. Creation/reissue enroll encrypted SMTP custody and the identifier-only job on the same ordinary transaction as Invitation state and its required audit. No notification/private audit table or SMTP call inside the business transaction is admitted.
- Acceptance uses central plural MUST intents for the Invitation and actual
original Membership. New Membership/contained children receive real capture;
already_memberkeeps the Membership unchanged and produces a subject-only security-event row. The Invitation's mappedacceptanceDisposition, actor and original Membership record the result through central capture. Handlers cannot fabricate a diff or supply a general arbitrary metadata payload. - The only added two-root handler is
AcceptInvitationCommandHandler, alongside provisioning's existing exception. User creation/disposal precedes this owner; no global and tenant transaction joins or retargets the other. Both required resource rows commit together or the grant/consumption is rolled back. - Already Accepted routes to the exact Off own-result query before mutation intents. Same Active actor, consumed verifier and original Active Membership prove that disclosure. Pending-only email/expiry/version/Role/inviter checks do not invalidate a committed result. A dispatched Pending command losing the race returns 409 with truthful failed-attempt evidence; it cannot emit another successful acceptance or silently discard a declared intent.
- Pending own inspection and accepted own-result navigation are explicitly Off.
Administrative list/detail, delegation-limited Role choices and protected
receipt disclosure are MUST sensitive reads, committed before bytes. The exact
orgless own-current-tenant
GetTenantInvitationPolicyQueryis Off/ReadOnly. Status detail returns only normalized current-generation submission evidence under current administration authority, without a delivery-body read. - The existing MUST
tenancy.setting.writecovers the exact tenant-wide TTL setting. Its setter uses whole-value TenantSetting redaction; no weaker class or generic settings grant follows from the extra key. - Ordinary module preparation/finalization is MUST and binds the exact
Invitation/generation.
identity.invitation.email_submissionapplies validated durable provider evidence through the common audit owner. The private immutable provider receipt is operational evidence, not a substitute audit row or a new direct INSERT seam. ExternalScope's ordinary database denial remains intact; the dedicated two-function source cannot write module/User/audit tables. - Final SMTP
250records accepted submission, never inbox delivery. Definite temporary no-effect can consume the existing retry budget; ambiguous Sending/ Unknown retains occupancy without blind retry. Durable evidence reproduces the same terminal result after restart. Revoke/reissue/accept invalidates codes; Prepare refuses obsolete generations, but prepared email can still arrive. Provider recovery fencing is separate from business withdrawal.
No raw recipient email, link, code, verifier, ciphertext, SMTP response/exception text or provider body enters audit values, metadata or diagnostics. Keep sensitive properties with redaction markers and typed closed outcomes; references remain personal linkage under the canonical Data Protection inventory. Authorized recipient-email DSAR disclosure remains possible under separate subject/purpose authority; credential and verifier disclosure does not. Existing SecurityEvent/ReadSensitive retention targets remain; P03-10 owns locators and closure integration, Phase 11 retained-copy/purge enforcement. No runtime or production qualification is claimed by these additions.
Canonical names and each rule's kind live in
21-architecture-tests-catalogue.md § Audit, which is
authoritative for both. The two lists below split by assembly: a structural rule runs in
LearnStack.Tests.Architecture; the four rules that prove runtime behaviour against a
real database cannot, because that assembly has no database and a structural assertion
observes neither a rollback nor a 42501.
LearnStack.Tests.Architecture — structural, on every PR:
AuditEntry_Inherits_Entity_Not_AuditableEntity— the audit aggregate is append-only by inheritance.AuditEntry_Is_AppendOnly— noUPDATEorDELETEtargetsaudit_logoutside the three named sites, andIAuditStoreexposes no update method.OperationType_Enum_Matches_Catalog— the enum and § Operation Types carry the same seven members.Every_Shipped_Request_Is_Registered— every request type with a handler and every concrete integration handler in any backend assembly is in the catalogue,Offincluded.Every_TenantOwned_Command_HasAuditCoverage— every catalogue entry has a matrix row with the same slug, class and type.Every_Matrix_Row_Whose_Command_Exists_Is_Registered— every unmarked matrix row is registered, and no(planned)marker outlives its command.Every_Module_Has_An_AuditCoverage_Matrix— every module spec shipsdocs/modules/<module>/audit.md, andEvery_Module_With_An_Aggregate_Or_A_Request_Has_A_Matrix— every module that ships an aggregate root or a request type has one.Modules_Do_Not_Write_AuditLog_Directly—IAuditStoreis the only sanctioned write path.No_Set_Based_Write_Bypasses_The_Audit_Capture— no backend source writes throughExecuteUpdate,ExecuteDeleteorExecuteSql*, which leave the change tracker, and so the capture, without an entry.
LearnStack.Tests.Integration — Testcontainers against a real PostgreSQL:
MustClass_Audit_Writes_Share_The_Business_Transaction— exactly one row per declared intent, all on the business transaction.Audit_Survives_Transaction_Rollback— a rolled-back MUST-class command leaves zero business rows and exactly one row with outcomefailed.Audit_Classification_Does_Not_Read_The_Database_On_The_Request_Path— an unreadableaudit_configdoes not stop a MUST-class command, and classification never asks for a connection to answer one. Packet 10; the uncatalogued-operation half isAuditLogBehaviorTests, where a request the catalogue does not know can be registered.AuditLog_Update_Is_Column_Restricted—learnstack_appgets42501;learnstack_platformgets the column-restricted redactionUPDATEand the purgeDELETE, and nothing else; the table owner is stopped only by the trigger.
One further catalogue rule holds a claim made above and belongs to neither list:
AuditStateCapture_ClearedPerRequest
is behavioural — Clear() is called exactly once, by the outermost
AuditExecutionCoordinator, and never by a nested audit frame.
These drive the runtime path as learnstack_app, except where the privilege model is
itself the subject: AuditLog_Update_Is_Column_Restricted measures three layers that bind
three different roles, so it connects as learnstack_app, as learnstack_platform and as
the owner in turn. Everywhere else the rule of 05-database.md holds — an
isolation assertion that connects as the owner or as a BYPASSRLS role passes even
when every policy is inert, so it proves nothing.
A tenant admin's audit view supports:
- Filter by actor user, module, resource, operation, operation type, outcome, date range.
- Detail view shows
before,after,request,reason. - CSV export limited by retention class (security-event entries do not export to non-admin roles).
- Search across
resource,route,correlationId,userId.
Platform admins additionally see cross-tenant entries through a separate route guarded by platform-admin scope and rate-limited.
- Writing a MUST-class audit entry after its controlling transaction commits. Standalone writes own their transaction; absorbed denial evidence must satisfy the pre-success barrier before the enclosing execution commits or discloses success.
- Truncating
before/after/changessnapshots silently, or writing an empty object in place of one that was too large. OverJsonValue.MaxRowBytesthe value becomes the elision record of § Storage, in the column's own JSON type. There is noaudit_blob_id: it exists in no DDL, names no blob store, and is struck from this standard (ADR-0044 § 8). - Dropping a PII property from a snapshot instead of redacting its value.
SensitiveTokenCatalog.RedactedValuekeeps the fact that the field changed; deletion loses it. - Mutating an audit row in place from anywhere other than the two sanctioned paths (GDPR redaction, retention purge), or widening the trigger's redactable column set without an ADR. Granting
learnstack_appUPDATEorDELETEonaudit_log. - Storing audit entries in the same module's read schema (the audit aggregate is global / cross-module).
- Reducing retention without an ADR.
- Skipping the matrix in a module spec.
- ADR-0044 The Audit Write Path — the platform
sentinel tenant, intent multiplicity, the nesting rule,
outcomeandtimestamp, the classification key, the capture predicate, redaction and size, the table class and its GRANTs, the fourth write method, and the two error codes. - ADR-0016 Audit Log Subsystem — capture
pipeline, retention policy, partitioning strategy; Amendment 1 fixes the seven-member
OperationTypeenum. - ADR-0017 Tenant + Organization Hierarchy —
organization_idin audit entries. - ADR-0036 Tenant Resolution and Trusted Inputs — the two tenant-assertion operations of § Baseline Coverage; Amendment 7 is where their snake_case spelling is decided.
- 31-audit-subsystem.md — subsystem deep dive (interceptor, state capture, MediatR behavior, retention job).
- 05-database.md — the canonical RLS template, the table classes, the four database roles and the GRANT matrix.
- 09-error-handling.md —
audit_unavailable(503) andaudit_unclassified_operation(500) in the error-code table. - 11-security.md — security headers, authorization, tenant isolation, secrets.
- 02-domain-model.md § Audit —
AuditEntryaggregate definition. - 13-identity-and-auth.md — Keycloak vs LearnStack audit split.
- 10-observability.md — correlation id propagation, redaction.
- 20-infrastructure-stack.md —
IAuditStorerules.
ADR-0095 classifies definition lifecycle, Membership custom-value writes and independent Tenancy consent grant/withdrawal as MUST. Other-person custom-value reads are MUST ReadSensitive before disclosure; own reads and definition configuration reads are explicit Off. Publication designates its successor when tracking both revisions. The module matrices own planned request bindings; each new type and slug joins its catalogue before dispatch. Whole custom values and authored schema/labels/notices are redacted, while subject and linkage remain classified personal data. Phase 03 owns delivery and proof.
Derives from: ADR-0099.
P03-8 Step 2 binds the eleven MUST identity.federation.* operations to their exact
request types in the Identity matrix.
The Integrations baseline row above ("External provider credential … rotated") covers
identity.federation.rotate_secret. Each Begin, Resume and Complete is its own request
type; a Complete's failed or uncertain outcome is a settled, successful request with
its own MUST row, not a rollback. No federation row carries a client secret, an
assertion or a token; snapshots hold nonsecret fields and digests.
| Read | Classification | Reason |
|---|---|---|
GetFederationConnectionQuery |
Off | The connection detail holds no personal data: protocol, alias, display name, issuer or entity identifier, client identifier, state and digests only. |
GetPublicSignInQuery |
Off | Anonymous public read under ADR-0052; it returns the host tenant's Active alias and display name and no personal data. |