Help us shape the future of Go! Take the 2026 Go Developer Survey

postgres

package module
v0.0.0-...-789096f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 37 Imported by: 0

README

Identity PostgreSQL

Protected explicit account linking

NewAccountLinkUnitOfWork(coordinator, repository, AccountLinkUnitOfWorkConfig{RetentionPolicyVersion: revision}) implements the root identity.UnitOfWork for AccountLinkService. The exact repository, audit/lifecycle, capability, current-counter and native OAuth account-link participants must already be registered with their complete typed recovery and execution phases. Missing phases fail before reservation. This is trusted backend composition, not an application SQL gateway or provider proof API.

The native AccountLinkContributor enriches the original signed command with its retained counter context without changing that intent. Current provider, original session, policy and factor admission run inside the kernel transaction; the native owner must enforce them rather than accepting caller assertions. AccountLinkWork expires with each invocation and poisons ignored denials. It reuses the kernel's directory, credential and authorization checks. Its credential-authority getter permits only the original epoch initially and this transaction's actual successor at the final check, never a refreshed session.

One coordinator reserves the command/counters/proof, applies identity-owned link/credential changes and provider-owned effects, persists audit/lifecycle, rechecks admission and finalizes proof/provider custody. A failed phase rolls back all provisional changes. Required denial auditing and proof release follow the existing proven-rollback protocol. Exact replay returns its historical receipt. Expired pending recovery requires every frozen owner to prove noncommit; provider uncertainty leaves custody reserved. Current rows never reconstruct a successful receipt. Historical bare-link bytes remain unchanged.

Original OAuth callback preparation

The trusted native adapter calls AccountLinkUnitOfWork.ExecutePrepared with the root AccountLinkPreparationCommand and its closed declaration. Original code/state/session intent uses the existing keyed command claim; the later verified subject and signed link command do not replace it. This is an adapter seam, not an application callback API or permission to invent missing owners.

Install AccountLinkPreparationMigrationSource after the existing CounterPreparationMigrationSource and all installed successors. The forward profile preserves earlier migration checksums and rejects other operations. The declaration fixes six consuming/domain owners, original callback-state capability, counters, audit and lifecycle, with no final link grant yet. The registry additionally contains the actual capability.issuance owner.

Original state reservation, current native admission, counter charge and start marker commit before the native owner may decrypt PKCE, exchange or sign. Lost start acknowledgment does not permit generation. Started-without-output stays pending; retained authenticated ciphertext resumes under its original generation without another exchange or renewed expiry. Matching terminal replay does not restore provider output. AccountLinkWork.Preparation lends original typed input and copied ciphertext only during that exact owner's invocation.

Attachment persists and reserves the one matching final grant atomically via the existing issuer/consumer. The issuer is a preparation prerequisite, not a final domain recovery participant: its positive issuance row must not turn a rolled-back account link into a committed result. Both distinct one-use inputs then apply/finalize with the protected mutation; proven rollback releases both.

This contract still does not provide the actual OIDC provider/session owner, token vault, HTTP callback or session-producing social flow. Native OAuth owns those required implementations and their current policy, fresh credential and source-proof expiry checks. No network exchange runs in open AccountLinkWork; no feature wrapper or second ledger substitutes for the root owner. Implicit, administrative linking and unlink remain outside this explicit-self profile.

Provider-account storage and trusted reads

Append AccountMigrationSource{Base: installedHistory, Version: nextVersion} after the credential-reference migration and every installed successor. Apply it through the normal migrations runner; do not alter an installed migration. The forward source preserves existing users, passwords, sessions and epochs. It installs identity-owned account/link tombstones and credential associations, not a provider engine, token vault or public account-link workflow.

Repository.ListAccounts implements the existing bounded AccountRepository: one primary statement, exact tenant/user partition, account-ID ordering, no partial result on overflow, and ErrUserAbsent for a missing user. It returns stored status rather than turning blocked users into active users. Configure MaximumAccounts in 1..100 and the repository's finite operation budget.

Repository.GetAccountLinkState reads the same user's complete account set, candidate/tombstone versions, credential epoch/references and tenant-wide exact provider/issuer/subject collision in one read-only repeatable-read transaction. The explicit and administrative query modes are structural reads, not authority to use either policy. Implicit linking is unavailable until its consistent identifier projection is composed. Returned methods conservatively have Usable=false: reference enablement alone cannot prove provider, factor or credential-owner eligibility. A disabled provider reference whose link was removed remains a retained tombstone, not a live login method. Disabled non-provider references, including removed passkeys, likewise remain in storage without consuming the bound on current methods. Enabled references and provider methods currently associated with live links still count. Disabled provider references without an association are retained credential tombstones, not current methods. Enabled references missing their association, and invalid or non-provider associations, still fail closed rather than being omitted.

The live subject index uses a database-checked SHA-256 commitment of the length-framed UTF-8 provider tuple so valid maximum-size metadata does not exceed PostgreSQL's B-tree entry bound. Lookups compare original exact tuple bytes; a collision denies instead of selecting another identity. No bearer, token or PKCE verifier is stored here. Account IDs and historical versions are retained; an absent account in a user's list never proves tenant-wide subject absence.

These are trusted storage ports. Consumers must not write account rows directly or treat these snapshots as authorization, provider proof, authentication, usable-final-access evidence or a renewable validity lease. The protected link owner must recheck current state, consume proof/risk, and commit account, credential, audit, lifecycle and recovery effects through the sole coordinator. That consumer workflow and its session/HTTP composition remain unfinished.

For a known-user native feature invocation, Work.RequireActiveProviderAccount fences an original ProviderAccountAdmission: exact account/provider tuple, account and social-link versions, associated provider credential and independent kernel user/identifier/credential epochs. It retains user, credential, account and association share locks and checks credential expiry again after obtaining the link locks. Denials poison the original Work even when ignored. These are read/locking checks only; they do not mutate a link, resolve an anonymous flow, validate provider cryptographic proof or current provider configuration, choose factor policy, consume risk/capability state or issue a session. A prior success cannot renew the original evidence or be cached as a new validity lease.

The private link writer now locks the current partition and applies the core's pure ApplyAccountLink transition in that same transaction. Account records, credential associations and independent epochs commit or roll back together; retained IDs cannot be reassigned or revive an old disabled credential. The tenant exclusion and live-subject unique constraint serialize competing owners. Relinking retires only disabled credential associations on that exact account; credential-reference tombstones and their versions remain stored. Association rows describe current access, not historical credential lineage. This prevents repeated same-ID relinks from reattaching the entire retired credential history. This storage phase alone is not a callable account-link service. The protected unit of work above requires proof, original session/policy, risk, required effects and recovery participants; missing native composition fails closed.

Native command fingerprinting recognizes the separate canonical protected-link counter variant. It binds network attribution through a keyed, domain-separated commitment and retains the original preparation time and digest-version aliases. The original link command ID, scope, proof and bare-link byte format stay intact; safe journal metadata contains no raw network. This codec support does not enable unsupported reservation, Begin, or a public linking service by itself.

Source-version snapshot imports

Trusted feature schemas may explicitly select FeatureVersionSnapshotImport when importing an absent local record with a positive source version. The coordinator binds that exact policy in command intent, collision scope, request-preparation identity, historical plans, lifecycle and journal receipts. Existing sequential schemas retain their bytes and adjacent-version rules. Policy changes cannot borrow a registered schema or its original preparation. The native importing owner must authorize the source and atomically fence local absence; this declaration grants neither import authority nor overwrite rights.

Atomic API-key verification effects

The exact opt-in apikey-verify-organization-v1 schema represents a known organization-owned key without a human UserID. Its AnonymousFlowID is the original command ID (the authentication attempt), while the actual API-key actor remains the audit target and owns the positive original key version. It uses the same closed plan, typed comparison, required effects and original recovery as known user-owned keys, not the unknown-key denial profile. The trusted native producer must bind the actual organization and credential epochs in command fields and fence current organization authority inside Work; this kernel support supplies no organization authority or browser session.

The native verifier uses ExecutePreparedAPIKeyVerification to submit original preparation and obtain the coordinator fingerprint actually matched under its claim lock, including when acknowledgement is lost. ObserveAPIKeyVerificationCommand is an effect-free intent check; absence supplies only a prospective fingerprint, which must never replace the actual submission commitment after a concurrent retained-key claimant wins. Authorized primary absence supplies only the prospective current-key commitment; it is not a reservation or rollback proof. Existing attempts compare complete intent under their retained fingerprint key. RecoverAPIKeyVerificationCommand requires that original nonzero fingerprint before pending recovery, and repeats the check under existing recovery locks. Neither method compares a credential, returns a native principal, renews freshness or adds an attempt journal. Generic command metadata remains fingerprint-free.

Prepared native submissions bind APIKeyVerification.KeyVersion in the original uint64 apikey.verify.key-version field. An unattached preparation remains fingerprint-bound pending metadata, even after its lease expires; missing output never authorizes generation or proves rollback.

The closed CommandPlan.APIKeyVerification profile is a trusted native-adapter composition seam, not a standalone API-key backend. Its exact APIKeyVerificationContributor compares the credential and checks current owner, tenant and policy authority inside the existing Work. It must first require the unchanged command through Work.RequireFeatureCommand, and its mandatory CheckFeatureCommit fences the original facts and expiry again after required effects. It cannot renew freshness or create a private transaction.

ApplyAPIKeyVerification returns a record-free FeatureReceipt and an independent APIKeyVerificationOutcome:

  • Ordinary success or denial persists one protected authentication audit, without advancing key versions or emitting lifecycle events.
  • A genuine strict permission reduction also persists its successful update audit and api_key.permissions_changed.v1, even if the resulting grant denies authentication. Both effects remain atomic with the actual native reduction.
  • An unknown key can only deny, with an authentication_attempt subject bound to the original command. It cannot authenticate or reduce any key's grant.

Known-key plans freeze the original positive, incrementable KeyVersion, the API-key actor as audit target, protected authentication/update slots and nominal zero-version lifecycle declaration. Unknown-key plans use version zero and only the authentication slot. The coordinator selects actual slots from the native result; the retained plan never changes. Actual reductions use the frozen key's adjacent version transition while the record-free receipt stays at zero. All other feature profiles retain their existing mandatory mutation effects. The declared native verification schemas require this closed plan and cannot fall back to a generic mutation contributor. The envelope discriminator does not reserve an operation name belonging to another registered feature owner.

CommitOutcomeCommitted describes durable command effects, not successful authentication. Native adapters must retain and reconcile their original result under the sole command journal, never infer a principal from that receipt or rerun comparison after an ambiguous commit. Missing required audit, lifecycle or final authority rolls back the entire provisional reduction; unproven closure remains unknown. This support alone does not supply native credential storage, verification, reconciliation, HTTP or cache adapters.

After the original lease expires, unanimous negative evidence from every frozen participant may close the attempt as not committed. That recovery writes only the failed authentication audit, never the possible update/lifecycle. It retains the existing dependency-failure error classification alongside the durable noncommit result. Composed authentication and reduction records share original command/correlation identity and retain distinct canonical causation IDs.

Independent user-owner status admission

Work.RequireActiveUserStatus admits only the exact registered feature owner during its live invocation. Freeze the real Repository.GetStatus result in the command's intent, then require the command-bound tenant/user's active state and original positive user-security epoch. The existing user-row SHARE lock fences lifecycle changes until the coordinator commits or aborts. Acquire this guard before API-key or other feature-aggregate locks and repeat the original expectation at the final check; do not adopt a newer epoch to make it pass.

The user's aggregate revision is not an authority epoch. This guard does not require password, identifier or session credentials and does not authenticate an API-key actor as its human owner. Native callers must separately prove the actual credential, directory/tenant status and permission ceiling. Existing credential-specific guards remain mandatory for operations relying on them. Missing/inactive/stale owners deny uniformly; every live failure poisons Work, including an already-open cursor, while expired invocations cannot poison a later call. No transaction, authority state or freshness window is created.

Passkey eligibility during anonymous TOTP completion

Work.RequireMFAPasskeyCredential fences the exact passkey reference and user epochs for the subject frozen in the protected TOTP completion plan. The child must already be consumed in that Work; the same guard remains available in its original final check. MFATOTPAttemptWork.RequirePasskeyCredential supplies the matching current-credential prerequisite before counted comparison/denial. Both retain the original anonymous command, poison live Work on denial and use existing credential locks/time checks. Neither authenticates an assertion or factor, authorizes an operation, supplies an email recipient or issues a session.

Before output generation, Work.RequireMFAPasskeyPreparationCredential uses the original input-admission command and frozen continuation subject to perform the same eligibility read. It does not consume the child or admit Apply; the existing consumption-required guard must still run during Apply and final checks.

Recovery when an original request precedes its journal

An opted-in native RequestKeyRecoveryContributor authenticates its original prepared-request ciphertext and returns its complete original command binding. RecoverPreparedFeatureCommand checks current query policy, actual immutable mapping, exact registered owner and every query field before outcome disclosure. A mapping with no claim returns CommitOutcomeUnknown and UnknownCommitError for that original command. It never proves rollback or permits another execution; the first invocation may still be starting. Existing journals use the same sole recovery owner. Generic outcome queries keep uniform missing/denied responses. The decoder performs no preparation or effects; native session/domain disclosure checks remain required. Retain the original envelope configuration and keys.

Definitive refusal of an expired, never-started original

An explicitly registered RequestKeyExpiryContributor also authenticates the original exclusive preparation deadline. It must restore the earliest original session/preparation validity ceiling from the immutable envelope, not calculate a new deadline from current time or a replacement session. Its bounded decoder performs no reads, generation, counters or effects. Native possession and current session/domain disclosure checks remain required around this kernel operation.

Install RequestKeyExpiryMigrationSource{Base, Version} after the selected request-preparation history, then select ExpirePreparedFeatureCommand. Before the deadline, an absent claim remains Unknown. After primary-database expiry, the operation arbitrates with every ordinary/prepared writer through the existing global command-ID primary key. Only a never-claimed original can become an irreversible, scope-free retired claim carrying a keyed original-envelope digest. This is an explicit exception to retirement after terminal-result retention: the fence proves effects can never start, rather than removing an existing result. An existing claim is never retired; its ordinary recovery owner still decides.

An exact restarted retry returns metadata-only CommitOutcomeNotCommitted. It never permits that command ID to execute again or renews any authority. A lost commit acknowledgement remains Unknown until the same original is reconciled. Generic queries and ordinary retired claims retain their non-disclosure behavior; retain fingerprint keys and the original native codec/configuration for retries. No second journal, mutable mapping, background cleanup or HTTP route is added.

The optional forward migration preserves earlier checksums and populated rows. It adds a nullable digest/check constraint and small invoker-rights triggers; typed fences reject UPDATE/DELETE, and command-claim TRUNCATE is rejected. Trusted schema owners can still bypass database enforcement and must not be application roles. Apply this upgrade before enabling the API. The ALTER/check validation and trigger installation take table locks and may scan existing claims; use the migration runner's bounded deployment window, including lock/statement budgets, and roll forward on failure. No downgrade, production-scale latency or live-rollout safety is claimed by the disposable PostgreSQL correctness tests.

Challenge-only MFA after an original UV passkey

The exact registered PasskeyMFAChallengeContributor can prepare a challenge-only identity.passkey.signin-verify.native-v1 command through the existing original-output journal. It retains the verified self-user assertion's command, original browser custody, current factor/policy versions and frozen continuation. Its only lifecycle is mfa.challenge.created.v1, version 0 to 1; ordinary known-empty-factor signin retains its historical representation.

Work.PasskeyMFAChallenge exposes that declaration only during the original owner's protected Apply. The owner must consume the genuine protocol assertion and persist its original primary, continuation and exact single-use child in that same Work, without a session. Apply and final checks must fence original expiry and current directory/credential/passkey/factor/policy/risk authority. The native flow must bound the child by the actual original primary; a scalar declaration or implementation of this interface authenticates nothing.

QueryPasskeyMFAChallenge observes the original profile under current query authorization. Only committed history discloses frozen child scope. Pending, aborted or foreign history cannot create a session or renew proof/expiry; recovery never repeats assertion verification or reveals another credential. These kernel APIs are not a complete native passkey/TOTP login or HTTP endpoint.

Additional passkey under an existing session

Work.CreatePasskeyCredential also admits exactly identity.passkey.register-verify.session-registration-v1 from the registered passkey/postgres owner. Bind the original PasskeyCredentialCreationFields and positive user/identifier/credential authority epochs. Its only lifecycle is identity.passkey.create_credential, event index zero and version 0 to 1. The historical passkey.registered.v1 alias remains limited to .native-v1.

This writer does not authenticate a session, assertion or registration. Native passkey orchestration must verify genuine action-bound UV and retain original session/CSRF, intent/expiry, current factor/directory/policy and mapping checks inside the same Work. Existing or disabled references conflict rather than being replaced; creation does not advance user security epochs. Complete native enrollment and reference composition are required before reporting that journey usable. No new migration, transaction, proof or replay owner is introduced.

Passkey-only prospective creation

After actual initial session persistence and its full current-owner checks, the session owner calls Work.StagePasskeyRegistrationSession with that exact original command and its command-bound session.result.session.id. This is provisional event staging, not session validation or token issuance. Duplicate, foreign, mismatched or overflowing staging aborts. The existing outbox participant must implement PasskeySignupSessionLifecycleContributor and persist StagedPasskeyRegistrationSessionLifecycle when present. An older account-only contributor aborts instead of silently omitting this required event. Its next unused index follows the unchanged credential/account indexes; existing effect IDs and encoded plans remain unchanged. Legacy account-only profiles produce no session event. The native signup journey must prove all three events and actual session persistence atomically; these kernel contracts alone do not.

PasskeyRegistrationIntent contains a trusted generated prospective user, already admitted attributes and an initial passkey-owned CredentialRef, not authenticator material or signup permission. Bind PasskeyRegistrationFields unchanged into the original identity.passkey.register-verify.signup-v1 command: its subject is the original anonymous flow and its actor is the configured service account. registration.user binds the real protocol participant's prospective subject. The command record is the new credential reference.

Append PasskeyRegistrationMigrationSource{Base: installedHistory, Version: next} after credential references, registration/acceptance and all selected historical magic-link/username suffixes. It extends the existing original-command evidence; it adds no journal, backfill, email, password or recovery method. Old rows and predecessor migration bytes remain unchanged. Native signup is explicit opt-in; installing this schema does not enable it.

Enlist the actual repository, PasskeyRegistrationContributor and PasskeyRegistrationLifecycleContributor. Freeze the prospective IDs, complete creation digest and distinct account-creation event index in CommandPlan.PasskeyRegistration. During that exact native Apply, after real WebAuthn verification, NewPasskeyRegistrationDomain.Apply creates the active initial user/attributes and passkey reference inside the sole Work. Duplicate, foreign/reconstructed commands, changed intent and existing subjects deny. The returned user is provisional. Work.PasskeyRegistrationUser lends only that actual creation during Apply/final Check, including original correlation and current initial user/reference authority; it is not a renewable proof.

The outbox must persist both the canonical zero-to-one identity.passkey.create_credential primary event and Work.StagedPasskeyRegistrationLifecycle (user.created.v1). Native risk, pre-auth consumption, protocol finalization, known-empty MFA, authorization initialization and session issuance must commit in this same Work. This kernel seam alone is not a working signup/session API. Retained original-command creation evidence and canonical plan decoding support recovery without inferring success from an existing user or revealing session material.

Anonymous placeholder namespace

Append AnonymousIdentityMigrationSource{Base: installedHistory, Version: next} after identifier retirement, normalization and every installed successor before selecting anonymous identity storage. It adds the non-contact placeholder kind without changing existing contact rows or predecessor migration bytes. Database constraints reject verification, primary selection, display/contact values and noncanonical opaque IDs; ordinary email/phone recipient discovery stays separate. No destructive down migration or anonymous workflow is provided by this source. The native anonymous lifecycle and session effects remain in development.

NewAnonymousCreationDomain borrows the exact enlisted kernel repository. Include AnonymousCreationFields unchanged in the original native command; its closed identity.anonymous.signin.native-v1 profile uses an anonymous-flow scope, not a fabricated credential or permanent-user actor. Apply owns user, admitted-attribute and placeholder SQL in that same Work; changed/foreign or repeated intent poisons it. Work.AnonymousCreation lends only actual provisional creation to the current native invocation. The suffix also retains immutable original-command creation bindings for recovery after payload pruning; it is not an anonymous lifecycle store or a second command journal. Native risk, expiry, session, deletion and upgrade still require their owning composition.

Closed anonymous self-disposal

Append AnonymousDisposalMigrationSource after the installed anonymous creation and status/legal-hold histories. GetAnonymousDisposal preserves actual anonymous creation, placeholder and independent user/identifier/credential generations plus legal-hold version. It authenticates no bearer and grants no disposal permission. Freeze AnonymousDisposalFields before fingerprinting. The exact native identity.anonymous.delete.native-v1 owner then calls NewAnonymousDisposalDomain.Apply inside its original Work after real session, risk and pure retention admission. It rejects extra contacts/credentials, changed epochs/hold and missing/duplicate/reconstructed invocation. Delete/anonymize erase kernel attributes/profile and retain distinct irreversible identity tombstones; retain preserves those payloads but terminalizes authentication. All ordinary kernel SQL stays here. Check is the final same-Work read fence; original retained effect correlation supports recovery without inferring success from absent data. Anonymous lifecycle and complete session/family revocation remain their owners' atomic effects, not private SQL in the workflow. No general privacy endpoint, permanent-user deletion or upgrade is enabled by this component alone.

Guest disposal during permanent upgrade

Append AnonymousUpgradeDisposalMigrationSource after the installed disposal history before selecting the closed identity.anonymous.upgrade.native-v1 profile. Existing migration bytes and guest tombstones are preserved. The native AnonymousUpgradeContributor must independently validate the verified permanent target, guest possession and typed merge decisions. UserID and ActorID remain the permanent target; the distinct guest is RecordID. Missing one-use proof, protected counters or exact owner/schema/audit/lifecycle declarations deny.

During that exact Apply invocation, Work.AnonymousUpgradeConsumption exposes only the original provisionally consumed declaration. Call ApplyUpgrade with the unchanged AnonymousDisposalFields; all its SQL addresses the guest, never the permanent target. Work.AnonymousUpgradeDisposal exposes the actual guest effect only to that owner. CheckUpgrade repeats guest state and original hold before commit. Original retained disposal evidence supports recovery without reinterpreting target IDs or relying on prunable payloads. The native workflow must still fence target authority, apply supported merges and enlist the real session owner for guest revocation and exactly one permanent session. No generic capability feature, separate transaction or automatic endpoint is introduced.

Internal anonymous-upgrade issuance

The closed identity.anonymous.upgrade.prepare.native-v1 profile is a native preparation phase, not another public HTTP operation or the upgrade mutation. It selects only AnonymousUpgradePreparationContributor under the existing anonymous owner, with permanent user/actor, no record transition and one protected preparation audit. Original admission is issuance-free; only acknowledged generation may add exactly one identity.anonymous.upgrade grant through the existing capability issuance participant. A final command without that grant, recipient overrides, delivery, consumption or a schema alias is rejected. Both commands retain the canonical identity.anonymous.upgrade action and permission, with distinct exact schemas, record policies and command IDs.

The native owner must freeze both real sessions, merge intent, unchanged remember choice and original deadlines in the existing encrypted preparation. Signing alone is not durable issuance: commit this phase before the real one-use owner reserves the grant for the protected upgrade. Only that later command consumes the target action proof and applies risk, guest disposal, merge and session effects atomically. Neither preparation nor a retained signature authenticates an upgrade by itself. No additional transaction, journal or public endpoint is introduced.

OAuth authentication-age continuation handoff

The canonical native OAuth owner can select OAuthContinuationPreparationContributor for an original human authorization continuation. Ordinary preparation admission remains read-only. Only the separate checked start callback may CAS that existing continuation's current attempt pointer, atomically with this coordinator's acknowledged start marker. It requires Work.RequireOAuthContinuationHandoff and a locked, exact same-human/tenant/grant/schema/policy predecessor whose immutable receipt is NotCommitted with OAuthReauthenticationRequiredError. Unknown, pending, committed, missing and other failed history cannot authorize another attempt.

Append OAuthReauthenticationMigrationSource{Base: installedHistory, Version: nextVersion} before enabling this profile. It extends the terminal shape constraint without rewriting existing migration bytes or receipts. Use upgraded readers for the new denied classification. The OAuth owner must independently require genuine newer authentication and all current/original source, client and expiry checks, preserve the original token/request/deadline, and retain recovery access to every original attempt even after pointer advance. An unacknowledged start grants no generation or retry; recover its original command through the existing coordinator. This adds no transaction, journal, credential, freshness renewal or OAuth protocol implementation to the kernel.

Pending phone enrollment

NewPhoneEnrollmentDomain freezes the phone owner's exact metadata-bound normalization profile and positive identifier recycling cooldown. Install IdentifierNormalizationMigrationSource and IdentifierMutationMigrationSource in the selected history; no existing identifier is relabeled or reverified. PhoneEnrollmentFields binds the new candidate, tenant, subject, record and original user/identifier-authority predecessors before fingerprinting.

The closed identity.phone.send-verification.native-v1 profile requires a PhoneEnrollmentContributor under identity/phone/postgres / identity.phone version one, a self-bound original session, identifier.attached.v1 lifecycle 0→1 and required protected audits. It cannot consume an OTP or capability: this initiation profile issues a challenge; confirmation is a separate flow.

The coordinator locks and checks the original directory and number reservation, then invokes the native owner while those original epochs still hold. The owner must check/consume its actual action-bound fresh proof, current session, factor and risk policy and stage its purpose-bound OTP/SMS delivery in the same Work. Work.RequirePhoneEnrollmentCandidate accepts only that exact prepared candidate during this invocation, before the kernel mutation. It does not fabricate an existing or verified RecipientRecord or establish authority. The kernel then persists a pending, non-primary, unverified phone and bumps the user/identifier epochs through the existing CAS writer. Errors roll back all enlisted effects; absent kernel apply cannot produce a committed receipt. The final native check conserves original validity, not a newer admission.

Recovery treats an existing target as unknown, never as proof of commitment. Only target absence can contribute negative evidence; all other participants and the original command journal must independently reconcile the outcome. Construction, fields and the storage participant alone are not a public phone enrollment service, OTP verifier, delivery sender or HTTP endpoint.

Native username rename and advisory discovery

NewUsernameRenameDomain freezes the explicit comparison profile, retained identifier-reuse keys and cooldown. UsernameRenameFields binds every original user/identifier/verification predecessor. The exact registered native username contributor must supply real password/session/factor/risk admission; the kernel alone swaps the owned identifier and writes keyed retirement history. The identifier.updated.v1 lifecycle and required protected audit share that Work. Same-canonical display edits preserve possession/time and create no retirement; actual canonical changes reset possession and conserve the original cooldown. This typed storage seam is not a standalone public rename workflow.

domain.UsernameAvailable reads primary occupancy and live keyed cooldowns. Historical/unbound or inactive-account reservations still block uniqueness; missing historical keys or schema deny. Supply only an exact canonical value and profile, never an owner-exclusion selector. The owning workflow must enforce trusted tenant/network rate policy before exposing this advisory result. It locks/reserves nothing and cannot promise a later signup or rename will succeed.

Username lookup and protected admission

ResolveUsername reads one tenant-scoped canonical username only when its stored normalization profile/version matches UsernameQuery. Legacy unbound names, absent, inactive and revoked users/names return the same suppressed record. Pending username state is permitted; it proves neither a verified delivery channel nor authentication. Install status and credential-authority histories alongside identifier metadata before using this reader.

The workflow must independently verify its required email, password and factor policy, then call Work.RequireUsername on the exact original record during its registered native invocation. The fence locks current user and identifier rows until transaction termination, denies changed ownership/profile/versions and poisons the Work on failure. It grants no lease, session or new freshness. The exact username password-signin profile may apply an atomic password hash upgrade through the existing credential owner, not a separate write path.

Username registration provenance

The exact identity.username.signup/username-signup v1 and identity.username.signin/username-signin v1 profiles reuse the registered identity/password/postgres contributor's paired custody and sole coordinator. No other cross-owner tuple is admitted. This registration is not an enabled workflow, proof of username policy, or HTTP exposure.

For required-email username signup, install normalization binding, original registration/acceptance and email-verification histories, then append UsernameRegistrationMigrationSource{Base: history, Version: nextVersion}. Install any already-selected historical magic-link registration suffix first; this successor retains its disposition arm without activating that workflow. It adds no account, inferred origin, backfill, transaction owner or journal. Legacy password origins retain their exact bytes and empty operation selection. Username confirmation supplies EmailVerificationIntent.RegistrationOperation as identity.username.signup; this freezes its distinct original purpose in the command and retained foreign-key evidence. Never relabel the origin.

This experimental adapter uses authentication v2, authorization v3, capability v2 and password v2 together with the matching identity kernel. Update supplied primitive values to those major imports. Existing migration source bytes and stored database history remain unchanged.

Optional canonical-policy binding

Compose IdentifierNormalizationMigrationSource{Base: existingHistory, Version: nextVersion} before selecting username support. The forward migration preserves existing values as explicitly unbound empty/zero metadata; it does not normalize or backfill legacy identities. Existing readers remain usable without this optional schema. Bound records retain the exact profile/revision through primary/locked reads and CAS writes; malformed or partial stored pairs fail closed. The feature owner, not this storage layer, proves canonicalization.

PasswordRegistrationIntent.Username can reserve one supplementary username atomically with its required email, user, password reference and original registration receipt. Include PasswordRegistrationFields unchanged in the original command. Collision checks cover both values under the existing tenant fence; neutral occupancy creates neither account nor credential, and rollback removes every provisional row. This native storage capability is not by itself a public username signup service or authentication proof.

Native organization invitation send uses the existing preparation journal, capability issuer and encrypted delivery effects, not another workflow owner. OrganizationInvitationIssuanceContributor must validate original owner/session, organization, recipient and limits before generation. In each protected Work, RequireOrganizationInvitationRecipient reuses primary recipient/authority locks and retains an invocation-bound verified-email selection. Apply must repeat the fence before StageCapabilityIssuanceFor; a preparation Work cannot grant later issuance. Final checks can call the existing RequireRecipient again without recording a second issuance selection. Original invitation expiry, recipient, member role and all five signed scope caveats must match; no subject override is added. The native owner separately enforces current owner and organization policy.

The separate identity.organization.invitation.resend operation selects only organization-invitation-resend v1 with the same typed native owner. Its exact positive invitation version advances once, and the new capability binds that successor; initial send still uses 0-to-1. Resend requires the canonical identity.organization.resend_invitation audit with standard retention and the informational invitation.resent.v1 event. It cannot reuse send's created event or audit. Native ownership must atomically supersede the old proof, preserve the original exclusive expiry/recipient/member role, and enforce current authority and limits alongside one issued grant and one encrypted delivery. This kernel profile alone does not implement resend or confer permission to renew a grant. Pending/aborted preparation history uses the original frozen journal declaration, not regenerated credentials. Resend's existing immutable invitation row anchors its organization; the optional send-origin profile below is unchanged.

Send owners additionally freeze OrganizationInvitationOrigin with the exact original command's organization.id and organization.version. The existing preparation declaration retains it before generation; final attachment cannot change it. QueryOrganizationInvitationOrigin lets that exact registered owner, under current command-query policy, resolve safe original organization metadata even when no invitation row or generated output exists. Authenticate a fresh session and current organization/action access separately before asking the sole coordinator to reconcile. The returned version is historical correlation, not current authority. Missing/legacy correlation fails closed; neither row absence nor this read proves noncommit, renews a lease or authorizes redelivery.

Acceptance requires OrganizationInvitationConsumptionContributor, the actual one-use capability participant and OrganizationInvitationLifecycleContributor. OrganizationInvitationConsumption exposes original custody only during the exact owner's Apply, after provisional consumption. After successful native membership SQL, record OrganizationInvitationMembership with the real retained member version; StagedOrganizationInvitationMembership emits index1 alongside the primary index0 invitation's exact positive-version successor event (initial acceptance is 1-to-2). Rejoining a removed member advances its actual tombstone, not invitation versions. No ignored recording failure can leave usable Work. Capability finalization, both events, audit and mutation must commit together; any failure rolls back. Metadata is not proof or a commit receipt.

For the exact public-password OAuth continuation or native device approval, OAuthConsentContributor records an independent OAuthConsentMutation after its actual successful SQL. The authenticated command freezes oauth.consent-id, oauth.consent-before-version, oauth.consent-after-version and oauth.consent-created; native validation also binds the original client. OAuthConsentLifecycleContributor persists primary grant index0 and the StagedOAuthConsent index1 event in the same outbox. Creation is consent.created.v10-to-1; repeat explicit approval retains the consent ID and emits consent.reconfirmed.v1 with its real positive predecessor. This does not invent a grant scope change, expose consent fields as permissions or acknowledge downstream consumption. Zero, foreign, wrong-phase or repeated mutation receipts deny; required secondary owners cannot be replaced by a single-event contributor.

The optional device child declares only identity.oauth-server.device-authorize, device-token, device-approve and device-deny through the existing oauth-server/postgres contributor, using each exact native-device-v1 schema. Authorize/token use anonymous-flow bindings; approve/deny use authenticated-user bindings. Only human approval with grant.authorized.v1 selects the independent consent contribution. Registration alone authenticates neither client nor user and does not initialize device storage or expose a route.

For client-authenticated polling of an approved human grant, RequireOAuthDeviceGrantSource fences the source user's exact credential, independent user/identifier/credential epochs and user-policy authority in the same Work. It admits only the exact native device-token command during its owner's preparation, apply or final invocation, checking its original source, client and grant selectors. The command's client actor and anonymous flow never become the source user. Current withdrawal poisons Work; credential expiry is checked again after authorization lock waits. Derive expectations through the session owner's OriginalDeviceGrantAdmission; the native owner must still match the complete original session to its locked grant, fence directory, session, client and consent authority, and retain original temporal bounds. This check is neither authentication nor a renewable validity lease.

These are library prerequisites. Complete native invitation/OAuth consumers, their public dependency pins, real delivery/denial/replay/rollback acceptance and whole-unit qualification remain separate requirements; these declarations alone do not deliver either complete consumer milestone. Existing migrations and non-selected declaration encodings are unchanged.

Scoped lifecycle-catalog additions for these profiles are invitation.created.v1 (invitation0-to-1), invitation.accepted.v1 (positive invitation successor), invitation.resent.v1 (the same invitation's positive successor, not a membership/organization-authority cascade), and consent.reconfirmed.v1 (independent retained consent successor). The existing membership.created.v1 and consent.created.v1 semantics remain unchanged. These safe informational envelopes do not alter current-authority epochs, grant membership or acknowledge cascade completion; consumers selecting the new transitions must register their exact event names.

Pending managed email attachment

The independently selected OTP profile uses OTPEmailVerificationFields and RequireOTPEmailVerificationTarget with the actual registered OTP contributor, not a capability/link substitute. It binds the original OTP Send, exact pending identifier/CAS and email_verification_otp before comparison. The user partition is locked before credential/factor/session rows. Only this Work's exact persisted identifier successor is admitted to its final authority checks; no original credential, user, authorization, session freshness or expiry is renewed. The shared directory writer and protected audit remain the mutation owners.

Primary-change OTP uses OTPEmailChangeFields for genuine replacement and the additive OTPEmailInitialPrimaryFields for explicitly selected first-primary establishment. Both authenticate the original change and independent Send; RequireOTPEmailChangeTarget locks the complete partition before comparison. Initial establishment requires the original sole verified predecessor and no primary, preserves the old row's versions and cannot reinterpret a generic add.

Native verified-phone replacement

NewPhoneChangeDomain selects the existing directory/recycling owner and a purpose-bound IdentifierChangeCascadeConfig. Retain a distinct policy version from removal when both are installed in the same tenant. Apply PhoneChangeCascadeMigrationSource after its phone-removal predecessor and all other selected migrations before enabling replacement.

The exact identity.phone.update.native-v1 participant must implement PhoneChangeContributor, preserve both numbers/profile bindings and original send custody in PhoneChangeFields, and use RequirePhoneChangeTarget during input admission before any OTP comparison or debit. The sole coordinator applies one versioned verified replacement, retires the old canonical value under the existing keyed cooldown policy, and admits ten pending identifier-change consumers. It never acknowledges downstream cleanup or creates a second journal. Only this Work's own persisted successor can advance OTP's final identifier expectation. Historical recovery cannot infer success from today's directory. The self-only consuming profile requires the canonical identity.identifier.change audit with standard retention; an unrelated action or a protected-retention declaration does not match this selected profile.

The actual native phone owner must still prove new-number OTP possession, recent action-bound authentication, current session/factors/risk, independent recovery, session effects and the encrypted old-number notification in the same transaction. This directory extension is not that workflow or an HTTP route; ordinary replacement and existing enrollment/removal semantics are unchanged.

Native safe removal

Administrative intents additionally freeze EmailRemovalAdministration with the actor's original global/tenant authority epochs. RequireEmailRemovalSubjects locks those authorities and both users in canonical order before either user's credential/factor/session checks; execution repeats this before identifier locks. Use RequireActiveActorCredential and RequireActiveActorAuthorization for the actual human actor, without replacing the target-scoped command binding. These fences grant no policy permission or proof. Native participants still own fresh original proof consumption, both MFA generations and exact target access.

EmailRemovalContributor supplies frozen EmailRemovalIntent and the enlisted EmailRemovalDomain. The coordinator alone locks the complete partition and applies the existing directory writer. Native Apply owns original proof, factor/risk and actual remaining signin/reset eligibility, with capability retirement through Work.EmailRemovalScope. That scope denies foreign, reconstructed, unprepared, already-applied and returned invocations.

Install IdentifierRemovalCascadeMigrationSource after status admission and identifier-retirement histories. It extends the existing identity-owned cascade tables without another journal or rewriting installed source. All ten versioned consumer contracts are required; unavailable adapters stay pending, never implicitly acknowledged/not-applicable. Cascade policy versions share the status namespace: incompatible definitions require distinct versions. Admission retains exact identifier authority, event, generation, legal hold/version and deadline atomically. The pending receipt is not consumer closure/whole-unit qualification.

The distinct identity.email.verification-send.resend-v1 declaration reuses EmailAttachmentContributor for IdentifierRestartVerification. Its intent requires ExistingCanonicalAddress and exact identifier/verification versions; attachment leaves that field empty. Resend preserves the pending mailbox and advances its verification generation through the same private writer. The native owner must still enforce fresh authority, cooldown and shared family fencing, and commit replacement issuance/encrypted delivery together. This storage seam does not supply a complete public resend service.

ManagedEmailVerificationContributor supplies exact authenticated original management intent for identity.email.verification-confirm.managed-v1. The coordinator uses the same identifier writer and capability transaction, while keeping signup verification and generic execution closed to this profile. ManagedEmailVerificationFields binds the original request, mailbox and pending predecessors. Only a pending non-primary address can transition to verified; this profile performs no primary swap or session issuance. Recovery reconciles all enlisted owners; a changed/missing successor is not proof of noncommit.

EmailAttachmentContributor is the typed native port for authenticated identity.email.verification-send and identity.email.change-request attachment under their version-one native schemas. It maps frozen EmailAttachmentFields and an immutable EmailAttachmentDomain tied to the exact enlisted repository. The coordinator locks the complete partition, checks optimistic versions and canonical reuse restrictions, then applies the shared kernel-owned CAS writer after native admission. The new address remains pending/non-primary and the existing verified primary is unchanged. Proof and required audit/lifecycle writes roll back with late final-admission failure. Generic identifier Begin stays closed.

The native email owner must provide original fresh-proof/session/factor/risk checks and enlisted capability issuance/encrypted delivery. This kernel port is not an application-written email workflow, delivery service or verification endpoint. Original command recovery must remain scoped and cannot infer a committed receipt merely because an address currently exists.

Anonymous MFA login-send counter source

MFALoginSendCounterContributor lets the registered native MFA owner lend its authenticated original resolved account to the exact counter invocation. CommandCounterWork.MFALoginSendScope and the current-check counterpart accept only the closed anonymous OTP-send profile, preserve original browser identity and reject foreign, returned or other-profile custody. The journal remains anonymous; these methods create no session, fake child-consumption plan, store or proof. The source's protected input/commit checks remain mandatory.

Native OTP enrollment confirmation

The closed authenticated identity.mfa.otp-verify / mfa-otp-enrollment-confirm profile can retain one native consuming attempt in the existing preparation journal. Original protected counters, factor lifecycle, audit and static intent stay unchanged. Restoration adds only OTP's actual consuming contributor/plan; it cannot introduce a login child, capability, delivery or session effect. Ordinary OTP admission profiles remain separate.

FeatureInputAdmissionContributor supplies the exact registered MFA owner's original primary/factor/recipient checks before OTP counted denial and consuming reservation, and again after waits before commitment. Its synchronous scope does not acquire Apply-only command authority. Failures poison the complete transaction; no callback result becomes independent authentication evidence. The existing counted-denial phase commits wrong-attempt/audit/history together. Correct verification proceeds through the real reservation, protected Work.OTPConsumption, feature activation and OTP finalization in the sole coordinator. Retained output and terminal replay never generate another attempt.

Use the native MFA confirmation service, not application-written orchestration. The profile is not OTP login completion or an authorization to omit a pending feature's current admission, configured protected risk or consuming history.

Atomic MFA completion

CommandPlan.MFACompletion selects the session-producing alternative of the anonymous-flow identity.mfa.totp-verify, identity.mfa.otp-verify, identity.mfa.recovery-use or identity.mfa.security-key-assert-verify version-one operation. Their schemas are the corresponding mfa-* names. The command remains the named factor operation; identity.mfa.complete is the original child's capability purpose, not another public endpoint. Enrollment verification without this declaration retains its existing profile.

The closed declaration binds the original child ID, subject, immutable scope digest and expected continuation/factor/policy versions. It requires the exact identity/mfa/postgres, identity.mfa version-one native owner implementing MFACompletionContributor, protected authentication audit and session.created.v1. OTP verification additionally requires its consuming OTP plan/owner; other factor methods reject OTP consumption. No new capability issuance, delivery, signup or challenge-only branch is permitted.

The native owner must validate original grant/browser/primary/remember custody, fence current authority and shared attempts, verify the actual selected factor and persist continuation completion plus session effects in the sole Work. Work.MFACompletionConsumption(owner) returns owned frozen metadata only after provisional consumption, only to the exact protected Apply invocation. It is not a factor proof or session grant. Preparation and restoration preserve all original versions, capability and optional OTP submission. The existing coordinator owns finalization, audit/lifecycle, commit and recovery; late denial rolls back protected effects, and a committed retry returns the original receipt.

For TOTP failed attempts, PrepareMFATOTPAttemptPlan and RecordMFATOTPAttemptDenial enlist the exact MFATOTPAttemptContributor. The existing journal transaction locks the original command before calling the native owner through bounded MFATOTPAttemptWork. Native wrong-attempt accounting, denial audit and an aborted command result commit together; exact replay does not compare or charge again. Unchanged rolls back and grants no successful-factor authority. No child, OTP or session reservation is invoked. When protected counters are declared, the native callback must call MFATOTPAttemptWork.ReserveCommandCounters once after browser/current-authority admission and before comparison. Risk denial must return native denial without comparing the factor. Missing charging or ignored denial aborts. Wrong-code denial commits risk, MFA budget and audit in the same transaction; correct-code Unchanged rolls the provisional charge back. Sealed counter scope access binds the original MFA subject and child without granting factor/consumption authority. The native owner must verify the real factor and lock/recheck the current continuation and shared budget. Successful completion uses the retained preparation route, preserving the original opaque TOTP submission and verifying it again under protected current authority; ordinary opaque execution denies.

These kernel seams do not implement factor verification, the production shared-budget mutation, continuation store or MFA session issuance. Public MFA remains disabled until those owners and the consumer journey are connected.

Original MFA challenge preparation may declare only selected user/policy/factor while omitting ID, scope digest and both timestamps together. Only PrepareFeaturePreparationPlan admits that ungenerated form; ordinary reservation and history decoding reject it. The acknowledged original generator supplies the complete child through the existing retained output and issuance owner. Final scope preserves selected authority, original primary consumption, required audits and challenge-only lifecycle. This enables native composition; it does not itself implement public MFA challenge issuance.

The exact anonymous-flow identity.magic-link.consume, magic-link-consume version-one profile enlists identity/magiclink/postgres and the existing capability/postgres one-use owner. Declare the original purpose-bound CapabilityPlan, command counters, protected authentication audit and session.created.v1 lifecycle with zero directory-version transition. Proof-free, reset, OTP and issuance/delivery profiles cannot substitute.

The native owner must implement MagicLinkConsumptionContributor, including pure original-input validation and a final current-authority check. Its exact ApplyFeature invocation may inspect Work.MagicLinkConsumption(owner) only after provisional capability consumption in the same transaction. The returned binding is not a bearer, authorization or a committed result; foreign, retained and final-check invocations deny. The owner must authenticate the original grant and issuance, pre-auth possession, callback and recipient, enforce current factor/risk policy, and persist the complete native session.

Capability finalization, native effects, audits, lifecycle and journal share the sole coordinator transaction. Any late denial rolls them back; original exclusive expiry is rechecked by the capability owner without renewal. A committed retry returns the existing journal receipt. No additional replay store or original-intent journal is created. This kernel profile does not itself provide public magic-link APIs or native session composition.

CommandPlan.MFAContinuation has a separate challenge-only historical profile. It freezes the target, MFA scope digest, policy/factor generations and original time bounds together with primary consumption and exactly one identity.mfa.complete issuance. Its lifetime is at most five minutes and never extends the parent proof. It cannot carry signup, delivery or a session-created lifecycle. Original preparation declares these immutable fields without an issuer or signed child. Restoration must add exactly one child without changing any original field or primary proof. Historical session-producing bytes remain unchanged. Registry admission requires MagicLinkMFAChallengeContributor and its pure original-scope validation; session-only owners deny. During protected Apply, Work.MagicLinkMFAChallenge exposes an owned projection only after provisional primary consumption. It grants neither current factor authority nor completed MFA. Public MFA composition remains incomplete until native continuation persistence and the real issuer's challenge recovery are integrated. CapabilityIssuancePlan.MFAContinuationUserID selects only the frozen challenge subject after primary consumption. Staging checks the signed child's tenant, subject, resource, original time bounds and exact profile/scope caveats; it is not a general anonymous subject override. Original preparation without a signed child cannot begin protected domain work.

For signup-by-link preparation, the native owner calls MagicLinkRegistrationDomain.AdmitProspectiveMailbox with its email-owned canonical address. This checks all occupants and live retirement policy under the original preparation invocation, without allocating future IDs or staging issuance. An eligible-recipient lookup's suppressed result is not proof of absence. Preparation availability is not reusable authority: its locks end before generation.

Declare CommandPlan.MagicLinkRequestAcceptance in both original and restored plans to preserve the neutral no-delivery branch. At protected request Apply, SelectProspectiveRecipient repeats the current collision check with the original generated identity. A canonical collision can commit the request audit/lifecycle without invoking its prepared issuer or delivery. Structural future-ID conflicts and unavailable retained keys still abort. Missing branch declaration or kernel admission cannot silently suppress planned effects. This does not authorize account creation, email possession or session issuance.

For prospective signup, the selected native request calls MagicLinkRegistrationDomain.RequireProspectiveRecipient with its frozen MagicLinkRegistrationIntent. This reuses the kernel's tenant and identifier retirement fences, rejects occupied account/identifier/email selections, and creates no account or MFA state. The issuer's explicit PrepareMagicLinkProspectiveRecipient profile signs the creation digest, mailbox-policy version and future identity versions; ordinary existing-recipient preparation cannot select that profile. The original anonymous command and issuance plan envelope remain unchanged. Consumption must independently create the exact account, prove possession, initialize real factor authority and issue the session atomically. Public signup composition remains in development.

Native magic-link request contributors use the exact identity/magiclink/postgres owner, identity.magiclink contract version one and anonymous identity.magic-link.request operation. CapabilityIssuancePlan.MagicLinkRecipientUserID selects one existing verified-email recipient for one identity.magic-link.consume grant. It cannot coexist with either password-specific target and does not change the command's original anonymous flow. Existing plan encodings stay unchanged when this field is empty; readers without this additive profile deny new plans.

Before StageCapabilityIssuanceFor, call Work.RequireMagicLinkRecipient with the frozen original RecipientRecord during the exact contributor invocation. The kernel locks and rechecks current user, identifier, verification and security versions. The authenticated grant must match that recipient, original command, resource identity.magiclink/<identifier ID> and the magiclink.identifier, magiclink.canonical-email, magiclink.identifier-version, magiclink.verification-version, magiclink.identifier-authority-version, magiclink.user-authority-version and magiclink.credential-authority-version caveats. Versions use canonical unsigned decimal strings. Metadata alone cannot select a recipient; failures poison the existing transaction.

This seam supplies neither authentication nor factor permission. The native workflow still owns original pre-auth/device/callback intent, current factor and risk admission, encrypted delivery, supersession and atomic consume/session composition. It must not relabel a password reset grant or call ordinary session issuance after a separate consumption commit. Complete public magic-link composition and package release qualification remain in development.

Reset completion uses the canonical Authentication risk profile, which counts the attempt before credential work. PrepareFeaturePreparationPlan accepts its original NewFeaturePasswordResetInputCommand under the exact native FeatureAdmissionPreparationContributor and CredentialResetContributor. ExecutePreparedFeature retains the admitted generation in the existing journal; its final plan must preserve every original capability field and contributor. No delivery, issuance, new counter or renewed proof may appear during generation. Ordinary reservation rejects original input, and counter-free reset execution requires original admission, ciphertext, generation and generated execution custody. The kernel rechecks retained admission before mutation and commit. Historical session-counter-bound reset plans retain their original encoding. Native admission must still authenticate the original risk/HIBP facts and enforce all current recovery fences; public workflow composition remains in development.

Reset command intent binds the exact original opaque proof (including signature) and replacement verifier through separate keyed fields, never raw journal values. The fingerprint does not verify, transfer, reserve or consume the proof and stays stable for retained-key recovery after expiry. Keep original proof custody alive through bounded execution; terminal upstream transfer denies further binding. Generic reset metadata cannot substitute for the paired command. The distinct reset transaction profile requires CredentialResetContributor, a one-use capability participant and CredentialResetLifecycleContributor; authenticated password-change admission cannot substitute for reset admission. Append CredentialResetMigrationSource after the credential-replacement migration, using a new allocated version. Historical migration checksums remain unchanged.

CredentialResetFields binds independent user, authority and credential predecessors plus the original reference enablement. Only explicitly authorized reset can restore a disabled reference; blocked users and expired references remain denied. Native verifier mutation, kernel version increments, protected audit, required lifecycle/session effects and capability finalization share one Work. The native owner must validate original signed recovery scope, factors, current identifier authority and password policy, including HIBP. Pending-journal recovery never reconstructs success from a retained effect. This kernel seam is not complete public password-reset orchestration; production password/session composition and release qualification remain required.

Original anonymous password signup uses PrepareFeaturePreparationPlan followed by ExecutePreparedFeature. The original root input command carries the real password Secret and pre-auth cookie, not an already-generated hash. Keep the Secret alive for bounded execution and destroy it afterward. Ordinary PrepareCommandPlan and reservation reject this input; the native owner must restore its generated verifier and recheck admission before atomic execution. The same command journal and retained-key codec own original replay identity.

Native registration domain

NewPasswordRegistrationDomain(repository, config) constructs the kernel participant used by the native password-registration workflow. It does no IO, starts no goroutines and borrows the exact repository/pool enlisted with the sole coordinator. Configure the exact versioned identifier comparison profile and the retained reuse keys used by identifier removal; missing keys fail closed while live retirement history references them.

PasswordRegistrationFields(intent) binds prepared permitted attributes, their schema, the created user, canonical identifier, initial credential and comparison profile into the original signup command. Include every returned field unchanged before admission. Attributes are committed without putting a serialized attribute blob into feature metadata. Neither helper authenticates, canonicalizes input, approves fields or grants registration policy.

The native password owner calls domain.Apply(ctx, work, participant, command, intent) only during its original protected Apply invocation, after HIBP/risk, pre-auth and password preparation. The kernel creates user/attributes, an unverified non-primary identifier and an enabled version-one password reference; the native owner must insert its material through the same Work. Provisional results are not authentication or durable success. The coordinator refuses a signup receipt without its actual kernel creation and commits required audit/outbox/native effects together. Never chain UserCreate, identifier attachment and password persistence as separate registration commits.

For enumeration-safe anonymous signup, freeze CommandPlan.SignupAcceptance as true before reservation and call domain.ApplyOrAccept instead. The creation declaration remains user.created.v1; the opt-in profile additionally declares identity.password.signup.accepted.v1 at the same event index and zero versions. Canonical occupancy and live retirement are classified under the existing tenant fence. A neutral result is (zero User, true, nil): insert no password material, session, verification grant or delivery, but still run original pre-auth/risk and final admission checks. The coordinator commits the protected audit, neutral event and retained original acceptance binding together. Generated structural-ID collisions, unavailable retirement keys and other failures are never neutralized. Neither provisional result authenticates or reveals an existing account.

Append PasswordSignupAcceptanceMigrationSource after the registration migration before enabling this profile. Its forward migration preserves creation receipts and adds a closed all-NULL record arm for neutral acceptance; it does not create another journal. Historical plans retain their exact bytes and strict creation requirement. The new opt-in plan fails closed in older readers, so deploy compatible readers before enabling it. Prepared restoration must retain the original opt-in flag; it cannot add/remove the branch after admission. A prepared neutral commit intentionally leaves declared prospective issuance and delivery unused; any staged credential or envelope instead denies the commit. Original replay/recovery cannot regenerate effects or expose account identifiers.

Append PasswordRegistrationMigrationSource at an explicitly allocated version after the complete credential-reference and identifier-retirement history. Existing history and populated accounts are not rewritten or inferred to be signups. identity.registration_bindings is retained original domain evidence, not another journal: it links the signup command to its created record IDs and survives pruned account payloads. Primary recovery keeps the original command namespace and cannot regenerate an account or infer rollback from cancellation.

This kernel operation is a development prerequisite. The complete native signup service, verification delivery, optional session issuance and release qualification remain pending; applications should not implement their own workflow around this low-level seam.

Construct the original native password-signup v1 command with identity.NewFeaturePasswordSignupCommand(spec, preparedHash, originalCookie). The coordinator fingerprints the exact hash and cookie in distinct retained-key domains, with no raw material in the journal or safe collision scope. Scalar and cookie-only commands cannot impersonate this profile. Changing either input changes command intent; recovery must keep the original command, not regenerate its hash or submit a replacement cookie. Other independently registered signup schemas are unaffected. This identity binding neither admits the cookie nor proves password policy; the native workflow owns those checks.

Exact native command custody

Adapters staging a native feature command must call Work.RequireFeatureCommand with the supplied command before using its payload. It admits only an unchanged copy of the original command in that registered owner's active Apply invocation. Reconstruction, even from equal-looking fields and the same secrets, denies and poisons Work: ignoring the error cannot commit earlier provisional writes. FeatureCommandIdentity only returns correlation metadata; it does not validate a candidate command. Existing metadata and successor accessors remain unchanged.

The closed joint phone-reset plan retains capability, SMS OTP and distinct completion risk as separate atomic participants; it cannot use a generic or emailed-reset command. Install PhonePasswordResetMigrationSource after the canonical credential-reset receipt history before selecting this profile. During its final OTP check, OTPApplyWork.RequireFeatureOrigin lets the native MFA receipt owner correlate its actual provisional replay write with the exact same live protected Work and registered feature owner. Scalar copies, another transaction, an incomplete Apply and returned callbacks cannot supply that correlation. The guard performs no IO and supplies no factor verdict or SQL authority. Ordinary RequireFeatureCommand and FeatureCommandIdentity remain Apply-only. Native complete workflow and factor/risk/password/session checks remain required; these kernel contracts expose no recovery endpoint.

The separate native request uses otp_challenge with otp.sent.v1 0→1 and original initiation-only risk. Its original preparation cannot consume an OTP or capability. Final attachment must retain the exact risk artifact and add one identity.phone.password-reset-complete grant plus encrypted delivery, with no recipient override. Current pre-auth, verified phone/password, independent factor, actual risk and issuer checks remain the registered native owners' responsibility. The existing phone domain-risk declaration stays readable and unchanged; it does not gain this preparation path.

Original-signin hash upgrades

The registered identity/password/postgres owner can compose a hash-only upgrade inside the original paired password-signin command. Freeze independent predecessor versions with PasswordHashUpgradeFields before fingerprinting. After directory admission, call Work.PreparePasswordHashUpgrade before any shared user/credential admission. This exclusively locks current predecessor authority and admits the unchanged selected recipient without a lock upgrade.

The native owner compares the original password and prepares bounded replacement material before opening Work. It performs its material CAS in that Work, calls ApplyPasswordHashUpgrade, and binds PasswordHashUpgradeSuccessor into its own proof/session effects. Every failure must abort. Credential record, credential-authority and user aggregate versions advance independently; user and identifier authority and the original observation time do not change. Advancing credential authority invalidates predecessor-bound sessions: any continuation must follow an explicit session-owner policy, not this receipt.

The lifecycle participant can read StagedPasswordHashUpgrade after staging. Receipts remain provisional until the sole original command commits. A final kernel fence rejects missing application, expiry or changed successor authority, rolling back material and all effects. Only the exact original native Apply invocation can mutate or obtain successor admission; scalar fields grant no authentication. This API neither adds a password-change journal nor delivers tokens. Existing admission and replacement contracts are unchanged. Public signin composition with this seam remains required separately.

Final native feature admission

A native feature owner may implement FeatureCommitContributor in addition to the unchanged execution contract. The coordinator invokes CheckFeatureCommit with the original command after required audit/outbox, journal writes and other final checks, immediately before SQL commit. Use original expiry/admission facts and bounded primary reads; never renew facts, mutate, stage effects, perform network IO or retain Work. Existing owners without this optional contract keep their behavior.

Only the exact selected owner's synchronous check can use FeatureScope. Apply-only FeatureCommandIdentity remains unavailable. Callback failures, panics or unfinished rows roll back all provisional effects; SQL commit ambiguity keeps its existing unknown classification. This seam grants neither password authentication nor token delivery and creates no additional journal.

Original password-signin intent

The coordinator explicitly selects identity.NewFeaturePasswordSigninCommand for identity.password.signin, password-signin v1, record-free user or anonymous-flow scope. The original primitive-owned password and pre-auth cookie are borrowed together, fingerprinted in distinct password-signin-password and password-signin-cookie domains under the retained command key, and never persisted as raw bytes. Changed password or cookie is conflicting intent even after key rotation. Busy or destroyed password owners fail closed; callers must destroy the original owner after bounded execution. Plain scalar metadata cannot impersonate this exact profile. Other independently registered signin schemas, including existing CAPTCHA-protected commands, retain their historical mapping.

Native preparation and final-plan attachment preserve the disjoint command and its complete scope rather than using legacy accessors that omit its secrets. This structural transport grants no password authentication, cookie possession or session authority. Execution still requires an exact registered native owner to compare the password, enforce current policy and pre-auth state, and commit all session and security effects together. The complete native signin workflow remains under development. Recovery uses secret-free command correlation, not resubmission of destroyed secrets or reconstruction from a persisted digest.

Authenticated password-change intent

The coordinator explicitly selects identity.NewFeaturePasswordChangeCommand and fingerprints its original encoded hash, source bearer and complete upstream reauthentication proof under separate retained-key domains. Seconds and nanoseconds remain separate: timestamp rounding cannot make two proofs the same intent. Original versions retain all 64 bits. Equivalent time zones encode the same instant. Neither journal intent nor safe collision metadata retains raw verifier, bearer or proof values, and key rotation rebinds the original custody under the claim's retained key. Existing hash-only command encodings are unchanged.

This is structural mapping, not authentication or proof consumption. Execution still requires the exact registered native replacement participant, complete policy checks and the existing protected effect plan. The existing hash-only password repository rejects the authenticated variant. Native signed-proof and current-source validation, atomic consumption and the public password-change workflow remain under development; adding custody alone does not enable them.

Exact consuming OTP recovery

RecoverOTPFeatureCommand is the native consuming counterpart to metered-check and counted-denial recovery. Supply the exact original code-free OTPAttemptPlan and historical query scope under current QueryPolicy. It matches every attempt, fingerprint, scope, challenge and version field before disclosure and under the existing command locks before pending reconciliation. It does not compare a code, charge again, require the consumed pre-auth to remain executable, or return a session/bearer. Native orchestration must separately authenticate original possession and current disclosure scope. Historical outcomes grant no authority or credential redelivery; unavailable reconciliation preserves Unknown rather than inferring rollback. Existing recovery profiles remain separate.

Committed managed-email origin reads

QueryManagedEmailPreparation authorizes the actual current confirmation caller before reading the original committed management request. Signed origin, tenant, user and address must match its historical self-user native operation. Only verification-send -> verification-confirm and change-request -> change-confirm are admitted. The exact registered preparation owner must first authenticate the issued proof, then authenticate/decrypt output and authorize original intent. No historical live session or original-actor impersonation is needed. Original binding and journal generation are preserved, not renewed.

Returned ciphertext is an owned sensitive copy; clear it after use. Reads grant no mailbox ownership, remaining proof use or mutation permission. Noncommitted, foreign, retired and corrupt history fail closed. Existing preparation histories suffice; generic original-actor query/recovery rules are unchanged.

Request-key correlation before command preparation

For a signup verification link, the native owner can use QueryRegistrationPreparation(ctx, query, caller, feature, inputOwner). The query's command ID identifies the original signup, while its user, actor and identity.email.verification-confirm action describe the current confirmation context. Current query policy must permit that user/action; the kernel separately matches the committed anonymous signup, positive selected registration user and exact immutable input provenance. Never impersonate the original actor or invent a live pre-auth session to read this history.

This returns only caller-owned encrypted original input and its binding. The native owner must first authenticate the original signed registration proof, then authenticate the ciphertext and reconstruct/authorize its original email intent. Reading cannot verify an address, consume or renew the proof, issue a session, regenerate input or recover an outcome. Confirmation must still check current identity/capability state and perform all protected effects atomically. Existing registration, request-key/input and preparation migrations are required; no new schema or workflow authority is added. Clear returned bytes after use.

QueryRequestPreparation(ctx, query, caller, feature, inputOwner) returns only the original input binding and encrypted bytes. Use it for password-free native recovery when a mapping exists before its journal, generation is incomplete, or the command rolled back. The exact registered owner and current query policy are required. Original actor/tenant/POST route, namespace identity, feature and retained fingerprint keys are checked without callbacks, generation or mutation. Existing claims also fence complete query scope and original journal identity.

A mapping alone does not contain plaintext subject/flow/record scope. Before disclosing anything, the native owner must authenticate the complete envelope binding, compare its decrypted original scope with the recovery query, and check original bearer possession and current disclosure authority. Clear the owned returned ciphertext after use. Reading input establishes neither an outcome nor permission to execute. Use the existing coordinator's command query and recovery for outcomes; a missing journal never proves rollback. No migration beyond existing request-key/input custody history is added. This low-level seam is not the public signup/recovery workflow, which remains in development.

Native feature adapters can use QueryPreparedFeature to restore an existing committed workflow by its server-issued command ID without a new initiating key or caller-written store. The exact registered request/preparation owner and current CommandQueryPolicy must authorize the complete historical scope. The result contains independently owned encrypted input/output and their original binding/generation. Both envelopes still require native authentication, separate bearer possession and current authority checks; historical custody is not renewed authority. Missing, retired, pending, aborted or legacy incomplete history returns no custody. Lookup never recovers, generates, mutates or charges anything. Install the existing request-key and feature-preparation migrations; no additional schema is required. Generic QueryCommand remains metadata-only.

Native generated workflows can opt into ResolvePreparedRequestKey after installing RequestKeyPreparationMigrationSource{Base, Version} over the original request-key history. The exact registered feature owner prepares bounded authenticated code-free input outside SQL. The allocated command ID and ciphertext commit together in the existing immutable mapping; matching retries recover the original input without reselecting recipients or renewing times. Race losers recover the winner, and legacy mappings cannot be backfilled. Preparation may perform bounded reads/encryption, not risk charges, domain writes, delivery or OTP generation. Those follow acknowledged custody through the existing journal. Authenticate the complete returned binding and immutable configuration; include configuration in the initiating intent. Restore original input without treating it as current authority, and verify bearer possession separately. Unknown acknowledgement returns no usable input. This kernel seam does not itself implement the public OTP Send service.

Compose RequestKeyMigrationSource{Base, Version} after kernel history and use NewCoordinatorWithRequestKeys with a separate RequestKeyConfig. Existing CoordinatorConfig and NewCoordinator remain unchanged; the ordinary constructor leaves request correlation disabled. Construction performs no SQL. Use NewRequestKeyConfig(namespace, lookupKey, policy) to copy the nonzero 32-byte key into opaque custody; there is no raw key projection and nested configuration diagnostics cannot traverse its bytes. The first authorized resolve pins the configured random lookup key to its trusted deployment namespace; changing that key fails closed. Keep it secret and stable. Command-fingerprint keys rotate separately; retain every version referenced by a mapping. Stage new keys in both old/new processes before changing the current issuance version, so overlapping processes can verify the winner.

ResolveRequestKey accepts identity.IdempotencyKey, a trusted canonical RequestKeyScope and a complete immutable identity.RequestIntent. The lookup is namespace plus tenant, actual actor (ID/kind), method, canonical route ID and keyed client-key digest. Body, target user, purpose and options are not lookup dimensions: they belong in the independently keyed intent. Feature owners map every behavior-affecting field, including policy/schema and expected versions; applications do not supply private fingerprints, SQL or workflow callbacks.

The separate configured policy must authorize the current actor/tenant, route-ID action and resource identity.request-admission with that route ID. Owned resource attributes identity.request.admission, .method and .namespace replace caller overrides. Earlier cancellation/deadlines win. Policy decisions run outside transactions; database errors and panic are redacted.

Matching retries return the original random command and stored fingerprint-key version; different intent returns conflict without an ID. A lost commit acknowledgement returns unknown with no usable admission: retry the same key and intent, not a new key or namespace. Mapping never grants execution or a result. Recover the original command journal/native prepared state before generating another credential or provider effect. OTP Send composition is still pending.

Rows retain correlation indefinitely, including absent/pending/unknown journal state and retired command tombstones; there is no 24-hour reassignment. Immutable database fences reject updates, deletes and truncation. Operational storage retention is therefore an explicit tradeoff, not an implicit cleanup policy. Existing immutable migrations and default-disabled coordinator behavior remain unchanged; unsupported destructive downgrade must not remove retry identity.

Pre-generation journal custody

PreparationMigrationSource{Base, Version} adds optional columns to the same identity.commands journal; it does not create another workflow authority or enroll historical commands. The private preparation phases match the original immutable claim, acquire its journal lease, and commit a generation-start marker before any entropy, rendering or sealing outside the transaction. A competing caller cannot generate. An abandoned lease without a start marker can transfer; a start marker with missing ciphertext remains uncertain and cannot regenerate.

The original live generation can retain one bounded encrypted output. Exact byte retries are idempotent, replacement and erasure are fenced, and takeover receives the original ciphertext with its original generation—not permission to generate a new code. Lease checks use primary time after acquiring the row lock. The native feature codec must authenticate and bind that encrypted output; the journal does not interpret or decrypt it. A lost start-commit acknowledgement cannot authorize entropy. No SQL transaction is held across generation callbacks.

Installing these columns alone enables no public workflow. An opt-in stable native FeaturePreparationContributor can use ExecutePreparedFeature to consume the journal preparation and final execution path. Its original request is schema-validated and primary-admitted before committing the start marker. The owner generates bounded authenticated ciphertext outside SQL, then restores the exact original generated command and plan from retained output. The final plan preserves the initial feature, subject, mandatory audits and lifecycle; only original encrypted delivery may be added. The coordinator preserves the caller-request fingerprint, separately binds reconstructed execution fields, and executes through its existing atomic Begin/Apply/Commit owner.

Generated password hash/authenticated-change commands retain their disjoint native custody variant when the coordinator attaches the final plan. The legacy Feature accessor stays closed to those variants; native selection and the existing complete keyed hash/bearer/proof intent remain mandatory. The registered password owner still authenticates retained output and the original proof, checks current source authority, and owns atomic proof consumption. This is not a public password endpoint or a substitute for its native policy.

An optional FeatureAdmissionPreparationContributor can assess external facts before generation. Install AdmissionPreparationMigrationSource after the existing preparation source, with a later explicit version, before selecting this owner. The coordinator acknowledges its existing lease reservation and closes SQL before PrepareFeatureAdmission. It then reacquires that same generation/owner, repeats current primary admission, checks original local facts and commits the start marker. Admission is checked again after that acknowledgement before calling its invocation-local Generate.

FeaturePreparationAdmission.Check is strictly bounded and IO-free. The returned invocation captures the original request and admission, not shared request state. Its generated authenticated ciphertext must retain original admission custody; RestoreFeatureAdmission reconstructs a local check from that unchanged output/generation without provider, counter or generation IO. The coordinator checks local admission again after final Begin waits and just before commit. Current account/flow authority remains the native owner's job; this seam does not supply risk facts, authentication or a one-use artifact.

Busy, terminal and started-without-output replay never assesses externally. Retained output calls only IO-free restoration. Failed external admission leaves its acknowledged pending lease but no generation marker; retry remains under the existing journal and native risk owner's original-attempt replay rules. Nil/failed admission denies; provider diagnostics are redacted and cancellation/deadlines remain attributable. Unknown start acknowledgements cannot generate. Immutable profile 2 rejects legacy/profile-1 takeover rather than silently bypassing admission; historical profile 1 is not enrolled or reinterpreted. This is native composition support, not public OTP Send or proof of real risk/provider integration.

During final ApplyFeature, that exact registered preparation owner can read Work.FeaturePreparationOutput to restore invocation-local custody. It returns an owned ciphertext copy and the original output generation, even after a later lease generation takes over. Admission, ordinary execution, recovery, foreign instances and returned/closed handles have no access. This avoids shared per-request state and does not expand generic command-field size limits. The adapter must still authenticate its existing envelope, separately verify bearer possession and recheck current authority and expiry before staging effects.

Use one immutable comparable native owner across all phases, with per-invocation state; never replace the registry after generation or share mutable prepared delivery between requests. AdmitFeaturePreparation borrows Work only for current checks, not generation, effect staging or domain mutation. It can reuse existing exact-owner directory/user/credential/authorization helpers. Every final execution must recheck current admission after waits. Restore authenticates the complete original request/generation and separately submitted bearer; it cannot remap output, manufacture authority or renew expiry.

Terminal matching replay returns the original receipt without another native generation/restore invocation. Started-but-unretained output stays in progress after lease expiry. Lost start acknowledgement runs no generation; lost retained output acknowledgement returns unknown and retry can recover the original bytes. One-use preparation profiles remain rejected, not skipped. Protected counters are an explicit opt-in: install CounterPreparationMigrationSource after admission preparation history, with a later version, and register the exact native CommandCounterAdmissionContributor. Profiles 3/4 freeze the complete code-free declaration in the existing journal before charging. The charge and generation-start marker commit before generation; externally admitted profile 4 charges before external admission and commits its start marker afterwards. Denied charges retain their audit and original terminal receipt without output. Final restoration must preserve the exact counter scope, and final Apply/Commit still recheck current counter authority; an allowed reservation is not permission to mutate. Lease takeover transfers the original charge without recounting or renewing its observation. Lost start acknowledgements cannot generate, and lost retention acknowledgements resume the original output. A changed declaration conflicts, including after fingerprint-key rotation. Old readers reject the new profiles rather than bypass their charge; legacy profile 1/2 history is unchanged. These are trusted compile-time adapter phases, not consumer workflow callbacks or a public authentication endpoint. Public OTP Send and its real native composition remain unfinished. Ordinary command and migration bytes are unchanged.

Code-free identity.NewFeaturePreAuthCommand and identity.NewFeatureSessionCommand use these same private fingerprint domains, without an OTP entry. Identical scalar scope with changed bearer bytes or a different custody variant cannot reuse the original command intent. Retained-key replay retains original custody. This does not bypass native authorization or enable OTP comparison/reservation without a code. The owned issuance workflow must still authenticate the actual submitted bearer and original primary state.

Separate opaque pre-auth cookies use the existing identity-command-secret-v1 framing under the exact field path pre-auth-cookie; its HMAC enters private canonical intent as pre_auth_cookie. Different submitted cookies cannot reuse the same command fingerprint. Safe collision fields contain no bearer or cookie digest. Cookie-free and code-only commands retain their exact historical bytes. Fingerprinting is not active-flow admission. Generic execution still rejects all opaque OTP submissions; native counted and consuming phases must own their primary checks. No storage or migration change is introduced by this framing.

Workflow recipient selection

Work.RequireResetRecipientCredential is the reset-only password predecessor fence. The native anonymous reset owner supplies original trusted enabled/disabled state alongside the recipient and independent credential epochs. It may recover a disabled password reference without permitting sign-in; ordinary RequireRecipientCredential and RequireActiveCredential still require enabled credentials. Current account status, verified email, expiry and exact versions remain required. Factor authority and recovery permission are separate checks.

Repository.ResolveRecipient selects an exact owner-canonical email or phone identifier within one tenant. It never normalizes addresses. Supply UserID for an original known subject; omit it only for trusted discovery, keeping the resolved user separate from the anonymous command binding. Signin/reset require RecipientVerified; verification/change may use RecipientPendingOrVerified. Missing, inactive, foreign-subject and ineligible records return Suppressed without a selected identity. Infrastructure errors remain errors.

When the workflow requires a versioned comparison policy, explicitly set both RecipientQuery.NormalizationProfile and NormalizationVersion from that owner. Discovery and the same protected reread retain the actual persisted pair; absent/unbound/incompatible pairs suppress selection even when canonical bytes match. The phone/password profile requires this selection. Neither a missing optional schema nor a legacy row may be relabeled by the query. Omitting both fields preserves the historical channel projection and retained old intent; it does not prove a current normalization profile.

Freeze the selected record into original workflow custody. The exact native feature invocation calls Work.RequireRecipient before staging delivery: primary user and identifier locks fence original versions until commit/abort, and an ignored denial poisons Work. A suppressed record cannot authorize real delivery. Records are snapshots, not authentication, risk evidence or renewable validity leases; callers must not log or serialize them. Install the existing identifier, status and credential-authority migrations before using this port. Public OTP Send orchestration remains under development.

Protected OTP effect binding

Inside its registered ApplyFeature callback, a native feature can call work.OTPConsumption(theExactFeatureOwner) to obtain a scalar copy of the original checked consuming reservation. Bind composed effects to its command, attempt, generation and fingerprint; it is not a completed proof or a commit. Unchecked reservations, non-consuming checks, foreign owners and returned Work deny access. This performs no comparison, mutation or token delivery. Session issuance still needs its own complete native effect and commit-gated delivery.

OTP current-authority checks

The generic native feature invocation also exposes Work.RequireActiveUserAuthority(ctx, participant, UserAuthorityAdmission). Only its exact live FeatureExecutionContributor may compare the active primary user and all three original security epochs. No credential is fabricated for passwordless issuance, and aggregate user versions remain separate. The lock lasts until commit or abort; a live failure poisons Work, while returned or foreign invocations cannot borrow it. This does not replace directory, policy, flow or credential-specific admission.

OTPAttemptWork, OTPReservationWork, OTPApplyWork and OTPFinalizeWork expose RequireActiveDirectoryAuthority, RequireActiveCredential and RequireActiveUserAuthorization to their exact registered OTP owner. They also expose RequireActiveUserAuthority for passwordless users without credential references: compare original user, identifier and credential-security epochs and active status under a primary user share lock. Aggregate User.Version is not an authority epoch. Credential-bearing workflows still require their exact credential check, including eligibility and expiry. These reuse primary kernel and authorization-owner checks in the original transaction, with unchanged frozen expectations, locks and bounded deadlines. A live failure poisons Work even if ignored; a returned handle cannot affect a later phase.

Expected epochs and scope must be authenticated parts of the original native command, not values adopted from a current read. Success checks only the named dimension: it does not authenticate a code, establish current session/pre-auth authority, decide policy, renew validity, issue a session or consume proof. OTPReleaseWork deliberately has no current-authority admission gate, because coordinator-proven noncommit must permit terminal release after revocation. Production OTP session/pre-auth orchestration remains under development.

Protected apply/finalize handles lend the separately submitted bearer through PreAuthCookie to the exact live owner, without exposing the OTP code or full command. Missing or returned custody denies. The owner must independently authenticate the original cookie commitment and admit current session-owned flow state; access itself grants no authority. Never retain or disclose the borrowed bearer. Recovery/release have no cookie accessor.

CAPTCHA consuming declaration

CommandPlan.CaptchaEvidence carries bounded signed consuming custody, distinct from issuance replay ownership. Its deterministic historical profile binds issuance identity, original signature, evidence lookup, consuming signature, retained key/risk-policy versions and unchanged validity interval. The immutable native command must additionally bind the full original trusted flow/configuration and all protected target/version fields; this declaration cannot substitute for them or authenticate its own inputs. Risk policy is separate from authorization policy. CAPTCHA, phone evidence and counters share one exact risk-store contributor and must agree on risk-policy version.

Existing plan bytes are unchanged when this declaration is absent. Preparation requires the exact registered CaptchaUseReservationContributor and its pure native validation before SQL. ReserveCommand invokes reserve or exact predecessor rebind through CaptchaUseReservationWork inside the same primary command reservation transaction as every other declared participant. Errors, panic, unfinished rows, poisoned SQL or cancellation roll back that whole unit. Live/terminal replay invokes no new evidence reservation. Callback return expires every handle and native-input alias; copies cannot renew ownership.

Begin additionally requires the complete CaptchaExecutionContributor phase set. Reservation-only owners remain rejected without consuming their handle. The coordinator invokes CheckCaptchaEvidence before the protected mutation and again after provisional effects, then FinalizeCaptchaEvidence in the same domain transaction as the mutation, audit/outbox and command result. Only the exact native owner receives invocation-bound CaptchaApplyWork reads or CaptchaFinalizeWork terminal SQL; no provider callbacks or private commits. Failures poison the whole Work, including ignored SQL errors and open rows.

After proven domain rollback and current owner/tenant exclusion, the coordinator invokes ReleaseCaptchaEvidence through CaptchaReleaseWork at the unchanged generation. Unresolved recovery requires every frozen participant to prove noncommit under primary exclusion before exact predecessor release at its successor. Unknown/conflicting/absent proof retains the reservation. Release must be terminal and never grants a new reservation. RecoveryWork.CaptchaBinding supplies frozen linkage only to the exact risk owner, not release authority. Elapsed expiry or lease time is never noncommit proof.

The native risk adapter implements consuming reservation but not yet this complete execution phase set. SQL integration fixtures prove the coordinator's atomicity, lifetime and primary noncommit protocol, not production CAPTCHA authentication, protected workflows or final consuming composition.

Native CAPTCHA replay reservation

CommandPlan.CaptchaReplayReservation explicitly selects the native risk store's CaptchaReplayContributor before domain work. Only the exact user or anonymous-flow CAPTCHA issuance schemas admit it; declaration alone supplies no authority. The existing coordinator commits the alias reservation with the original command reservation, then invokes domain work separately. A domain rollback cannot erase that independently committed replay winner.

CaptchaReservationWork exposes only bounded SQL, primary time and the exact original immutable command, authoritative fingerprint and owner generations. The registered native participant authenticates signed custody/configuration and enforces alias uniqueness. Callback return or panic expires every handle copy; takeover uses exact predecessor CAS, never a timeout-based release. False leaves historical plan bytes unchanged. The risk PostgreSQL adapter now supplies production issuance and original-result recovery; protected consumption remains pending; applications must not implement private replay stores to fill these gaps.

Exact original final-authentication outcome recovery

QueryMFATOTPCommand is the owned TOTP completion adapter's exact-input history lookup. It compares opaque original code/cookie custody under the retained fingerprint key and validates the historical native completion plan, without requiring today's mutable continuation version. Current query policy remains mandatory. Only authorized absence returns found=false with no error; matching denied attempts retain their original receipt, changed input conflicts, and incomplete or retired history fails closed. Receipts never authorize a new session or credential delivery. This read performs no factor comparison, attempt charge, participant callback, reservation or mutation.

For native anonymous TOTP commands enriched with protected counters, use PrepareMFATOTPAttemptPlanWithOriginal / RecordMFATOTPAttemptDenialWithOriginal and PrepareMFATOTPFeaturePlanWithOriginal / ExecutePreparedMFATOTPFeature. Supply the exact submitted code/browser command and its native counter-enriched counterpart. Only the six known, independently validated counter fields may be added. Original input owns journal history; the complete counter declaration still owns preparation and charging. Generic command codecs are unchanged.

For the closed anonymous OTP completion profile, use PrepareMFAOTPFeaturePlanWithOriginal / ExecutePreparedMFAOTPFeature. Besides those six counter fields, only the two authenticated native OTP custody fields may enrich original input. Bind the unchanged trusted network as transport.network in original opaque intent. The existing immutable declaration retains only encrypted OTP custody and original counter time/key metadata before session generation or comparison; raw network/base intent is not persisted there. On retry, QueryMFAOTPPreparation authenticates the exact original opaque code/browser/intent identity and reconstructs independently owned metadata for the native OTP owner's RestorePrepared; never prepare another attempt or refresh its counter time. It also restores checkpoints that have no generated session output. QueryMFAOTPCommand observes pending or terminal history before any mutable continuation/factor read. A pending receipt cannot justify new generation, and terminal history cannot reveal credentials. The native OTP, MFA, risk and session owners still must implement the protected complete login transaction; these coordinator APIs alone are not a public OTP authentication service.

QueryAuthenticatedCommand is a read-only bridge for the owned authenticated session adapter. Supply the original mapped command, opaque final proof, prepared plan and trusted current actor context. The configured QueryPolicy must allow disclosure. The bridge compares the complete original input using the global claim's exact retained fingerprint-key version, original proof namespace and frozen plan before returning the safe feature receipt and audit event ID. Generic QueryCommand remains metadata-only.

Expired proof metadata is historical: the bridge validates original private provenance at the original issuance instant; it cannot renew authentication, authorize a session, consume a proof or return a credential. Wrong input/plan conflicts; missing, retired, malformed or unavailable evidence fails closed. Absence never becomes rollback proof or an implicit reservation.

RecoverAuthenticatedCommand first establishes that same original input and current access policy, then uses the existing sole reconciliation owner only for an already observed pending command. It repeats exact-input lookup after reconciliation. Live leases remain pending, and unresolved effects remain unknown. It never reserves missing input, executes a session transition or reveals a bearer. Retain original safe request/proof custody and old keys for this request-bearing path; general restart recovery from command identity and the complete public session execution service remain unfinished.

Final-authentication proof-use storage

SignInProofUseMigrationSource{Base, Version} appends bounded proof-use tombstones after the complete existing history. Existing IDs, status and versions are unchanged; no destructive downgrade or pruning is provided. Proof IDs are unique within a stable trusted authentication-source namespace, across tenants and versions. Changing that namespace must not bypass prior use. The original full-width proof version and nanosecond expiry remain exact.

The private staging phase writes through the original Work only. A unique command cannot acquire another proof; concurrent commands cannot commit use of the same proof. Rollback discards provisional use with every other effect. Primary time is checked after the uniqueness lock, so a proof expiring during a wait cannot leave usable Work. A denied or ambiguous attempt must follow the coordinator's existing abort/recovery path, never guess rollback or mint another proof or bearer. Session deletion cannot make a committed proof reusable.

This is not authenticated issuance. The private storage phase neither authenticates its metadata nor checks current authority or creates a session. The native issuer still needs configured opaque-proof validation, immutable command binding, current locked eligibility, session/family effects, final temporal checks, audit/lifecycle and terminal recovery. No ordinary feature or public session issuance is activated by this migration or storage phase.

Privacy admission storage

The native private command codec now binds the complete closed privacy request and its original authenticated proof to the existing global command claim. It reuses the core's deterministic intent digest, wrapping it and the exact opaque proof-envelope digest in separate framed, retained-key HMAC domains. Proof header/payload validation retains the existing bounded capability codec. Session IDs, projection choices and proof correlation fields do not enter persisted collision fields. Historical non-privacy command bytes are unchanged.

Exact replay regenerates the original fingerprint under its stored key version; it never re-signs the proof, changes its lifetime or promotes a changed session or privacy epoch. Even another valid signature over identical proof metadata is distinct submitted custody. This encoding and private claim check neither consume a one-time use nor expose public privacy reservation/execution. Full native proof consumption, all cuts, audit/lifecycle and terminal recovery must still be composed under the sole coordinator.

Journal persistence and request-bearing replay also compare the queued receipt against the retained original intent: identity/authority/privacy versions, artifact policy and every contributor projection must match. A structurally valid receipt from a changed session or policy cannot replace the original. Scope-only observation remains structural and preserves the stored bytes for the service's separate retained-key snapshot verification. Neither path proves cut provenance or authorizes new execution, and neither needs a live proof.

PrivacyExportAdmissionContributor is the native session owner's read-only eligibility role. The private invocation selects the already registered exact identity/session/postgres participant; registration alone cannot enable it as a public command. Its PrivacyExportAdmissionWork has no constructor or write/transaction-closure methods. Initial checks precede allocation; terminal checks require the same Work's stored allocation/snapshot and frozen request. The role borrows existing kernel credential, directory and authorization checks and bounded primary reads without defining another policy owner. Every ignored denial poisons Work, handles expire when the invocation returns, and repeated or reentrant phases cannot renew authority. Session/proof freshness remains the original authority owner's responsibility, never a new lease from this handle. The actual native session adapter must implement these checks; this invocation plumbing is not proof of session validity or complete queued admission.

Compose PrivacyExportJobMigrationSource{Base, Version} after the privacy epoch migration to add bounded immutable request/snapshot metadata and the closed six-state job profile. Existing applied migrations are unchanged. The private persistence phase uses the same Work's allocation and frozen intent, verifies the retained evidence key, rejects changed scope/time/projections and rechecks active identity, authority and privacy fences at its write. Command ID, export ID and per-subject epoch uniqueness prevent metadata rebinding; no upsert or snapshot re-signing is used. Exact JSON bytes retain full unsigned counters without JSONB coercion; the deterministic-CBOR MAC remains key-owned. Returned receipts are copied, provisional and not publication evidence. The metadata includes personal scope correlations, so restrict database access and apply the eventual legal-hold/erasure owner; do not log it. No worker or public admission API is activated by this migration or storage phase.

PrivacyExportMigrationSource{Base, Version} appends authoritative privacy_epoch and privacy_disposition fields to existing user rows. Compose Base with StatusMigrationSource first and allocate Version after every Base version. The migration preserves existing IDs, user/authority versions and blocked state; defaults keep explicit-column old creation/read paths compatible. No destructive down is supported. Resetting the epoch would resurrect prior export authority.

The private native allocation phase locks the exact user row, rejects blocked, pending-anonymization/deletion, stale or overflowing authority, samples primary time after locking, generates a random export ID and advances only privacy epoch inside the existing Work. All failures poison that Work. No transaction is opened or closed by allocation; rollback removes its entire provisional prefix.

This is not queued admission. Allocation does not prove session freshness, configured authorization, original proof consumption or cut provenance, and cannot make an export runnable. Public privacy execution remains disabled until the protected owner captures every contributor cut and persists the immutable snapshot, job, proof consumption, audit/lifecycle and command result atomically. Pending destructive lifecycle owners must set the disposition under the same user lock before initiating cascades. The initial wire profile still rejects unmapped imported directory IDs rather than rewriting them; profile reconciliation is unfinished. Worker, publication, download and recovery composition remain work.

KernelAuthorityKeys derives canonical version-one keys for kernel-owned global, tenant and user lifecycle dimensions. Session admission must compare these exact keys as well as current positive versions. They are correlation values, not authentication evidence; do not log them. Existing custom keys require explicit adoption and cannot be silently refreshed into this profile.

Protected identifier admission

Identifier reservation requires CapabilityPlan.ProofFingerprint to equal the submitted verified Grant.EnvelopeDigest(). Equal ID, expiry and use limits alone cannot substitute another signed envelope. The capability owner derives keyed replay metadata; callers must not invent it. This comparison changes no historical command encoding or frozen-plan decoding and grants no authentication or execution authority.

CommandPlan.IdentifierAdmission selects the exact registered identity/session/postgres checker through IdentifierAdmissionContributor. This role is frozen into the journal, separately from mutation contributors: it cannot claim a durable recovery outcome. Nil retains historical plan bytes.

IdentifierAdmissionWork is available only during the coordinator's check callback. Its complete command and initial/final phase are available only to the selected instance. Bounded queries and existing credential, directory and user-authorization checks share the original transaction and lock lifetime; there is no write or transaction-closure method. Ignored denial poisons Work. Close all rows before returning; do not retain the handle or perform network callbacks. The private persistence pipeline invokes initial admission before locking/mutating the identifier partition or consuming its proof. Final admission runs after provisional effects and before proof finalization and terminal journal persistence. Each phase runs once; reentrant, duplicate, out-of-order or failed checks poison the same Work.

IdentifierAuthorityVersion returns the original expected epoch initially. At final admission it returns only the exact successor from this Work's owned mutation receipt, with matching subject, intent, record, action and predecessor. It does not replace the original session snapshot or renew its freshness. Historical role-free provisional plans are unchanged; this optional role is not sufficient to activate public execution.

These checks alone do not authorize mutation, consume proof, or establish credential-specific reauthentication. Public identifier Begin remains disabled until complete native session, access policy and recovery composition exists.

Scoped user authorization authority

Native participants can call Work.RequireActiveUserAuthorization with their exact instance and a frozen UserAuthorizationAdmission. Bind all three authorization/postgres.AuthorityScope fields and the expected positive epoch into the native keyed command before reservation; compare that frozen intent at execution. The namespace is trusted native configuration owning user-ID uniqueness, not a request-selected subject kind. Subject must match the command's effective UserID, not its separate actor or calling workload. Organization and impersonation profiles require their own explicit authority contracts; this user-only helper cannot approximate them.

The existing authorization owner performs its exact primary lookup through the generation-bound WorkRows, retaining a share lock until the sole coordinator commits or aborts. Missing or unequal epochs deny without creating defaults. Malformed input, foreign invocation, cancellation and storage failures poison live Work even if ignored. Earlier deadlines win and no freshness is renewed. Use the owner's separately allocated forward-only authority migration through the owned migration composition; do not copy its SQL or bootstrap during login.

This is a lifecycle epoch check, not policy Allow, authentication proof or a completed session issuer. The existing policy engine, every other contributing authority owner and atomic one-time proof finalization remain mandatory. These admission checks are opt-in and existing participants remain compatible.

Deployment and tenant authority

Compose DirectoryAuthorityMigrationSource into the single owned migration history after its complete existing source. Allocate a permanent later version, one explicit GlobalAuthorityID, and up to 256 exact initial TenantIDs from trusted bootstrap configuration. The source creates independent full-width epochs at version 1; it does not discover tenants from users, create missing authority during authentication or modify user/credential versions. An empty tenant set deliberately enables none. Tenant order is canonicalized; duplicate IDs fail. Never edit the source configuration after its version is applied.

Repository.GetDirectoryAuthority returns a bounded structural primary projection, including disabled tenant state. It is not authentication, an authorization decision or renewable validity evidence. Missing exact scope returns redacted identity.ForbiddenError; corrupt/unavailable storage fails closed. No replica/cache fallback exists.

An exact active native participant can call Work.RequireActiveDirectoryAuthority with DirectoryAuthorityAdmission. Bind the deployment/tenant IDs and both expected epochs into the native command before reservation, deriving deployment identity from trusted composition. The helper retains share locks until the original coordinator terminalizes Work. Missing, disabled or changed epochs poison the transaction, including when a participant ignores denial after provisional writes. Earlier deadlines still win; driver cancellation may leave Unknown, requiring existing command recovery, never another command or an invented rollback acknowledgement.

These are current kernel checks only. Credential admission, scoped existing authorization-owner checks, optional owners and one-time proof finalization remain required before session issuance. Public tenant onboarding/transitions and global-compromise lifecycle/cascade acknowledgements remain in development; consumers must not replace them with SQL callbacks or mutate migration history.

Locked credential eligibility

During its synchronous native feature invocation, a registered participant can call Work.RequireActiveCredential with its exact instance and a frozen CredentialAdmission. The native command must bind all expected fields before reservation: credential reference/version plus independent user-authority, identifier and user-wide credential epochs. The aggregate user version is not a security epoch. Existing participants need not opt in.

The helper checks the current kernel rows under share locks retained until the coordinator commits or aborts, then samples primary time for exclusive expiry. Absent, blocked, disabled or stale credentials deny uniformly; an ignored denial poisons Work and prevents commit, including earlier provisional writes. No callbacks, external services or separate transactions run in this helper.

This is only kernel eligibility, not session issuance or bearer authentication. Native issuers must additionally establish private proof provenance, current global/tenant/authorization and optional-owner authority, and atomic one-time finalization. The returned time is not a renewable validity lease. Real-primary coordinator tests use a synthetic participant, not a completed session issuer.

Anonymous email/phone sign-in can use Work.RequireRecipientCredential with the original RecipientRecord and CredentialAdmission. Their tenant, selected user and all three security epochs must agree. The kernel rechecks the original identifier/verification under retained locks before checking that exact credential. It does not replace the anonymous command binding with the selected user or rediscover a newer recipient. Bind both snapshots into original intent; password verification and every other issuance policy remain the native owner's responsibility.

During protected Apply only, Work.FeatureCommandIdentity returns owned copies of the original binding, keyed fingerprint and reservation generation for native effect correlation (including pre-auth consumption). Foreign, admission-only, expired and returned invocations deny. This tuple is not proof, a new command, or refreshed authority evidence; never log it or use it to reset freshness.

Original-command capability issuance

CommandPlan.CapabilityIssuance declares 1..16 one-use grants and the exact capability/postgres owner, contract capability.issuance, version 1. This participant follows the base contributors and precedes optional delivery. Its purposes name future protected operations, not the originating mutation. Only immutable IDs, signed expiry/maximum, original-envelope fingerprints and independently keyed replay metadata enter the journal. Nil retains historical kernel, feature and delivery plan bytes.

The trusted issuing adapter stages authenticated capability.Grant values with Work.StageCapabilityIssuanceFor. Every grant must match its plan position, tenant, command user, purpose, ID, whole-second expiry and single-use maximum. This profile requires subject-bound grants, not subjectless bearer authority. Descriptor equality does not allow a foreign instance to stage custody.

For anonymous native password signup only, RegistrationUserID may explicitly select the newly registered verification subject. This bounded target is part of the frozen plan digest and recovery metadata; it does not replace the original anonymous command binding. Only identity.identifier.verify grants are admitted and staging requires successful kernel registration of that exact user in this same Work. Missing registration or a different subject/tenant poisons Work. Empty selection retains the existing command-user behavior and identical bytes. Older readers fail closed on the additional field. The native capability issuer and journal-prepared signup workflow must separately adopt this profile; kernel support alone does not enable an end-user verification flow.

For the closed anonymous password reset-request profile, ResetRecipientUserID instead binds exactly one existing recipient and one reset-complete grant. It is mutually exclusive with signup selection and preserves the anonymous command. Staging requires this native invocation's successful RequireRecipientCredential primary fence for a verified email and password reference. The grant must match the original command, selected user, identifier and independent predecessor versions. Declaration metadata alone cannot select a recipient. Current factor and risk policy remain mandatory workflow admission, not supplied by this fence. The issuer adapter and full reset workflow must adopt this separate profile; these kernel contracts alone do not enable reset. Empty target retains prior plan bytes; older readers deny the new target rather than dropping it.

ExecutePreparedFeature also permits that exact issuance profile in the authenticated restored final plan: original admission must declare neither issuance nor delivery. The final plan preserves every original contributor and its order, followed by the exact issuer and optional delivery owner. Feature, lifecycle, subject, audits and counters cannot change. The original journal retains ciphertext and its generation before execution; retries cannot replace the grant or renew its expiry. Existing consumption, OTP, identifier-admission, risk-evidence and CAPTCHA preparation profiles remain closed. This composition seam does not supply native issuer checkpoint/restoration or SignupService; those owners must still authenticate their original encrypted custody.

The exact owner receives CapabilityIssuanceWork only during coordinator-owned persistence; its aliases and SQL authority expire on return, including panic. The owner must verify original-envelope and keyed replay provenance, insert absent issued state and retain originating command/fingerprint/generation separately from subsequent consuming-command identity. It must never resurrect terminal records, open a transaction, sign, call providers, or retain the handle.

Issuance runs after the actual mutation and before delivery/audit/lifecycle and the sole commit. Missing staging, failure/panic, later phase failure and expiry before terminalization roll back the original mutation and issued records. RecoveryWork.CapabilityIssuanceBinding exposes frozen metadata only to the exact registered issuer; recovery never signs or reveals replacement tokens. The optional versioned envelope composes with encrypted delivery and bounded historical decoding, without a second ledger or coordinator.

No bearer bytes are staged or returned by this adapter. Queued credentials must use independently authenticated encrypted delivery custody; synchronous custody must not be revealed before a proven commit. Coordinator tests use an owned SQL phase to prove transaction and lifetime semantics, not the unfinished native capability producer, encrypted-delivery interoperability or end-user workflow. Consuming capability-bearing domain execution remains disabled.

Original-command encrypted delivery

CommandPlan.Delivery optionally declares 1..16 required effects and the exact last contributor identity/delivery/postgres, contract identity.delivery.effects, version 1. Its logical IntentDigest must bind all behavior-affecting inputs using the owning workflow's confidential fingerprint; randomized ciphertext is not logical replay identity. Safe effect/resource and template IDs are 1..128 printable non-space ASCII bytes. Purpose is a canonical lowercase event name; template/provider versions are positive. Expiry is an exclusive post-epoch microsecond-exact instant, never renewed on replay.

The original owned delivery adapter stages prepared secret-envelope ciphertext with Work.StageDeliveryFor and its exact enlisted pointer. Equal descriptors or configuration do not allow another instance to stage its own preparation. The existing Work.StageDelivery remains a trusted low-level composition seam, not participant authentication. Each envelope is at most 524288 bytes and total custody is at most 1MiB. Encryption/provider work must happen before opening the mutation transaction. Only the coordinator invokes the exact enlisted DeliveryContributor.PersistDelivery. During that synchronous invocation, DeliveryScope exposes an owned original-command declaration and StagedDelivery returns copied ciphertext. The owner must verify complete AAD and confidential logical input, and persist custody plus outbox admission via this Work. Neither a descriptor nor this plan authenticates an HTTP caller.

Missing staging, persistence error/panic, later audit/lifecycle failure, or expiry before terminalization rolls back the original mutation and delivery. Recovery invokes every frozen participant; RecoveryWork.DeliveryScope allows only the exact enlisted owner to inspect its original declaration. Unknown or conflicting delivery evidence cannot prove noncommit. No second enqueue command, transaction, sender invocation, or workflow engine exists here. The optional versioned plan envelope conserves historical base-plan bytes and excludes ciphertext from command journals. Closed Work drops custody references; this does not promise secure erasure of Go heap bytes or caller-owned copies.

Coordinator integration tests use a deliberate owned SQL seam. They are not production queue/envelope/provider interoperability proof: those remain part of the separate, unfinished identity/delivery/postgres implementation.

Typed one-use risk reservation

CommandPlan.RiskEvidence declares the scalar projection of risk's signed PreparedEvidenceUse. No bearer, provider facts or keys belong in the plan. Preparation owns copies and freezes every declaration field in the distinct identity-feature-risk-plan-v1 profile. Existing feature v1/v2 bytes are unchanged. Only the exact native identity/phone operation identity.phone.password-reset-request, schema identity.phone.password-reset-request.native-v1 version 1, required-record profile with subject kind phone, is admitted. This is not the public HTTP request schema. Other schemas and reset completion are rejected, not approximated.

Enlist the exact identity/risk/postgres / identity.risk.store / 1 participant implementing RiskReservationContributor alongside the identity, audit, outbox and native phone contributors. ReserveCommand invokes ReserveRiskEvidence or exact-predecessor RebindRiskEvidence inside its existing command reservation transaction. Participant failure, panic, poisoned SQL or unclosed rows rolls back both command and evidence ownership. A live command replay skips mutation. The invocation-only RiskReservationWork.Binding(participant) verifies the exact registered instance; retained copies cannot run SQL or disclose bindings.

The risk adapter must authenticate the projection, compare the native command's complete recovery scope and current policy, then lock the already-issued row using primary time and original expiry. Structural preparation is not that authentication. CheckedAt preserves nanoseconds; compare it against returned primary time without rounding or passing it as a microsecond-only SQL parameter. No method refreshes the precheck or evidence lifetime.

RiskReleaseContributor adds native retained noncommit evidence through RecoveryWork.RiskBinding(participant) and terminal release through an invocation-only RiskReleaseWork. Recovery requires this phase before taking over ownership. Under the primary command and tenant fences, every frozen participant must prove noncommit before risk release, failure audit and aborted receipt commit in one transaction. Missing, mismatched or unknown native custody must remain unknown. Evidence expiry neither proves rollback nor reactivates a reservation; proved noncommit releases even expired reservations. Audit/release errors, panics, poisoned SQL and open rows roll back takeover, release and terminal receipt together. The new recovery generation never grants domain authority. Terminal receipt replay invokes no new participant mutation.

After a proved nonretryable domain rollback, Abort instead rechecks the same live owner and frozen plan, acquires the tenant exclusion, and releases custody in the failure-audit/aborted-receipt transaction. RiskReleaseWork.Binding returns that current generation in both generation fields; an owner that took over generation 2 releases generation 2, not its former predecessor. Private coordinator provenance distinguishes this path from successor-generation recovery without widening reservation/rebind authority. Missing failure audit, release phase, matching custody or live ownership retains pending/Unknown; errors, panic, open rows and poisoned SQL leave no durable terminal prefix.

The same proven-rollback rule applies to CapabilityReleaseWork: Abort terminal-releases the exact reserved capability under the current generation only after rollback, live-owner/frozen-plan rechecks and tenant exclusion. Release, failure audit and aborted receipt commit together; a missing phase, wrong custody, failed rollback, lost owner or callback failure leaves Unknown and no terminal prefix. Recovery release still advances exactly one generation. Private release provenance cannot be reused as reserve/rebind authority. Release is terminal, not permission to reuse the proof, and does not enable the still-incomplete protected identifier workflow.

RiskExecutionContributor is the separate opt-in for domain execution. The exact registered owner must implement pure ValidateRiskEvidenceCommand, read-only CheckRiskEvidence and terminal FinalizeRiskEvidence in addition to reservation, recovery and release. Reservation/release-only owners remain closed at Begin. The coordinator compares the entire original command before any effect, checks risk immediately before native feature mutation, and checks again after provisional audit/outbox persistence. It then finalizes the exact reserved row in that same transaction before terminalizing the command receipt. The native owner must authenticate complete recovery scope, current policy and provider versions, original exclusive expiry, current counters and journal custody; finalization must recheck expiry and CAS the original generation.

RiskApplyWork exposes bounded reads/primary time and immutable native input only to its exact owner. RiskFinalizeWork additionally permits bounded trusted terminal SQL. Both are invocation-only, redact diagnostics, reject serialization and share the domain Work's nonrenewing budget; no raw driver or transaction closure is exposed. A retained apply handle is already invalid when finalization begins. Neither copies nor late effects renew original evidence freshness. Errors, panic, SQL poisoning and unclosed rows roll back domain effects, finalization, audit/outbox and receipt together; the existing proved-noncommit release protocol then terminally releases custody. Unknown commit never implies release or reuse. Exact committed replay does not invoke the phases again.

This boundary does not yet enable phone recovery. The official risk adapter still supplies only reservation/release, and must implement native current checks and finalization before adoption. OTP/capability issuance/consumption and phone orchestration remain required. Applications must not provide their own SQL participant to substitute for the owned adapters.

Trusted command admission observation

Protected counter reservation

Counter-bearing domain execution additionally requires the exact registered owner to implement CommandCounterAdmissionContributor. Reservation-only participants still cannot open Begin. The new CheckCommandCounters phase receives CommandCounterAdmissionWork immediately before native feature mutation and again after audit/lifecycle persistence, before terminal commit. It must recheck exact current-generation charge custody, policy, original evidence expiry, authoritative counters and any explicitly selected lockout/override policy. It must not increment, refund, refresh original observations, invoke providers or open its own transaction. This bounded invocation exposes reads/primary time and the original immutable command only to that instance, then expires. The coordinator retains command input only in memory until Work closes. The feature owner still owns current user/credential/organization/factor checks.

Late denial rolls back all provisional domain effects and persists classified failure audit/aborted receipt through the ordinary proved-rollback path. Its original charged attempt remains committed. Errors, panics, SQL poisoning or unclosed rows fail closed. Counter and one-use risk declarations are distinct closed profiles; neither substitutes for the other's authority. The native adapter must implement the selected current-check contract before real protected workflow composition can use either opt-in.

Native protected-feature composition may declare CommandPlan.CommandCounters with the core's complete keyed counter fingerprint and risk-policy version. It must enlist exactly one identity/risk/postgres participant implementing CommandCounterContributor, in addition to the native feature, kernel, audit and lifecycle participants. Both the feature owner and risk participant perform pure native validation before the first SQL write. No raw subject/network dimensions are serialized into the frozen plan; historical feature-plan bytes remain unchanged when this profile is absent.

ReserveCommand calls that exact participant under the existing primary command/tenant exclusions. CommandCounterWork returns frozen binding and the immutable original native command only during its invocation; aliases and rows must not be retained. Allowed disposition commits the charge and its original snapshot with pending command ownership. Denied disposition commits the charge, all declared denied audit slots and the aborted command receipt together, with no domain mutation or successful lifecycle event. Returning an error instead rolls back the reservation unit; SQL before commit is provisional. A commit attempt error returns Unknown even when a deferred constraint rejects commit.

Live/terminal replay bypasses mutation. Expired-owner takeover supplies the exact predecessor/current generation and must reuse the original charge, never increment or refund it. RecoveryWork.CommandCounterBinding exposes exact charge linkage to its registered owner for read-only reconciliation: a charged reservation is prerequisite evidence, not proof that the domain committed.

The real risk adapter's durable counter storage/rotation/algorithm and current domain checks are still being implemented. Counter-bearing Begin and ApplyFeature therefore remain disabled. SQL integration seams prove this coordinator boundary, not password workflows or native risk interoperability; applications must not supply a replacement counter store to fill the gap.

Native feature adapters may configure CoordinatorConfig.AdmissionPolicy separately from QueryPolicy and call ObserveCommandAdmission(ctx, query, caller) before evaluating external providers. The current policy receives owned identity.command.read-admission=true and identity.command.recovery=false attributes; caller, tenant, operation and identity.user resource must match the query at the configured revision. Only an authorized actual absent global claim returns CommandAdmission{Absent: true}. Denial, wrong scope, retired claims, orphan journals, corrupt history and outages never become absence.

Existing claims return only safe CommandRecord history and its original terminal classification; expired pending commands remain pending. No command or participant is reserved, repaired, locked, renewed or invoked. This is a trusted native composition API, not a client lookup route. QueryPolicy alone does not enable admission, and AdmissionPolicy alone does not enable lookup.

Absence is a point-in-time observation, not a reservation or proof that an earlier ambiguous submission rolled back. A concurrent command may appear immediately afterward. Native adapters must compare their own retained pre-evaluation intent before replaying protected results, and must still submit through ReserveCommand for the full immutable command collision fence. This method neither returns nor verifies native bearer/proof payloads.

Primary credential eligibility metadata

Compose CredentialMigrationSource{Base: existingHistory, Version: allocated} with the owned migrations runner, after every installed kernel/session/status migration. It adds non-secret references and the independent tenant/user credential_version; existing status, aggregate and identifier epochs are unchanged. Old creation writers receive epoch 1 but no fabricated reference. Keep disabled references as retained state; this migration never re-enables one. Down SQL is unsupported. Expiry is nullable (indefinite), otherwise finite UTC microsecond precision, strictly after the Go zero instant and before year10000.

Repository.GetCredentialAuthority(ctx, identity.CredentialAuthorityQuery{...}) implements the core port with one consistent primary statement matching exact tenant, user and credential ID. Missing schema fails unavailable, not absent; missing exact references return identity.ErrUserAbsent. All versions preserve full uint64 precision, with no aggregate/security/credential substitution. Blocked users, disabled references and expired instants remain visible to identity.CheckCredentialAuthority, which denies them rather than repairing stored state. Earlier caller/configured deadlines bound reads; driver details and partial records do not escape failures.

This is metadata eligibility, not secret verification, factor/provider status, authentication proof, authorization or a cache freshness lease. Credential reference mutations, their atomic epoch bump/audit/outbox and final proof consumption are still under development; applications must not supply private SQL callbacks to replace them. User-owned references do not represent organization-owned API-key authority, which belongs to its separate owner.

Durable user-status admission

Opt in with StatusMigrationSource{Base: MigrationSource{}, Version: allocated} and the owned migrations runner. Allocate its version after every composed kernel/session migration; do not renumber installed history. Migration defaults persist user-security epoch 1 and no legal hold while preserving every existing status, aggregate version and identifier epoch. They also keep prior creation and ordinary field writers compatible. A database missing this migration fails closed; readers never invent security versions.

Repository.GetStatus(ctx, identity.UserStatusQuery{TenantID: tenant, UserID: user}) implements the core primary status port. User.Version is aggregate CAS; AuthorityVersion is the independent user-security epoch. Profile and ordinary administrative field edits advance only aggregate CAS. Suspend/ban and restore/unban advance both, so restoring eligibility cannot restore old vectors. Expired restrictions remain blocked until a fresh audited restore/unban.

Construct NewStatusUnitOfWork(coordinator, repository, config) with the exact enlisted repository and typed audit/outbox contributors, then pass it and the repository to identity.NewUserStatusService. That service supplies current authorization, policy admission and redaction; calling the adapter directly is not an authenticated endpoint. Configuration contains the same explicit status policy/reasons as the service, a positive status-policy revision, finite cascade deadline and reviewed version/fingerprint for every exact manifest consumer. These are deployment metadata, not consumer stores or callbacks. Every change to that configuration needs a new status-policy revision. The owner durably rejects conflicting definitions for an already-used tenant/revision.

One shared commit persists status, reason/absolute expiry, both successors, random cascade ID/generation 1, exact manifest and ordered consumer contracts, trigger event/version, deadline, current legal-hold state, audit, lifecycle and original receipt. Row locks precede the final primary-time expiry check. Exact replay precedes current CAS and retains original IDs, timestamps and consumers, even after restoration or a composition change. Preserve command identity and use Recover after unknown closure; recovery never reexecutes the mutation. Retain cascade admission rows alongside non-reassignable command evidence; current user state or pruned payloads cannot substitute for retained evidence.

The returned cascade is pending. This admission path does not acknowledge consumers, complete cleanup, manage legal holds, or implement cascade closure. Those remain distinct generation-bound phases. Nor does a primary status read alone establish authenticated session issuance or the shared-issuer 30-second cache/resource guarantee; actual proof consumption and all authority owners must still be composed. All epochs retain full unsigned 64-bit precision; exhaustion denies a successor rather than resetting or wrapping.

Experimental Go 1.27 module implementing identity.UserDirectoryRepository using the owned go-postgres pool. Tenant and user IDs are matched exactly; lifecycle states and the full uint64 version range are preserved. Reads are primary-only, bounded and uncached. Configure primary endpoints explicitly.

Construct with NewRepository(pool, Config{MaximumDuration: time.Second}), then compose it through identity.NewUserQueryService for policy and redaction. The caller owns pool shutdown. No globals or background goroutines are created. Driver errors are discarded rather than exposed through errors.As or logs. Cancellation and deadline classifications remain observable.

Feature operation registration

Durable feature adapters may implement FeatureContributor alongside the existing Contributor. The same immutable registry snapshots their compile-time identity.FeatureOperation descriptors once, including all supported schemas, explicit record policy and exact adapter owner. An explicit SubjectRequirement also freezes the user or anonymous-flow namespace. Anonymous feature scope persists AnonymousFlowID, never a fake UserID; current-policy admission/query/recovery must use the exact identity.anonymous-flow resource and retain the separately verified actor. Record-free audit/lifecycle targets use that flow ID. User-only descriptors retain their existing canonical command/plan bytes and JSON receipt shape. This uses existing command claims/journals; no extra replay owner or schema migration is introduced. Concrete CAPTCHA persistence remains separate work.

Each core owner maps to its <owner>/postgres adapter; each operation belongs to one exact contributor across schema versions and subject namespaces. A schema/version may declare both user and anonymous-flow subjects; selection still matches the complete descriptor. Duplicate/conflicting schemas within a subject and foreign ownership fail construction before any transaction opens. Limits are 64 declarations per feature contributor and 1024 total. Legacy contributors need no new methods.

ContributorRegistry.FeatureOperations returns an owned scalar projection for trusted composition; it performs no callbacks. This is not enabled-feature discovery, registration of codecs, authorization or execution readiness. Kernel command plans remain closed. Native non-one-time feature execution uses the same coordinator; production session issuance remains in development. Do not advertise routes from these declarations or substitute private journals.

The existing private command codec also maps immutable identity.Command feature inputs for future owned phases. Exact owner/record policy and every named scalar kind/value affect the keyed fingerprint; all scalar values are conservatively digested before canonical encoding. Scope remains separate from private intent, and retained-key replay regenerates the original fingerprint. This is not schema validation or execution readiness.

Opaque Command.OneTimeCode custody contributes a separate one_time_code payload digest using the fixed canonical path one-time-code and the existing identity-command-secret-v1 profile. Raw code bytes never enter canonical payloads or safe collision fields. Absent custody preserves historical bytes; replay recomputes from the immutable submission under the stored retained key. The central preparation path rejects these commands before generic feature admission. Fingerprinting alone does not count attempts or consume challenges; native OTP reservation/current/finalize/recovery phases remain required.

CommandPlan.OTP freezes the complete server-issued attempt projection: random attempt ID, keyed attempt fingerprint and version, challenge/scope digest, digest-key version, expected challenge version and check/consume mode. It is private correlation, not proof or current authority. Historical decoding binds all fields and supports optional CAPTCHA/risk declarations without creating a second journal. Generic feature admission remains closed to OTP custody.

For a native OTPAttemptContributor, PrepareOTPAttemptPlan authenticates the original opaque submission through that exact registered owner before SQL. RecordOTPAttemptDenial then locks the existing command before the owner's bounded challenge comparison. The owner proposes the wrong-attempt charge and exhaustion; the coordinator commits these with required denial audits and the aborted command in one transaction. No risk, CAPTCHA, capability or session reservation runs on this narrow path. Exact retries return history without another comparison; changed code or attempt conflicts. OTPAttemptUnchanged rolls back provisional effects and grants no successful precheck or reservation. Returned callback handles cannot access SQL or opaque custody.

Native metered checks use the additive OTPMeteredCheckContributor, the same OTP owner as the declared record-free feature, and an exact OTPCheck plan. RecordOTPMeteredCheck uses the existing transaction and journal to commit check/total counters with required audit and a redacted check receipt. It does not invoke domain application, risk/capability consumption, lifecycle delivery or session effects. OTPAttemptChecked is accepted only on this explicit path; the existing denial path cannot turn a correct check into success.

For correct checks, CommitOutcomeCommitted describes committed metering only, not authentication proof, reservation or protected mutation. Wrong checks retain the denial outcome; disabled/exhausted checks roll back unchanged. Exact replay does not compare or charge again. RecoverOTPMeteredCheck binds the original attempt plan and current query authorization to retained check history without needing a bearer/code or granting current authority. Commit ambiguity remains Unknown and must be resolved through the original command, not a new attempt.

Any commit-attempt error is Unknown. Keep the original command and complete attempt identity; RecoverOTPAttemptDenial uses the configured current QueryPolicy and one primary read without code, comparison or mutation. A historical denied result is NotCommitted plus Forbidden. Changed attempt fields return no history. Pending remains InProgress, including after lease expiry; it never authorizes a replacement submission, takeover or challenge release. The production OTP adapter and composed protected workflow remain required before adopting a complete OTP workflow.

OTPReservationContributor additionally enables PrepareOTPReservationPlan and ReserveOTPCommand for consuming mode only. Its reserve callback runs last after the existing one-use participants inside their shared claim/journal transaction. Native failure rolls back every prefix; a commit-attempt error returns Unknown and no ownership. A live same-command retry does not compare again. Expired-owner takeover invokes only exact predecessor CAS rebind, never reserve/comparison, and cannot transfer another command or generation. Returned reservation handles enter Begin only when the same exact registered owner implements OTPExecutionContributor. Current checks run before protected mutation and again before finalization, without another code comparison or attempt charge. OTPApplyWork permits only primary reads; apply/finalize CommandSpec returns code-free feature scope. OTPFinalizeWork terminal CAS, domain effects, audits, outbox and original receipt commit together. Returned, foreign and wrong-phase handles deny. Callback failure, panic, unfinished rows or poisoned SQL roll back all provisional domain/finalization effects.

OTPReleaseWork runs only after proven domain rollback or unanimous retained primary noncommit evidence. RecoveryWork.OTPBinding exposes exact frozen challenge/attempt/command linkage to that native owner, never submitted code or release rights. Missing/divergent evidence, ambiguous commit and expired leases do not release a challenge. Release is terminal: a new challenge is required, not reuse of the released OTP. Release failure retains reserved custody and a pending journal. These coordinator phases are tested with native SQL fixtures; the production OTP store, cryptography and authenticated final-login admission remain required. They are not an adoptable complete OTP workflow.

CommandPlan.Feature selects one exact frozen registration. Public PrepareCommandPlan copies the matching contributor order, 1..64 strictly ordered required audit slots and lifecycle declaration, and computes FeaturePlanDigest using the current retained-key command fingerprint. The preparation profile requires identity, audit, lifecycle/outbox and the exact feature contributor; audit/outbox contributors must implement their typed phases. Each audit slot has exactly one record, schema 1, positive retention version and at most 16 KiB record/aggregate bounds. Required record lifecycle versions are one checked successor; record-free declarations keep both zero. Feature-owned adapters remain responsible for exhaustive native schemas and action policy. Feature capability/cascade inputs fail rather than being silently discarded, except the exact identity.email.verification-confirm.native-v1 declaration. That profile preserves the original signed identity.identifier.verify purpose, envelope fingerprint, expiry and retained replay identity. It requires the identity.email native owner, identifier lifecycle, protected audits and command counters, and excludes OTP reinterpretation, fresh issuance and delivery. Its canonical history is readable without granting execution authority. Execution requires an EmailVerificationContributor, the real kernel repository and typed capability reservation/execution contributors. The ten EmailVerificationFields bind the original committed signup, canonical address and current predecessors. The kernel locks and verifies the original pending identifier, advances user and identifier authority, and commits proof consumption, protected audit and outbox in one transaction. Counter denial never reserves the proof; rollback cannot retain a verified address or successful consumption. Install the additive EmailVerificationMigrationSource after the complete existing migration history. The native owner still supplies original proof/origin and current action policy; this kernel profile alone is not the public email workflow or session issuance.

An empty CommandPlan.SubjectType retains the historical v1 structural-only profile and cannot reserve. For native execution, select a valid subject type and explicit AuditPlan.RetentionClass (standard or protected) for every slot. These fields are bound into canonical feature-plan-v2 bytes. The native adapter must implement FeatureExecutionContributor, exhaustively validate the immutable command and full security plan before reservation, and inspect retained effects during recovery. Every selected participant must implement recovery.

Use FeatureAuditBindingDigest for exact feature scope, subject and actor binding.

Native adapters call Work.FeatureScope(themselves) during Apply and RecoveryWork.FeatureScope(themselves) during recovery to verify the exact registered instance, active invocation and frozen version transition. Matching descriptors or a still-open Work after Apply returns are not native authority. The check performs no IO and returns owned scalar scope declarations. Then PrepareCommandPlan, ReserveCommand, Begin, ApplyFeature and Commit execute through the sole coordinator-owned transaction; always defer Abort after a successful Begin. The native phase owns current authority checks and its domain mutation, never kernel-table writes, audit/lifecycle staging, external IO or transaction closure. The coordinator binds the provisional receipt to the frozen transition and stages all audit/lifecycle effects. Only a successful Commit proves durability; ambiguous commits return unknown and never locally retry or reveal a bearer. Exact replay returns the original safe receipt.

Historical feature plans and command scopes are decoded as bounded, canonical records. Authorized QueryCommand returns an owned CommandRecord.Feature descriptor for feature history; it remains nil for kernel history. The stored scope, frozen plan and terminal receipt must agree on owner, operation, schema and record policy. Observation does not consult today's contributor registry, replay commands, renew authority or expose native response/credential payloads. Missing, wrong-scope and denied callers retain the same policy/read shape.

RecoverCommand observes live/terminal history. Expired native v2 commands can take a new generation only with the exact frozen typed participants. Unanimous retained non-commit evidence permits failure auditing and an aborted receipt in one transaction. Unknown/conflicting evidence stays pending; success is never reconstructed from current rows. Audit recovery can obtain an owned copy of all slots through invocation-scoped RecoveryWork.AuditPlans; the existing singular getter still rejects multi-slot plans. Historical v1 remains observation-only and never takes over. Capability and OTP-consuming profiles remain disabled until their atomic typed phases exist; risk consumption additionally requires its native current-check/finalize owner. This is not a working session issuer. Kernel digest bytes and the kernel-only scope decoder remain unchanged.

Stable status-filtered listing

Compose the same repository through identity.NewUserDirectoryService for collection/row authorization, redaction and authenticated wire cursors. List materializes structural IDs, statuses and versions atomically in the primary database; it is not a live OFFSET query or an authorization cache. Migration 7 creates the owned snapshot/row tables without changing users or migrations 1–6. Existing get-only consumers keep their APIs and configuration.

Ordering is bytewise ascending canonical user ID. Filters are an exact closed status set. Continuations require the original tenant, status set and expiry, and survive repository replacement and live insertion/update/deletion. Expiry retains nanosecond identity, lasts at most 15 minutes and cannot be renewed; primary time plus a shortened local deadline bounds each operation. Snapshot status is historical directory data, never current identity authority. The public service must reauthorize every page and each scanned row.

Config.ListSnapshots defaults to 10,000 users and 32 retained snapshots per tenant. Explicit profiles require both positive limits, at most 100,000 users and 32 snapshots. Pages are at most 100 rows. Each status branch uses the existing tenant/status/user index and bounds candidates before materializing. Quota or size pressure is identity.UnavailableError, never a partial snapshot or silent truncation. Mismatched/expired continuations are redacted invalid input; database failures disclose no diagnostics. An ambiguous snapshot commit returns no page/cursor and remains bounded by retention/quota.

New snapshot admission removes at most one expired snapshot. Trusted platform maintenance must also call PruneUserListSnapshots(ctx, tenant, maximum) for inactive tenants, with maximum in 1–32; primary expiry and SKIP LOCKED keep active/in-use snapshots intact, and removal cascades to their rows. The library starts no worker and never closes the caller's pool. These storage APIs confer no tenant permission. Grant the selected storage role the snapshot-table CRUD and existing user SELECT permissions; no DDL or table ownership is required.

Remaining scope: exact identifier filters require the remaining identity- owned identifier lifecycle store and fail closed today. Arbitrary attribute search, complete fields, privacy/lifecycle snapshot erasure and full domain commands remain unfinished. Do not create a list-only identifier authority or application-written domain store to fill those gaps.

Current development boundary

Consistent self-profile reads

The repository also implements identity.ProfileRepository. Select it explicitly with Config.ProfileSchema: ProfileSchemaRef{ID: "fields", Version: 1} and declare that same schema in Config.AttributeSchemas and identity.ProfileConfig.Fields.Schema. Zero leaves profile reads disabled. The selected schema must contain at most 123 additional fields, without aliases for name/image, credentials, identifiers, roles or other privileged core fields.

GetProfile observes the user, name/image and typed attribute document in one primary SQL statement. The stored schema key and immutable definition must match the selected declaration exactly. A missing structural user is ErrUserAbsent; an incompatible/corrupt stored document is Unavailable, with no partial output. The whole document is validated even for a narrow projection. Empty requested fields select all output-readable fields; explicit fields must be unique and known, with schema output permission. Structural ID/tenant/version remain bound to the aggregate; unselected values are not returned. Returned collections own their memory. Existing false/zero/empty values and full versions remain exact.

Forward migration 8 adds the owned identity.user_profiles name/image table. It preserves migrations 1–7, structural-only users and old writers. Missing rows produce empty name/image, not invented additional-field defaults or backfills. No independent profile version or authority is created. Grant selected storage roles SELECT on profile, attribute and schema tables along with user reads.

Compose through identity.NewProfileService for current-human self scope, active status, authorization, schema output filtering and current redaction. Storage reads confer no caller authority. Database image strings are bounded, never fetched, and still require the public service's exact HTTPS origin policy. The existing creation UnitOfWork can supply the service's dependency for reads; select the profile composition below to enable mutation and recovery. Indexed/ secret storage and privacy erasure remain required platform work, not application-written repositories or SQL workflows.

Durable self-profile mutations

Use NewProfileUnitOfWork(coordinator, repository, CreationUnitOfWorkConfig{ RetentionPolicyVersion: revision}) as the identity.NewProfileService command dependency. It requires the exact registered repository, selected ProfileSchema and typed audit/outbox phases. The existing creation owner remains creation-only. This is an opt-in composition of the same Coordinator, not another transaction, claim, receipt or recovery engine. No caller-written plans or SQL are needed.

ProfileUpdate admits current self scope and per-field policy before SQL. The storage owner resolves exact command replay before CAS, then requires an active user at the expected aggregate version. Name/image omissions preserve existing values; explicit additional false/zero/empty values replace only their named fields, preserving all omitted values without default backfills. Selected schema definitions must agree exactly. Name/image, the canonical typed document, one full-uint64 version increment, privacy-safe identity.user.update audit, identity.updated.v1 outbox event and original receipt commit atomically.

RecoverProfileUpdate and exact retries preserve the original result after later mutations; current authorization/redaction still control its disclosure. A changed command conflicts; stale or blocked new writes close with audited NotCommitted and no domain/outbox prefix. Participant failure/panic rolls back; unproved or ambiguous closure remains Unknown. Expired pending recovery requires all frozen participants' negative evidence. The domain's original unchanged version is negative evidence under the journal and tenant fences; a missing or changed aggregate remains unknown, never inferred success. No fresh authority, session, provider call or background worker is created.

Storage roles need UPDATE on users and SELECT/INSERT/UPDATE on profile/value tables, with SELECT/INSERT on immutable schema definitions and the existing command, audit and outbox permissions. Migration 8 already supplies profile storage; migrations 1–8 and existing structural writers are unchanged. The remaining kernel lifecycle profiles are unfinished.

Durable administrative attribute updates

NewUserUpdateUnitOfWork supplies the existing UserUpdateAdminService with the sole Coordinator's command protocol. Register the exact Repository and typed audit/lifecycle phases as for creation. Select frozen AttributeSchemas; the independent ProfileSchema feature is not required. Current operation and per-field authorization remain in the core service, not role labels or direct adapter calls. The current audit actor profile supports human and service accounts; API-key actor composition remains unsupported and fails closed.

ApplyUserUpdate locks the authoritative aggregate and replaces individual whole typed values, preserving omissions, explicit zeros, output-denied stored fields, and the existing lifecycle status. Deleted/anonymized users cannot be updated. The expected version fences exactly one full-width successor. Neither name/image storage nor credentials, identifiers, roles or authority versions are changed. Each command uses its exact registered schema ID/version; stored definition mismatches and corrupt documents fail without a partial result.

One transaction persists the values, protected identity.user.update audit, identity.updated.v1 lifecycle and original structural receipt. Exact replay precedes current-state CAS; a live parallel retry can return InProgress and must retain the same command ID. Recovery observes the original receipt under current core authorization/redaction. Expired pending commands close only with the unchanged original aggregate version and negative evidence from every frozen participant; missing/changed evidence remains unresolved. No second transaction owner, callback inside SQL or migration is introduced. Storage roles need the existing user and attribute/schema read/write permissions; administrative updates do not require writes on the self-profile table.

Focused real PostgreSQL tests exercise these adapter semantics through the public service with typed SQL audit/outbox test phases. Updated production audit/outbox administrative composition and complete lifecycle/release gates remain pending; the self-profile production composition is separately proven.

Owned creation service composition

NewCreationUnitOfWork(coordinator, repository, CreationUnitOfWorkConfig{ RetentionPolicyVersion: revision}) supplies the core identity.UnitOfWork dependency for identity.NewUserCreationService. The exact repository instance must already be registered with typed audit and lifecycle contributors. The adapter owns plan construction, privacy-safe audit records, primary time, reservation, execution, closure and scoped receipt lookup. Consumers do not implement a domain store or supply Work, audit-record builders or command plans.

This is a trusted storage seam, not a transport endpoint: only the core service provides current caller authorization, field preparation and output redaction. Creation supports human and service-account actors; API-key actor audit mapping remains unsupported and fails before reservation. Failure evidence is built before domain writes and staged after proven rollback, never by unpoisoning SQL Work. No success prefixes survive participant failure. A failed failure-audit commit or ambiguous transaction remains Unknown. Replay preserves the original receipt and audit ID, including after retained fingerprint-key rotation.

Recovery returns historical creation, not current user status. Live pending returns InProgress without changing ownership. Expired creation can take a new generation and atomically abort with failure auditing only when every exact frozen contributor supplies RecoveryContributor and proves non-commit. Missing, unknown or conflicting evidence remains pending. Existing users never become reconstructed success receipts. Other command profiles, recovery-deadline alerting and transaction retry policy remain unfinished. Existing test SQL contributors prove coordinator atomicity, not production audit/outbox adapter interoperability; that composition remains required before package completion.

RecoverCommand(ctx, query, caller) uses current QueryPolicy authorization and returns metadata only; owned core recovery uses the trusted storage seam without synthesizing caller identity. RecoveryWork is invocation-bound, exposes only scope, bounded evidence queries and the participant's frozen declaration, and cannot stage mutations or close transactions. Contributors read retained bindings even when payloads have been pruned. QueryCommand remains observational.

RecoverFeatureCommand(ctx, query, caller) uses that same current disclosure policy and recovery owner, but returns the full safe feature receipt: original binding/operation, terminal audit ID and declared before/after versions, or pending retry metadata. Kernel user/profile commands are forbidden before reconciliation; generic RecoverCommand remains metadata-only. Missing commands are never reserved. Unsupported expired participants leave pending evidence unchanged; ambiguous commits return UnknownCommitError without credentials. Feature receipts carry no session, proof or native response and grant neither current authority nor credential reveal permission. Native feature adapters must match their own exact retained intent/evidence and enforce current result-access policy before composing recovery. Original frozen participants, not today's domain state, determine the historical outcome.

Primary command lookup

CoordinatorConfig.QueryPolicy optionally enables QueryCommand(ctx, query, caller). Configure the existing authorization.Service, a trusted clock.Clock and positive current PolicyVersion; nil keeps lookup disabled. Policy callbacks run before the single primary read, never under an open transaction.

Trusted authenticated composition supplies the authorization.DecisionContext: the actor/kind, tenant, original operation and identity.user resource targeting the query's user must match at that current revision. Do not decode caller identity or authorization attributes from client overrides. Every historical query field—including optional record ID and link mode—must match the stored command. Current policy permits disclosure but never rewrites old policy/schema versions or correlation. Reserved identity.command.* attributes are rebuilt from the exact query: ID, record ID, decimal link mode and recovery/read-admission flags cannot be replaced by caller attributes. Missing, wrong-scope and denied requests all perform the bounded decision/read shape and expose zero receipt plus ForbiddenError; this is not an identical wall-clock latency guarantee.

Pending, including an expired lease, remains InProgress. CommandRecord exposes only historical scope, outcome and retry metadata, never stored profile, attribute, account or credential payloads. It is not current user status or fresh authentication authority. Protected replay values stay inside owned core recovery and its current field-redaction policy. Orphaned, legacy/incomplete or corrupt history fails closed. Lookup neither locks for mutation nor changes a lease, generation or contributor. RecoverCommand and the owned UnitOfWork service bridge remain unfinished; callers must not implement their own transactions or participant recovery to replace them.

Identifier and verification partitions

Apply forward migration9 before calling GetIdentifierState. It adds the positive identifier_version authority dimension to users (initial version1) and identity-owned identifier/verification rows. Existing users retain their aggregate versions; structural writers that omit the new column remain valid. The migration takes PostgreSQL DDL locks and validates the new user constraint; run it through the bounded migration Runner during a reviewed migration window. No destructive downgrade or application-written backfill is supported.

GetIdentifierState(ctx, identity.IdentifierQuery{TenantID: tenant, UserID: user, MaximumIdentifiers: 128}) implements the existing public storage port. One indexed SQL statement returns the complete ordered partition or an error with no partial state. The limit must be1..128; oversized partitions are unavailable, not truncated. Missing users return ErrUserAbsent. The configured repository budget and any earlier caller deadline bound pool acquisition and query execution. Returned slices own their memory; the pool remains caller-owned.

Canonical values are exact, case-sensitive, at most512 UTF-8 bytes with no C0/C1 controls. Optional display values have the same bounds but may be empty. IDs preserve the existing validated directory-ID profile. Record and canonical-value uniqueness is tenant-local; canonical uniqueness also includes kind. A user has at most one verified primary identifier of each kind. Verification state and identifier flags share a row and database constraints; pending has no timestamp, verified requires one, revoked may retain the original timestamp. Reads reject future or otherwise inconsistent verification timestamps and preserve uint64 versions without signed-bigint truncation. Neither snapshots nor structural validation grant authorization or prove a challenge.

IdentifierMutationMigrationSource{Base: source, Version: allocatedVersion} appends forward-only retirement history after all migrations in source. Allocate a unique version greater than every installed/composed Base version; do not replace or renumber existing migrations. The new table retains tenant, user and identifier IDs, exact retired record/verification versions, original retirement and reuse-expiry instants, and a keyed digest rather than retired canonical/display values. ID history remains necessary after a value cooldown expires; this source intentionally supplies no deletion or downgrade policy. Run it through the same bounded migration Runner in a reviewed DDL window.

Native provisional writes now implement all five identifier transitions under the existing Work transaction. They lock the complete bounded partition, preserve original verification instants, demote the old primary before promotion and atomically persist retirement history with exact optimistic version fences. Stored value-cooldown expiry is not renewed by key/policy changes; missing keys for still-active history deny, while expired history does not require those keys forever. Retired IDs cannot be attached anew even after value expiry.

This remains a storage foundation, not a complete identifier workflow. The writer is private and public capability-bearing Begin remains disabled. Use the existing IdentifierService for admission once native current-authority, challenge/final-access checks, atomic capability/risk consumption, audit, lifecycle, complete commit receipts and recovery composition are implemented. Do not supply application-owned SQL or transactions to bypass those requirements.

MigrationSource{} owns identity.users with tenant_id, user_id, status and version. Compose the source with the existing go-migrations/v3 Runner and PostgreSQL backend before constructing the repository. The source creates no private ledger or migration runner. Initial install requires an unoccupied identity schema and runs atomically. Replayed migrations preserve populated data; destructive downgrade is unsupported. Future changes append history.

It is not yet an adoptable complete durable identity adapter. Do not write application-owned identity tables or transactions to bridge that gap. Commands, snapshots, attributes, imports, lifecycle cascades, audit/outbox, reconciliation and the shared transaction coordinator remain unfinished.

The appended command-claim migration installs the global ID claim and scoped journal foundation. Private admission runs inside the Coordinator's transaction, never commits independently, and does not grant mutation authority. Exact replay selects the stored fingerprint-key version; missing retained keys or missing scoped rows fail closed. Retired IDs conflict permanently. The owned retirement policy and scoped recovery still require implementation; the later migrations provide leases, terminal receipts and frozen plans.

The private codec maps core commands, including privacy requests, account link/unlink and all identifier actions, through typed accessors. It uses the closed identity-command-v1 deterministic encoding profile, framed HMAC-SHA-256 digests for all private fields, and stored-key regeneration on rotated-key replay. Directory IDs retain their exact validated representation, including ULIDs; random command IDs become fixed-width byte strings. Attribute times must be microsecond-exact within PostgreSQL years 1..9999; no rounding is performed. Equivalent whole-field replacement ordering does not change intent, but list ordering does. No raw command, name, image or attribute value enters persisted collision fields. Invalid command values fail closed. Provider subjects/issuers, identifier values and the complete authenticated capability authority are represented by framed keyed digests. Capability owns its canonical payload representation; the adapter never JSON-serializes core commands or consumes a proof during encoding. Proof header/key metadata, all version fences, link modes, credential references, provider-revocation choice and session/pre-auth continuations are included. A changed authenticated proof is changed intent, not an implicit recovery credential. The claim phase does not yet reserve or finalize proof use with a domain mutation. The encoder follows RFC 8949; full protocol interoperability and release evidence remain pending.

The third forward migration extends the existing command journal with private pending ownership, positive generation/attempt counters and database-time lease, heartbeat and creation/update fields. Matching live reservations return bounded retry delays; expired reservations acquire a new generation inside their caller's transaction. Heartbeats cannot renew expired or stale ownership. A takeover is not public apply authority: all declared participants must still be rebound in that same transaction before the future Coordinator can commit it. No private helper owns commit/rollback or infers a terminal result from lease expiry. Foundation-only rows keep NULL ownership metadata and remain readable by older claim code; the new reservation path rejects them until authoritative recovery can prove their history. This migration does not fabricate ownership, classify them as aborted or enable terminal rows without complete safe receipts.

The fourth migration enables committed/aborted rows only with a positive supported receipt version, bounded body, database terminal time and closed classification. Private terminalization locks and rechecks live generation and owner; it never commits independently. Exact replay returns the original typed receipt, not current user authority. Core CommandResult.Validate owns receipt invariants; the private version-1 JSON storage representation rejects unknown fields, duplicates, alternate spelling, lossy values and trailing input by requiring exact re-encoding. JSON is not used for command fingerprints. Retained attribute instants are encoded from an owned UTC copy and must be microsecond-exact within PostgreSQL UTC years 1..9999. Second-offset time zones cannot lose offset seconds in JSON, and caller-owned receipt values are untouched. Receipts may retain authorized profile/attribute snapshots and private identifier intent digests; treat this restricted replay storage as identity data under retention/access policy, never logs, metrics or transport responses. Encoding validates bounded core values before allocation; decode rejects bodies over 8 MiB. Required audit/participant staging and public scoped recovery are not yet implemented, so private terminal SQL is not a conforming composed mutation API.

Final-authentication coordinator admission

Configure CoordinatorConfig.FinalAuthentication with an explicit trusted authentication.AuthorityAuthenticator and a stable durable namespace. Do not derive either from request data or change the namespace while proof-use tombstones exist. An exact registered AuthenticatedFeatureContributor owns exhaustive native-command mapping and initial/final current-authority checks. Its checks run inside the coordinator-owned Work and must not write, perform network IO, consume proofs, renew freshness, or retain transaction authority.

Use PrepareAuthenticatedCommandPlan and ReserveAuthenticatedCommand with the same original opaque proof and native command. The existing retained-key fingerprint binds the original namespace, credential/proof IDs and versions, scope, method, assurance, and exact original timestamps without exposing raw correlations in canonical intent. Ordinary ReserveCommand cannot execute identity.session.issue. Preparation validates provenance, not current eligibility; reservation does not consume the proof.

Initial admission stages the proof-use tombstone in the same transaction as native effects, audit, lifecycle and the terminal journal. Final admission rechecks original proof expiry and native current authority. Failure rolls back provisional effects and consumption. Exact replay returns historical metadata, never a new bearer or refreshed authority; retained fingerprint-key rotation preserves replay identity. Pending recovery cannot classify the kernel as effect-free when a proof-use tombstone exists.

This is coordinator admission, not a session service: complete native session/family issuance, their authority checks and recovery, bearer custody, and composed login remain unfinished. The integration fixture's synthetic feature proves coordinator atomicity only, not production session behavior.

Domain begin admission

Private domain-begin admission now revalidates the retained-key global claim, locks the scoped pending journal and verifies generation, owner and lease using database time read after lock waits. A key rotation with the retained original key preserves admission; changed intent, stale/foreign/expired ownership and terminal rows never become apply authority. Missing history or keys fails closed. The future Coordinator owns rollback on every failure and bounds Work by the remaining lease; this private snapshot neither renews validity nor begins/commits/rolls back a transaction or invokes participants. Public Work issuance and complete Begin orchestration are still unavailable.

Restricted Work execution

Work now provides Scope, Exec, Query and DatabaseTime for trusted compile-time enlisted adapters. Its constructor is private; application code cannot acquire valid Work until the complete Coordinator is available. All aliases share generation, scope, deadline, failure and closure. Work/WorkRows are serial, not concurrent APIs. The deadline starts before the authoritative clock read roundtrip, cannot restart on construction, and is never renewed by DatabaseTime. The coordinator must invalidate aliases/active rows before closing its transaction and retain sole commit/rollback ownership.

SQL must be a trusted compile-time SELECT/INSERT/UPDATE/DELETE/WITH statement up to 64 KiB with no more than 64 closed scalar parameters/1 MiB total. Inputs do not admit driver options, query rewriters or custom marshalers. Extended protocol executes the exact SQL through a fixed owned binary scalar profile, even without parameters; prepared-name aliases and caller-installed codecs cannot replace it. Multi-statements are rejected by PostgreSQL. Initial execution errors are resolved before returning rows. WorkRows exposes no driver or connection and permits only closed typed scan destinations, not RowScanner or custom scanners. It returns at most 256 rows, 64 columns and 1 MiB raw result bytes. Close rows before another query, inspect Err, and discard all destinations after a Scan error. SQL/scan/ budget/cancellation failures poison further execution; diagnostics are redacted. Empty byte parameters remain non-NULL and are copied before I/O.

This is not a sandbox for malicious adapter SQL, a tenant query rewriter, or a bound on server-side query work. Contributors must use scoped/indexed statements and cannot invoke functions changing transaction ownership/isolation or external state. No raw transaction, connection, nested transaction or closure API exists. Audit/effect writers, typed participant phases and complete Coordinator issuance remain required next; this partial execution surface is not full command authority.

Kernel audit admission

AuditPlan, AuditBindingDigest and Work.StageAudit now implement the kernel staging boundary. Coordinator-private admission freezes the plan before SQL; the current kernel mapping requires exactly one action for its command, including the canonical user action for profile/admin aliases. It rejects empty, duplicate, late or rebound plans. No public method can enlist an audit or obtain valid Work. Records must match the declared index/action/schema, command, tenant, actor, target aggregate, policy and correlation. Exactly one immutable record is staged per index; missing or duplicated staging fails closed. Invalid staging poisons Work. Record/aggregate bounds may lower the 16 KiB identity security ceiling.

The current kernel profile accepts privacy-processed no-change/redacted records, closed aggregate/version/reason attributes, safe opaque context IDs and bounded producer tokens. Free descriptions, raw network/user-agent data, unknown attributes, arbitrary structured changes and delegation are unsupported and rejected. Feature-specific fields, composed multi-action mappings and the typed complete IdentitySecurityEventV1 builder remain required implementation. The identity profile requires 128-bit-or-stronger opaque IDs: configure audit.Builder with a trusted random generator, such as identity.NewSubjectID, before Build. The primitive default UUID has fewer than 128 random bits and is not selected by this profile. Staging preserves IDs; it never derives them from a command or replaces them. Canonical base64url 128-bit and lowercase hex 128-bit ID profiles are accepted; format validation cannot attest randomness.

This is owned in-memory staging, not persistence, an independently committable audit transaction or complete command authority. The registered audit contributor must persist each canonical record and its command/index binding through the same Work; the future Coordinator must enforce completeness before commit and retain denial/unknown recovery evidence. Those durable paths are not yet present.

Contributor registration

CommandPlan.Lifecycle adds one typed kernel notification plus the exact outbox/postgres identity.lifecycle v1 contributor. Work.StageLifecycle constructs a safe scalar-only record with a stable command/class/index ID; StagedLifecycle returns an owned snapshot only after successful required audit staging agrees on its target and before/after versions. It accepts no arbitrary payload, identifier value or bearer. The trusted adapter obtains occurrence time from Work.DatabaseTime; staging itself does not perform I/O. Closed or failed Work cannot produce notifications. Mismatches poison the Work.

The open LifecycleContributor will persist these records through the same Work, not a separately committable transaction. Persistence, cascade consumer snapshots/checkpoints, encrypted delivery/provider effect profiles and complete Coordinator invocation are still pending. Older audit-only admission remains compatible, but cannot satisfy a successful future mutation commit. The deletion notification is identity.deletion_requested.v1, never proof of completed erasure.

AuditContributor supplies the open durable audit phase. Work.StagedAudits exposes owned declaration/record pairs only when every required slot is staged. The registered audit adapter uses this snapshot to write canonical records and immutable command/index bindings through that same Work. It cannot retain Work or own transaction closure; success is staging, not commit. Complete Coordinator phase invocation remains under development.

CommandPlan declares ordered contributor descriptors, required audit slots and a digest. KernelPlanDigest binds the current kernel-only profile to the exact command scope and authoritative fingerprint using deterministic CBOR. Admission snapshots the slices against the exact registry; later input mutation cannot change admitted work. Audit binding rejects foreign-registry Work, different commands and late/repeated enlistment before SQL.

This intermediate profile supports exactly one domain and one audit contributor. It does not accept feature, risk, capability or OTP contributors without their typed inputs; it cannot substitute for their atomic reservation. The Coordinator must resolve retained-key fingerprints before plan admission. Public command issuance, durable audit delivery and complete participant phases remain pending.

CommandPlan.Capability can now freeze one scalar, single-use capability input for deterministic digest preparation and bounded historical decoding. It binds the exact signed ID, purpose, expiry/use bound, independently keyed replay digest and retained key version, and immutable proof fingerprint. The enclosing command fingerprint binds target/version intent. Existing audit-only and lifecycle plan bytes are unchanged. Formatting redacts this input and JSON export is rejected. This declaration is not proof validation. Exact identifier commands can now prepare/reserve when the registry supplies a CapabilityReservationContributor. The coordinator freezes owned inputs, checks signed ID/expiry/use and target versions, and invokes Reserve or exact-predecessor Rebind under the same claim, journal and tenant locks. Failure, panic or unfinished rows rolls back every prefix; returned invocation handles and rows cannot outlive the phase. Retained fingerprint keys remain authoritative on replay. Contributors never own closure. The additive CapabilityExecutionContributor seam provides separate CapabilityApplyWork and CapabilityFinalizeWork invocations. Their bindings select the original frozen input and current generation, never predecessor release authority. Only the exact registered instance can inspect them; wrong phase, foreign registry and retained copies fail. SQL uses the existing bounded Work, with no pool, transaction closure or raw driver escape. Callback errors, panic and unfinished rows poison the underlying work. These custody contracts do not yet provide a production consumption algorithm or native identifier mutation, and cannot consume an authentication.AuthenticatedProof. Begin still rejects these reservations before consuming their opaque handle: domain/session/risk/apply/finalize phases and the production capability store are pending. No capability use or complete workflow is claimed by a reserved journal. Existing creation/profile/admin composition is unchanged.

Expired identifier-attachment commands additionally support primary recovery when every frozen contributor supplies RecoveryContributor and the capability participant supplies CapabilityReleaseContributor. Missing targets and exact reserved capability bindings are negative evidence, never sufficient alone. Only unanimous non-commit evidence under journal and tenant exclusions grants CapabilityReleaseWork; it CAS-releases the prior generation to a terminal state with the new recovery generation. Failure audit, terminal capability and aborted receipt commit together. Missing, conflicting or unknown evidence and callback errors/panics roll back the entire takeover. Capability expiry does not release an unknown outcome; terminal repeat returns the original receipt. These SQL fixture tests prove coordinator atomicity, not production capability-store composition. Other identifier operations and successful consumption remain open.

Contributor identities can now be composed with NewContributorRegistry([]Contributor{...}). The registry snapshots 1..64 trusted compile-time adapter descriptors once, preserves composition order, rejects nil/typed-nil, duplicate contract IDs and conflicting versions, and allows only exact registered descriptors in private command admission. Owners are bounded lowercase printable ASCII; contract IDs are bounded printable ASCII; neither admits whitespace or normalization. Composition roots own canonical IDs and contributor lifetimes. Returned Descriptors() slices are caller-owned copies and registry reads are concurrent-safe. Implementations remain open to independent modules. This is identity admission only: no transaction phase, typed participant input, Work issuance, late registration or commit API is provided by registration. Unsupported phase combinations and foreign plan rejection remain part of the forthcoming complete Coordinator, not guarantees of this constructor.

Command reservation

NewCoordinator(primaryPool, registry, CoordinatorConfig{...}) owns bounded reservation transactions. Configure positive operation/lease durations no longer than one minute, a microsecond-exact lease, and 1..32 retained nonzero 32-byte fingerprint keys with an explicit current version. Keep the pool primary-only and caller-owned. Configuration/Coordinator diagnostics hide keys and reject JSON serialization. Registration is immutable; contributor resources stay owned by the composition root.

Use PrepareCommandPlan(binding, typedCommand, plan) to obtain an owned digest with the current key, then ReserveCommand(ctx, binding, typedCommand, plan). The initial public profile requires user creation, one required audit slot and the matching lifecycle declaration with typed audit/outbox contributors. One-time and cascade profiles are rejected before SQL. Services must authorize commands first; preparation is not authentication or authorization.

Migration 5 adds a bounded immutable canonical plan to the existing journal. It leaves historical rows NULL, not invented participant history. A matching replay uses the stored key version and fingerprint; key rotation cannot rewrite the declaration. Changed scope, intent or plan conflicts; missing retained keys, NULL historical plans and corrupt history fail closed. Plan replacement is rejected by a SECURITY INVOKER trigger, not a defense against privileged administrators or DDL owners. Cleanup remains the retention owner's obligation and must preserve global non-reassignable claims.

A new or expired reservation returns opaque generation ownership and InProgress. Busy replay has no ownership; terminal replay retains the exact historical receipt, not current authority. A proven reservation commit is never a user commit. Failures before durable observation or after proven rollback return a zero result, not fabricated NotCommitted. Any commit-attempt failure or unproven rollback returns Unknown; no automatic retry or rollback follows a commit attempt. The detached rollback budget is finite and earlier operation deadlines win. No contributor callback executes during reservation.

Creation execution (development profile)

Coordinator.Begin(ctx, reservation) consumes exact ownership once and opens one bounded primary transaction. Reservation copies cannot issue another Work. The original lease is checked after command locks; waiting never renews it. Kernel mutations also take a transaction-scoped tenant lock. Work and its cursors are serial-use; every path must close through Commit or Abort, including panic (normally with deferred Abort). No closure goroutine is started. An idle transaction timeout limits abandoned server locks but does not substitute for releasing the caller-owned pool connection.

Repository.ApplyUserCreation(ctx, work, command) requires the exact registered repository and frozen creation command. It inserts an active version-1 user; the returned user is provisional until Commit. Declare up to 32 copied, versioned Config.AttributeSchemas for ordinary scalar/list storage. The exact tenant/schema/version definition becomes immutable in the same transaction; different definitions under that identity conflict. Undeclared fields/kinds or unsupported indexed/secret profiles fail closed, not silently disappear. Repeated apply poisons the transaction. Stage the required successful audit with redacted structural changes and the declared lifecycle record before Coordinator.Commit(work, result). Commit checks the caller result against the actual mutation, invokes the registered audit then lifecycle persistence phases through the same Work, terminalizes the journal and commits once. Missing evidence, open cursors, changed results or a phase failure roll back all prefixes. All aliases close before transaction closure. Any error after commit starts is Unknown, never automatically retried.

Coordinator.Abort(work, cause) proves rollback before a separate bounded terminal transaction. A complete matching pre-staged denial/failure audit is required for a known NotCommitted result; terminal audit and receipt commit together. Missing evidence or lost ownership leaves pending/Unknown for recovery, not fabricated success or denial. Detached cleanup remains bounded after caller cancellation; driver and caller error text is never exposed.

Attributes use a private bounded version-1 canonical CBOR document, preserving present false/zero/empty values, int64 extrema, ordered string lists and UTC microsecond-exact instants without float conversion or JSON escaping growth. They are private stored values, never diagnostic snapshots. Recoverable secret fields require the future owned secret-envelope profile; there is no plaintext fallback. Indexed fields need explicit field migrations, not arbitrary search. Migration 6 adds schema/value tables without inventing values for old users; old structural writers/readers remain supported. Definition update/delete/ truncate is rejected for ordinary writers, not hostile DDL/database owners. Public reads still return structural fields only; field authorization, redacted projection, attribute updates/backfills and secret/index profiles remain required.

This is not yet an adoptable identity.UnitOfWork: remaining attribute profiles, other domain commands, the owned service bridge, classified retries and scoped query/recovery remain required. The integration suite proves actual PostgreSQL transaction behavior with typed audit/lifecycle SQL seams, not production audit/outbox adapter interoperability. Do not supply application-owned identity transactions or stores to bridge the unfinished profile.

Denial-only credential compromise

The registered password or passkey participant may implement CredentialCompromiseContributor for its closed mark-compromised operation. Its frozen command includes CredentialCompromiseFields plus native detection and authorization metadata. The coordinator locks the exact user/reference and checks the independent aggregate, credential-authority and reference versions before invoking native verifier disablement. Banned/suspended and expired credentials may be disabled; deleted/anonymized users and already disabled or stale references are rejected. No credential is enabled or restored.

The existing outbox participant must also implement CredentialCompromiseLifecycleContributor. Its same-Work phase persists both StagedLifecycle and StagedCredentialCompromise, keeping all three version dimensions distinct. These provisional values grant no current authentication authority or cascade acknowledgement. Native mutation, kernel metadata, audit, outbox and the original journal receipt use the sole coordinator transaction. Only the shared commit establishes durability; replay preserves the original receipt even after later changes. Retained participant evidence cannot be replaced by a lookup of current credential state.

Compose CredentialCompromiseMigrationSource after credential-reference history with an explicitly allocated later version; retain its evidence with command tombstones. This is not password set/change/reset, passkey ceremony validation, or production password detection. Those workflows still need their real native owners, proof consumption and composed adapter evidence.

Existing-password replacement

CredentialReplacementContributor enlists the kernel-owned effect for identity.password.change. Its complete frozen command carries CredentialReplacementFields and the native workflow's original policy intent. For verifier writes use identity.NewFeaturePasswordHashCommand; native owners select PasswordHashFeature and explicitly borrow PasswordHash for parsing and SQL-driver storage. The coordinator binds exact hash bytes with the command fingerprint key, never raw journal metadata. Changed verifier bytes conflict with the original command ID, including terminal replay. Legacy hash-free commands keep their encoding but cannot supply material through this custody. The coordinator matches the native mapping, locks the primary user and password reference, and checks active status, enabled state, expiry and all three exact predecessors. Native hash replacement runs in the same Work; the kernel then advances the user aggregate, credential authority epoch and reference version. The credential's owner, identity, enabled state and expiry do not change.

Install CredentialReplacementMigrationSource after credential history with an explicitly allocated later version. The existing outbox participant also needs CredentialReplacementLifecycleContributor; persist StagedLifecycle and StagedCredentialReplacement without conflating their version dimensions. Native material, kernel metadata, audit, outbox and the original command result share one recoverable transaction. Any failed phase rolls back all effects. Pending-journal recovery treats retained effects as unknown, not success inferred from the current credential. Exact terminal replay returns the original receipt.

This is a trusted persistence seam, not an authenticated password-change endpoint. Native workflow composition must still own reauthentication proof validation/consumption, HIBP, reuse policy, secret custody and session policy. Do not supply application-written stores to bridge those unfinished workflows. Registration, provider-only set, reset/recovery and hash-only rehash remain separate pending profiles; this effect cannot enable or restore credentials.

FAQ
  • Can I use a replica? No; the repository's primary consistency contract is required for security composition.
  • Are reads authorization? No; use the identity query service.
  • Can I request extra fields? Only id, tenant_id, status and version are supported; unknown or duplicate fields are rejected, not ignored.
  • Is the pool closed by the adapter? No; the application retains ownership.
  • Is this released? No. Full adapter implementation and release gates remain pending.

Integration testing

Initial phone confirmation participant

PhoneVerificationContributor selects only identity.phone.verify.native-v1 under the logical identity/phone/postgres owner. Use PhoneVerificationFields with the original committed enrollment command, canonical number, immutable normalization profile and exact pending identifier/verification versions 1/1. The selected PhoneEnrollmentDomain must borrow the same enlisted repository. The operation requires an authenticated-session command, consuming OTP, protected audit and identifier.verified.v1 1→2; it neither issues a session nor changes a primary number. No new migration or transaction owner is introduced.

Input admission calls RequirePhoneVerificationTarget before credential, session and factor locks. It exclusively locks and compares the original user/ identifier partition before an OTP comparison can charge an attempt. Kernel preparation does not write possession; Apply rechecks the actual enlisted OTP reservation before persisting verification in the coordinator transaction. Final OTP checks may map only that Work's exact persisted identifier successor; all other authority dimensions and original validity times remain unchanged. Current rows never reconstruct historical success during recovery.

These are trusted storage/admission contracts, not a complete phone endpoint. The native workflow must authenticate original enrollment/session possession, derive only the enrollment's exact authority successor, enforce factor/risk/ CSRF policy and provide code-free unknown-outcome recovery. Ordinary session validation is not relaxed. The focused storage test deliberately does not claim genuine caller, SMS or complete OTP interoperability.

The private identifier storage path provisionally consumes its enlisted capability through the same Work after locked state/cooldown checks and before identifier writes. Only the owned exact identifier receipt can reach Commit; the coordinator finalizes consumption after provisional audit/outbox effects and before its terminal receipt. Phase failures poison Work and require Abort. Public identifier Begin remains disabled until native session, current policy, challenge, final-access and recovery composition is complete. Private tests use a phase probe to prove invocation and storage rollback, not native capability-store interoperability or an executable verification endpoint.

go test -tags integration ./... requires IDENTITY_POSTGRES_TEST_DSN pointing to an explicitly disposable loopback PostgreSQL cluster with database identity_test and database-creation permission. Each invocation creates and removes its own random database; it never drops the supplied seed database. Missing infrastructure fails the selected lane rather than skipping it.

PostgreSQL numeric with scale/range checks preserves all uint64 versions and rejects fractional values; a scale-constrained type would round before checks. See PostgreSQL numeric semantics.

Documentation

Overview

Package postgres implements the authoritative PostgreSQL identity store. It includes owned forward-only migrations and structural creation execution; complete commands, attributes and recovery remain under development.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AnonymousCreationFields

func AnonymousCreationFields(intent AnonymousCreationIntent) ([]identity.FeatureField, error)

AnonymousCreationFields maps the complete prepared kernel intent into scalar original-command fields before keyed fingerprinting. Attributes use a domain-separated commitment, not public serialized values. Results own their bytes. Structural validity does not establish field policy, risk or privilege.

func AnonymousDisposalFields

func AnonymousDisposalFields(i AnonymousDisposalIntent) ([]identity.FeatureField, error)

AnonymousDisposalFields binds every original kernel/retention input to the command. It is structural mapping only, with no IO or destruction authority.

func AuditBindingDigest

func AuditBindingDigest(binding identity.CommandBinding, record audit.Record) ([32]byte, error)

AuditBindingDigest computes the domain-separated deterministic binding of a kernel event to the exact core command, actor and target. It includes neither event ID nor outcome: Builder owns random IDs, and success/denial/failure is selected at execution. It is correlation, not authentication or redaction evidence. Invalid/mismatched scopes return redacted InvalidInputError. The current kernel profile accepts redacted/no-change records only; broader feature profiles and typed event construction remain under development.

func CredentialCompromiseFields

func CredentialCompromiseFields(s CredentialCompromiseIntent) ([]identity.FeatureField, error)

CredentialCompromiseFields returns eight independently owned canonical metadata fields for a native command mapper. Include every field unchanged in NewFeatureCommand along with its native fields; never infer a missing epoch. This does not enable an operation, classify a breach or authorize a caller.

func CredentialReplacementFields

func CredentialReplacementFields(s CredentialReplacementIntent) ([]identity.FeatureField, error)

CredentialReplacementFields returns owned canonical metadata for a native command mapper. Include every field unchanged alongside native policy intent. The scalar encoding is shared with denial-only compromise, but the admitted operation, native trait, eligibility and effect remain independently checked. No missing predecessor is inferred and this function grants no authority.

func CredentialResetFields

func CredentialResetFields(i CredentialResetIntent) ([]identity.FeatureField, error)

CredentialResetFields returns independently owned predecessor metadata for the exact native reset command. Include every field unchanged before binding original proof/verifier custody. This performs no IO or authorization.

func EmailAttachmentFields

func EmailAttachmentFields(s EmailAttachmentIntent) ([]identity.FeatureField, error)

EmailAttachmentFields returns every kernel-owned canonical input. Include these unchanged before fingerprinting. Structural bounds do not normalize addresses or confer current authority. Pending email attachment and its distinct native resend profile are supported; verify, replace, primary selection and removal are separate flows. Resend retains exact target predecessors and the unchanged canonical mailbox.

func EmailRemovalFields

func EmailRemovalFields(i EmailRemovalIntent) ([]identity.FeatureField, error)

EmailRemovalFields returns all kernel-owned original intent for command fingerprinting. No IO, normalization, proof authentication or mutation occurs.

func EmailVerificationFields

func EmailVerificationFields(s EmailVerificationIntent) ([]identity.FeatureField, error)

EmailVerificationFields returns ten owned canonical fields for the native confirmation command. Include all unchanged before fingerprinting. It checks structural bounds, not normalization, cryptography or current authority. A username signup adds an eleventh exact original-operation field; the empty legacy selection retains its original bytes and password-signup meaning. Only the initial pending signup email profile is supported here; session management, OTP, resend, replacement and address removal are distinct flows.

func FeatureAuditBindingDigest

func FeatureAuditBindingDigest(binding identity.CommandBinding, operation identity.FeatureOperation, subjectType string, record audit.Record) ([32]byte, error)

FeatureAuditBindingDigest binds a native feature audit's exact registered owner/schema/record policy, actor and primary target kind. It grants neither authentication nor registration. The native adapter must validate subjectType and every required action before admission. API-key principals use audit's service actor representation; their distinct kind remains in command scope. Invalid/mismatched bindings return redacted InvalidInputError; no IO occurs.

func FeaturePlanDigest

func FeaturePlanDigest(binding identity.CommandBinding, fingerprint [32]byte, plan CommandPlan) ([32]byte, error)

FeaturePlanDigest structurally binds an explicit feature preparation profile, ordered contributor identities, exact schema, required audits and lifecycle declaration to the command binding and nonzero fingerprint. Digest is excluded. It performs no I/O, registry lookup, authorization or native schema validation. Trusted adapters must declare every required action; these bounds do not prove that declaration complete. The coordinator alone computes authoritative keyed intent and matches its frozen registry. Preparation grants no reservation, Work or execution readiness. Only the exact native registration-email, password-reset, magic-link, organization-invitation and anonymous-upgrade profiles support original proof consumption through their typed atomic phases. Other capability/cascade inputs are rejected. Invalid input returns redacted identity.InvalidInputError. Do not mutate inputs concurrently with this call.

func KernelPlanDigest

func KernelPlanDigest(binding identity.CommandBinding, fingerprint [32]byte, plan CommandPlan) ([32]byte, error)

KernelPlanDigest returns a domain-separated SHA-256 digest of the current kernel-only plan, command binding and nonzero authoritative fingerprint. It uses deterministic CBOR and preserves contributor order and every audit field. Digest itself is excluded. This is binding, not authentication or proof that the fingerprint is authoritative: the sole coordinator must resolve retained fingerprint keys and compute it from the typed command. Canonical explicit-self account links use a distinct closed envelope with mandatory counter and native provider declarations in addition to the four kernel/capability participants. This preserves older kernel-plan bytes. Exactly one identity/postgres and one audit/postgres contributor are required; a lifecycle declaration additionally requires exactly one outbox/postgres identity.lifecycle v1 contributor. A capability declaration requires lifecycle plus exactly one capability.one-use v1 contributor. Existing audit-only and lifecycle digest bytes remain unchanged. Digest preparation does not activate that participant: reservation additionally requires the typed contributor; domain execution remains disabled until its remaining phases exist. Feature/one-time contributors without typed inputs are rejected, not silently omitted. Invalid inputs return redacted identity.InvalidInputError. It does no I/O or callbacks. Concurrent calls require immutable caller-owned inputs.

func MagicLinkRegistrationDigest

func MagicLinkRegistrationDigest(s MagicLinkRegistrationIntent) ([32]byte, error)

MagicLinkRegistrationDigest commits the complete kernel-owned field set. It is structural binding, not authentication or a keyed command fingerprint.

func MagicLinkRegistrationFields

func MagicLinkRegistrationFields(s MagicLinkRegistrationIntent) ([]identity.FeatureField, error)

MagicLinkRegistrationFields freezes kernel-owned creation inputs into the native consuming command. It does not normalize, prove possession or authorize registration. Returned byte fields are independently owned.

func ManagedEmailVerificationFields

func ManagedEmailVerificationFields(i ManagedEmailVerificationIntent) ([]identity.FeatureField, error)

ManagedEmailVerificationFields maps bounded initial pending verification to canonical native command fields. These are sensitive metadata, not authority. No normalization, cryptography, IO or callbacks occur; inputs remain immutable.

func OTPEmailChangeFields

OTPEmailChangeFields binds primary replacement to its original committed change request and a distinct independently issued OTP send. The native owner authenticates that original custody; caller metadata is not authority. Only genuine-primary replacement is selected, never generic pending verification or initial-primary establishment. Include fields before fingerprinting and consuming reservation. No IO, normalization or credential work occurs here.

func OTPEmailInitialPrimaryFields

func OTPEmailInitialPrimaryFields(i ManagedEmailVerificationIntent, send identity.CommandID) ([]identity.FeatureField, error)

OTPEmailInitialPrimaryFields explicitly selects first-primary establishment from an original sole-verified/no-primary change policy. Existing replacement fields remain primary-only. This encodes intent, not authority: the registered owner and locked complete partition must prove the original predecessor, zero primaries and exactly one verified old email before comparison or debit. Fingerprinting, protected notice and consuming protocol match replacement.

func OTPEmailVerificationFields

func OTPEmailVerificationFields(i ManagedEmailVerificationIntent, send identity.CommandID) ([]identity.FeatureField, error)

OTPEmailVerificationFields binds the native pending-address transition to one independently issued OTP send command and the canonical email_verification_otp recovery selector. RequestCommandID must select that OTP send, not an older link or attachment request. Include all fields before fingerprinting/reservation. This profile never replaces a primary or issues a session. Mapping proves no code comparison, current authority, reservation or mutation; the enlisted OTP owner and managed-email contributor must establish those in the sole Work. Inputs are borrowed synchronously; returned fields are caller-owned.

func PasskeyCredentialCreationFields

func PasskeyCredentialCreationFields(c identity.CredentialRef, a UserAuthorityAdmission) ([]identity.FeatureField, error)

PasskeyCredentialCreationFields binds an initial passkey-owned reference and all three original user security epochs into the enrolling native command. The returned fields contain no verifier, WebAuthn credential bytes or proof; they grant neither enrollment permission nor authentication. Version must be one, and each authority must be positive. User aggregate version is not an authority epoch. Copies own their scalar values and construction performs no IO.

func PasskeyCredentialRemovalFields

func PasskeyCredentialRemovalFields(c identity.CredentialRef, a UserAuthorityAdmission) ([]identity.FeatureField, error)

PasskeyCredentialRemovalFields binds an existing passkey reference and all three independent user security epochs to the original removal command. Version must be positive and have a representable successor. The fields contain neither protocol bytes nor authentication/recovery permission. Construction owns its scalar values, performs no IO and is concurrency-safe.

func PasskeyRegistrationDigest

func PasskeyRegistrationDigest(s PasskeyRegistrationIntent) ([32]byte, error)

PasskeyRegistrationDigest commits the complete kernel-owned prospective field set under this exact registration profile. It is structural intent, not a keyed command fingerprint, a WebAuthn result or proof of successful creation.

func PasskeyRegistrationFields

func PasskeyRegistrationFields(s PasskeyRegistrationIntent) ([]identity.FeatureField, error)

PasskeyRegistrationFields freezes the complete kernel-owned prospective creation into the original native command. It neither creates an identity nor grants authentication. The exact registration.user field also binds the protocol participant's prospective subject before a durable account exists. Attributes must already satisfy the identity field policy; their bounded commitment is not a substitute for authorization or canonicalization. Returned fields own their values and contain no password or authenticator.

func PasswordHashUpgradeFields

func PasswordHashUpgradeFields(s PasswordHashUpgradeIntent) ([]identity.FeatureField, error)

PasswordHashUpgradeFields returns the complete owned predecessor projection. Include every field unchanged in the original paired signin command before fingerprinting. Returned fields do not alias intent. No IO or callbacks run; this mapping grants no authentication or permission to mutate a credential.

func PasswordRegistrationFields

func PasswordRegistrationFields(s PasswordRegistrationIntent) ([]identity.FeatureField, error)

PasswordRegistrationFields maps every kernel-owned input into the original native command. Include the returned fields unchanged before fingerprinting. Prepared attributes use a domain-separated commitment, not a serialized blob; the coordinator subsequently keys all fields. No verifier belongs here. Structural validation proves neither field permission nor normalization.

func PhoneChangeFields

func PhoneChangeFields(i PhoneChangeIntent) ([]identity.FeatureField, error)

PhoneChangeFields freezes both canonical number/profile bindings, exact predecessors and original send before coordinator fingerprinting. No IO, normalization, OTP comparison or authority admission occurs. The selected native compound transition advances every version exactly once, preserving the existing feature receipt and lifecycle CAS contract.

func PhoneEnrollmentFields

func PhoneEnrollmentFields(i PhoneEnrollmentIntent) ([]identity.FeatureField, error)

PhoneEnrollmentFields freezes complete pending-attachment input before the coordinator fingerprints it. It accepts only a new phone identifier, not email, verification, replacement, primary selection or a caller's verified status. E.164 shape is checked defensively; actual pinned-metadata validity remains the phone owner's responsibility. No IO or normalization occurs.

func PhoneRemovalFields

func PhoneRemovalFields(i PhoneRemovalIntent) ([]identity.FeatureField, error)

PhoneRemovalFields returns all kernel-owned original target/reason fields for immutable command fingerprinting. It normalizes nothing, authenticates nothing and performs no IO. The native phone owner must validate pinned metadata first.

func PhoneVerificationFields

func PhoneVerificationFields(i PhoneVerificationIntent) ([]identity.FeatureField, error)

PhoneVerificationFields freezes complete initial confirmation input before fingerprinting. No IO, normalization, code comparison or authority admission occurs. The returned fields are caller-owned sensitive intent, not proof.

func UsernameRenameFields

func UsernameRenameFields(i UsernameRenameIntent) ([]identity.FeatureField, error)

UsernameRenameFields returns complete kernel-owned typed intent. Preserve these unchanged when fingerprinting. The workflow owner must validate names through its selected policy; structural acceptance grants no reservation or authentication. Display-only edits still bind every original predecessor.

Types

type APIKeyVerificationContributor

type APIKeyVerificationContributor interface {
	FeatureCommitContributor
	ApplyAPIKeyVerification(context.Context, Work, identity.Command) (identity.FeatureReceipt, APIKeyVerificationOutcome, error)
}

APIKeyVerificationContributor owns credential comparison, current authority and an optional strict permission reduction inside the original Work. Only the exact closed API-key verification plan selects this phase. Generic mutation contributors cannot supply its disposition. The returned receipt remains record-free; authentication and permission mutation are independent. CheckFeatureCommit must fence the original credential, current owner/policy and original freshness after required effects, without renewing authority. Implementations follow FeatureExecutionContributor's ownership, cancellation, concurrency, redaction and no-network rules. A denial is a nil-error false authentication result; errors roll back the entire attempt, including Narrow.

type APIKeyVerificationOutcome

type APIKeyVerificationOutcome struct {
	Authenticated      bool
	PermissionsChanged bool
}

APIKeyVerificationOutcome selects the result of an actual native comparison inside the original Work. PermissionsChanged means that Work also persisted the declared key's non-expanding grant and checked version successor. It does not imply successful authentication: denied use of a removed permission can commit the narrowing and its own successful update audit atomically. Unknown keys may select neither authentication nor a permission mutation.

type APIKeyVerificationPlan

type APIKeyVerificationPlan struct {
	KeyVersion uint64
}

APIKeyVerificationPlan declares an original authentication attempt, not a key mutation. KeyVersion is the original known key version whose optional Narrow transition may advance exactly once; zero is required for an unknown key. The exact native owner must compare the secret and recheck current authority inside Work. This value conveys neither authentication nor permission to narrow. Ordinary verification never advances a key/root/configuration epoch.

type AccountLinkContributor

type AccountLinkContributor interface {
	RecoveryContributor
	PrepareAccountLink(context.Context, identity.Command) (identity.Command, CommandCounterPlan, CapabilityPlan, error)
	ValidateAccountLink(identity.Command, CommandPlan) error
	CheckAccountLink(context.Context, AccountLinkWork) error
	PersistAccountLink(context.Context, AccountLinkWork) error
	FinalizeAccountLink(context.Context, AccountLinkWork) error
}

AccountLinkContributor is the trusted native provider/session policy owner for explicit self-linking. Preparation performs bounded primary reads only; provider exchange belongs to acknowledged native preparation outside SQL. Validation reconstructs the exact retained provider, session, policy and risk input without I/O. Check repeats current admission initially and before final consumption. Persist and Finalize write only this owner's provisional effects in the kernel's transaction. No phase may open or close a transaction, run network callbacks, retain handles, refresh proof expiry or substitute identity link rows. Recovery must preserve uncertainty about external exchange effects.

type AccountLinkPreparationContributor

type AccountLinkPreparationContributor interface {
	AccountLinkContributor
	ValidateAccountLinkPreparation(identity.Command, CommandPlan) error
	AdmitAccountLinkPreparation(context.Context, AccountLinkPreparationWork, identity.Command) error
	GenerateAccountLinkPreparation(context.Context, identity.Command, uint64) ([]byte, error)
	RestoreAccountLinkPreparation(context.Context, identity.Command, uint64, []byte) (identity.Command, CommandPlan, CapabilityIssuancePlan, error)
}

AccountLinkPreparationContributor extends the exact native provider/session owner for original root OAuth callback intent, not a feature command. Validation is bounded and I/O-free. Admission borrows primary read/authority checks only: no mutation, external callbacks, decryption, exchange or signing. Generate runs outside SQL only after the coordinator acknowledges durable original-state reservation and its generation marker. It returns bounded authenticated ciphertext, never plaintext credentials. Restore authenticates the unchanged original intent, original output generation and submitted bearer without SQL, network, generation or expiry renewal. It returns the exact final signed command, consuming plan and one matching issuance declaration. The existing issuer must persist that grant during attachment; issuance is preparation evidence, never proof that the protected account link committed. Shared owners support concurrent independent calls with invocation-local state.

type AccountLinkPreparationMigrationSource

type AccountLinkPreparationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

AccountLinkPreparationMigrationSource adds the closed original OAuth account-link preparation profile to the existing command journal. Base must include CounterPreparationMigrationSource; Version follows installed history. Profile 5 retains original declaration, generation and encrypted exchange output. It does not create a second workflow or permit another exchange after an uncertain start. Install before selecting the prepared account-link owner. Older profiles and migration checksums are unchanged. There is no down SQL.

func (AccountLinkPreparationMigrationSource) Load

Load returns independently owned forward history without database I/O. Invalid configuration and cancellation follow PreparationMigrationSource.

type AccountLinkPreparationWork

type AccountLinkPreparationWork struct {
	// contains filtered or unexported fields
}

AccountLinkPreparationWork borrows primary admission reads from the sole coordinator transaction before its durable start. There is no constructor, Exec, raw transaction, commit, generation or provider-call authority. Copies share serial invocation lifetime and failure state; returned handles deny. Query is trusted bounded read/locking SQL, not an untrusted SQL sandbox. Close every cursor before returning and propagate every denied authority.

func (AccountLinkPreparationWork) Command

Command returns original metadata only to the exact invoked owner. It creates neither a provider subject nor signed proof and exposes no callback secret.

func (AccountLinkPreparationWork) DatabaseTime

func (h AccountLinkPreparationWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime reads primary time without renewing original admission facts.

func (AccountLinkPreparationWork) Format

Format hides original callback, session and transaction correlations.

func (AccountLinkPreparationWork) MarshalJSON

func (AccountLinkPreparationWork) MarshalJSON() ([]byte, error)

MarshalJSON refuses serialization of borrowed admission authority.

func (AccountLinkPreparationWork) MarshalText

func (AccountLinkPreparationWork) MarshalText() ([]byte, error)

MarshalText refuses serialization of borrowed admission authority.

func (AccountLinkPreparationWork) Query

func (h AccountLinkPreparationWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query borrows bounded primary read/locking SQL for this admission only.

func (AccountLinkPreparationWork) RequireActiveCredential

RequireActiveCredential reuses the kernel's current credential/epoch fence.

func (AccountLinkPreparationWork) RequireActiveDirectoryAuthority

RequireActiveDirectoryAuthority reuses the kernel's exact directory fence.

func (AccountLinkPreparationWork) RequireActiveUserAuthorization

RequireActiveUserAuthorization reuses the original user-policy epoch fence.

type AccountLinkUnitOfWork

type AccountLinkUnitOfWork struct {
	// contains filtered or unexported fields
}

AccountLinkUnitOfWork is the sealed explicit-self-link implementation of the root durable seam. Use behind AccountLinkService with the actual configured native OAuth participant; it is not a provider-verification or HTTP endpoint. It owns no pool, goroutine, second ledger or transaction engine. Concurrent service calls use independent bounded Work; each Work remains serial-use.

func NewAccountLinkUnitOfWork

func NewAccountLinkUnitOfWork(c *Coordinator, r *Repository, config AccountLinkUnitOfWorkConfig) (*AccountLinkUnitOfWork, error)

NewAccountLinkUnitOfWork validates complete typed native phase composition, not names alone. It does no I/O or callbacks. Pools remain caller-owned. Missing recovery/current/finalization phases fail before any reservation.

func (*AccountLinkUnitOfWork) Execute

func (o *AccountLinkUnitOfWork) Execute(ctx context.Context, original identity.Command) (result identity.CommandResult, err error)

Execute completes already-authorized root link intent with the exact native current provider/session/risk owner. Every domain, proof, provider, audit and lifecycle effect commits together. Exact replay returns the original receipt; failures roll back and use the same coordinator's conservative recovery rules. Native preparation may enrich counters but cannot change the signed intent.

func (*AccountLinkUnitOfWork) ExecutePrepared

func (o *AccountLinkUnitOfWork) ExecutePrepared(ctx context.Context, original identity.Command, declaration CommandPlan) (result identity.CommandResult, err error)

ExecutePrepared runs original explicit-self OAuth link input through the existing command journal. The native owner supplies the exact declaration; consumers must use its supported workflow, not author one themselves. Original state reservation, counters and the start marker commit before Generate may decrypt PKCE, exchange or sign. An unacknowledged start never permits generation. Retained ciphertext resumes under its original generation; neither retry nor takeover replaces original intent or re-exchanges a code.

Attachment persists and reserves the one matching final signed grant through the actual registered issuer/consumer in one transaction. That issuance is a prerequisite, not evidence of account commitment. The final six-owner plan consumes both original state and final grant with account/audit/lifecycle effects. Final current checks and conservative recovery remain mandatory. Matching terminal replay returns its original receipt without restoration. Earlier deadlines win; uncertain durable outcomes reveal no partial result.

func (AccountLinkUnitOfWork) Format

func (AccountLinkUnitOfWork) Format(s fmt.State, _ rune)

Format omits runtime dependencies and retained security configuration.

func (AccountLinkUnitOfWork) MarshalJSON

func (AccountLinkUnitOfWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of runtime composition.

func (*AccountLinkUnitOfWork) Recover

Recover reads the exact original scoped primary receipt without re-exchange, new signing, mutation replay or session issuance. Expired pending work needs unanimous native negative evidence; uncertainty remains pending. Current application authorization/redaction still belongs to AccountLinkService.

type AccountLinkUnitOfWorkConfig

type AccountLinkUnitOfWorkConfig struct{ RetentionPolicyVersion uint64 }

AccountLinkUnitOfWorkConfig selects the positive audit retention-policy revision. Zero is invalid; configuration is copied and immutable after setup.

type AccountLinkWork

type AccountLinkWork struct {
	// contains filtered or unexported fields
}

AccountLinkWork borrows the original transaction only during the selected native invocation. Copies share serial lifetime and error state; zero, foreign and retained handles deny. Queries are bounded trusted SQL, not a caller SQL sandbox. Only persistence/finalization permits Exec. Close every cursor before returning. This handle grants no independent commit authority.

func (AccountLinkWork) Command

Command returns original signed intent to the exact native participant. The boolean identifies the terminal check/finalization, never renewed freshness.

func (AccountLinkWork) CredentialAuthorityVersion

func (h AccountLinkWork) CredentialAuthorityVersion(p AccountLinkContributor) (uint64, error)

CredentialAuthorityVersion returns the original epoch during initial admission and only this Work's persisted successor during terminal checks. It cannot adopt a newer external epoch or renew original session freshness.

func (AccountLinkWork) DatabaseTime

func (h AccountLinkWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime reads primary time without renewing the original proof/session.

func (AccountLinkWork) Exec

func (h AccountLinkWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec borrows provisional writes only during persistence or finalization.

func (AccountLinkWork) Format

func (AccountLinkWork) Format(s fmt.State, _ rune)

Format hides command, provider, proof and transactional correlation.

func (AccountLinkWork) MarshalJSON

func (AccountLinkWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects export of invocation authority.

func (AccountLinkWork) MarshalText

func (AccountLinkWork) MarshalText() ([]byte, error)

MarshalText rejects implicit export of invocation authority.

func (AccountLinkWork) Preparation

Preparation lends the exact original typed callback/session input, an owned copy of retained authenticated ciphertext and its original generation only to the currently invoked native preparation owner. It permits local restoration and current checks, never exchange, generation or freshness renewal. Callback custody retains its shared bounded lifetime; do not destroy it before the enclosing operation returns. No SQL, callbacks or raw transaction escape run. Ordinary links, foreign owners, zero and returned invocations deny.

func (AccountLinkWork) Query

func (h AccountLinkWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query borrows bounded primary reads. Check phases must use read/locking SQL, not mutations; the native implementation is a trusted owner, not a sandbox.

func (AccountLinkWork) RequireActiveCredential

func (h AccountLinkWork) RequireActiveCredential(ctx context.Context, p AccountLinkContributor, expected CredentialAdmission) (time.Time, error)

RequireActiveCredential checks and locks the exact original credential and independent user epochs using the existing kernel authority implementation.

func (AccountLinkWork) RequireActiveDirectoryAuthority

func (h AccountLinkWork) RequireActiveDirectoryAuthority(ctx context.Context, p AccountLinkContributor, expected DirectoryAuthorityAdmission) error

RequireActiveDirectoryAuthority locks and checks exact global/tenant epochs.

func (AccountLinkWork) RequireActiveUserAuthorization

func (h AccountLinkWork) RequireActiveUserAuthorization(ctx context.Context, p AccountLinkContributor, expected UserAuthorizationAdmission) error

RequireActiveUserAuthorization checks original user-authorization authority.

type AccountMigrationSource

type AccountMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

AccountMigrationSource appends identity-owned provider-link storage to Base, which must already include CredentialMigrationSource. Version must exceed all Base versions. Load performs no I/O and preserves installed migration bytes; the caller applies this forward-only source with the migrations Runner. Neither installing it nor inserting metadata establishes provider proof.

func (AccountMigrationSource) Load

Load returns independently owned history. Missing/invalid composition and cancellation fail without partial history. Existing users retain their epochs, credentials and status; no account or authentication authority is synthesized.

type AdmissionPreparationMigrationSource

type AdmissionPreparationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

AdmissionPreparationMigrationSource appends forward support for the immutable externally admitted preparation profile. Base must include PreparationMigrationSource; Version must follow all selected history. Existing rows, preparation SQL/checksums and profile 1 remain unchanged. Old readers reject profile 2 rather than silently bypass admission. Install before enabling an externally admitted owner; no destructive down SQL exists.

func (AdmissionPreparationMigrationSource) Load

Load returns independently owned forward history without database IO. Invalid configuration and cancellation follow PreparationMigrationSource.

type AnonymousAuthorityRecord

type AnonymousAuthorityRecord struct {
	User                                                                         identity.User
	Placeholder                                                                  identity.Identifier
	UserAuthorityVersion, IdentifierAuthorityVersion, CredentialAuthorityVersion uint64
}

AnonymousAuthorityRecord is one primary kernel snapshot of an actually created anonymous user and its reserved placeholder. CredentialAuthorityVersion is the user's aggregate epoch, not a fabricated credential reference. Status and versions are preserved, never defaulted or restored. This structural record carries no authentication, anonymous lifecycle/expiry or renewable validity.

func (AnonymousAuthorityRecord) Format

func (AnonymousAuthorityRecord) Format(s fmt.State, _ rune)

func (AnonymousAuthorityRecord) MarshalJSON

func (AnonymousAuthorityRecord) MarshalJSON() ([]byte, error)

func (AnonymousAuthorityRecord) MarshalText

func (AnonymousAuthorityRecord) MarshalText() ([]byte, error)

func (AnonymousAuthorityRecord) Validate

func (r AnonymousAuthorityRecord) Validate() error

Validate checks structure only. A blocked user's structurally valid record remains blocked; consumers must independently require active status, compare all original epochs and check the anonymous lifecycle, session and policy.

type AnonymousCreationDomain

type AnonymousCreationDomain struct {
	// contains filtered or unexported fields
}

AnonymousCreationDomain borrows the exact enlisted kernel repository. It opens no transaction and owns no resource lifetime. Immutable composition is concurrent-safe; Work and input mutation remain serial. Applications use the anonymous service, not this trusted same-Work adapter seam. Zero denies.

func NewAnonymousCreationDomain

func NewAnonymousCreationDomain(repository *Repository) (*AnonymousCreationDomain, error)

NewAnonymousCreationDomain validates explicit composition without IO. Install AnonymousIdentityMigrationSource before use. Construction authenticates no browser, risk decision or credentials and grants no issuance authority.

func (*AnonymousCreationDomain) Apply

Apply creates the user/attributes and reserved placeholder only inside the exact anonymous participant's original command invocation. Foreign, changed, duplicate or out-of-invocation calls poison Work. The repository owns all kernel SQL. Returned User is provisional; the anonymous adapter must persist its own lifecycle and session effects, then required audit/outbox and the existing coordinator commit establish durability. No bearer is returned.

func (AnonymousCreationDomain) Format

func (AnonymousCreationDomain) Format(s fmt.State, _ rune)

func (AnonymousCreationDomain) MarshalJSON

func (AnonymousCreationDomain) MarshalJSON() ([]byte, error)

type AnonymousCreationIntent

type AnonymousCreationIntent struct {
	Creation    identity.CreateUserCommand
	Placeholder identity.Identifier
}

AnonymousCreationIntent freezes only the kernel-owned part of anonymous signin: an active initial user, admitted attributes and its non-contact placeholder. The user is a generated opaque subject, not a caller-selected permanent identity. No credential or session authority is represented here. Anonymous lifecycle, expiry and risk remain the native feature's obligations.

func (AnonymousCreationIntent) Format

func (AnonymousCreationIntent) Format(s fmt.State, _ rune)

func (AnonymousCreationIntent) MarshalJSON

func (AnonymousCreationIntent) MarshalJSON() ([]byte, error)

type AnonymousDisposalAction

type AnonymousDisposalAction string

AnonymousDisposalAction selects kernel-owned disposal, not authorization. Delete retains an irreversible identity tombstone and minimal non-contact creation linkage, but removes attributes/profile. Anonymize does the same erasure with a distinct terminal status. Retain preserves those payloads and terminalizes authentication only. Unknown/zero values deny.

const (
	AnonymousDisposeDelete    AnonymousDisposalAction = "delete"
	AnonymousDisposeAnonymize AnonymousDisposalAction = "anonymize"
	AnonymousDisposeRetain    AnonymousDisposalAction = "retain"
)

type AnonymousDisposalDomain

type AnonymousDisposalDomain struct {
	// contains filtered or unexported fields
}

AnonymousDisposalDomain borrows the exact enlisted kernel repository. It owns all ordinary user/attribute SQL, no pool lifetime, transaction or callback. Immutable composition is concurrent-safe; borrowed Work remains serial-use.

func NewAnonymousDisposalDomain

func NewAnonymousDisposalDomain(r *Repository) (*AnonymousDisposalDomain, error)

NewAnonymousDisposalDomain checks explicit owner composition without IO. AnonymousDisposalMigrationSource and the complete creation/status histories must already be installed; construction performs no automatic migration.

func (*AnonymousDisposalDomain) Apply

Apply fences and disposes only the exact kernel-created anonymous user in the current registered delete invocation. Additional contacts/credentials, changed authority or legal hold deny before erasure. Errors poison Work even when a caller ignores them. Success remains provisional until every owner commits.

func (*AnonymousDisposalDomain) ApplyExpired

ApplyExpired disposes the exact guest targeted by a trusted service command. It grants no maintenance authorization or expiry evidence: the native owner must separately fence its original database-time-expired lifecycle, current service policy and retention decision, and revoke all guest session families in this same Work. It accepts neither browser deletion nor upgrade authority.

func (*AnonymousDisposalDomain) ApplyUpgrade

ApplyUpgrade disposes only the guest in RecordID while UserID/ActorID remain the distinct permanent target. It requires the exact typed upgrade invocation and provisional one-use consumption. It never changes the permanent user or proves its credentials; the native owner must fence target authority and enlist the session transition in the same Work before commitment.

func (*AnonymousDisposalDomain) Check

Check repeats the exact applied terminal kernel state and original legal hold during the coordinator's final read-only fence. It neither erases payload nor renews an admission deadline. The workflow separately fences its original session, anonymous transition, risk and retention decision.

func (*AnonymousDisposalDomain) CheckExpired

CheckExpired repeats the exact terminal kernel state and original hold in the service-expiry commit fence. It does not renew the service's original validity window or replace native lifecycle, retention and complete-session checks.

func (*AnonymousDisposalDomain) CheckUpgrade

CheckUpgrade repeats the guest's terminal state and original legal hold in the exact upgrade commit fence, without renewing authority. Target and session owners must independently check their own current state in that same fence.

func (AnonymousDisposalDomain) Format

func (AnonymousDisposalDomain) Format(s fmt.State, _ rune)

func (AnonymousDisposalDomain) MarshalJSON

func (AnonymousDisposalDomain) MarshalJSON() ([]byte, error)

func (*AnonymousDisposalDomain) RequireUpgradePreparation

RequireUpgradePreparation fences the guest's complete original kernel and retention snapshot in the issuance-only command without disposing either identity. The native owner separately authenticates both cookies and fences the permanent target. Repeated checks retain the same snapshot and Work locks; no proof is consumed, lifetime renewed or new transaction created.

type AnonymousDisposalIntent

type AnonymousDisposalIntent struct {
	Snapshot               AnonymousDisposalSnapshot
	Action                 AnonymousDisposalAction
	RetentionPolicyVersion uint64
}

AnonymousDisposalIntent freezes kernel disposal and retention-policy identity before command fingerprinting. The workflow must obtain its bounded retention decision outside SQL, then fence this original snapshot inside the same Work as anonymous state, all anonymous-session revocation, audit and outbox.

func (AnonymousDisposalIntent) Format

func (AnonymousDisposalIntent) Format(s fmt.State, _ rune)

func (AnonymousDisposalIntent) MarshalJSON

func (AnonymousDisposalIntent) MarshalJSON() ([]byte, error)

type AnonymousDisposalMigrationSource

type AnonymousDisposalMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

AnonymousDisposalMigrationSource appends retained, payload-free kernel disposal evidence after anonymous creation and legal-hold histories. Existing populated predecessor SQL is returned unchanged; Version follows every installed successor. This enables no workflow and offers no destructive downgrade.

func (AnonymousDisposalMigrationSource) Load

Load validates the complete selected history without IO. The existing runner owns installation; missing prerequisites, invalid order and cancellation deny.

type AnonymousDisposalSnapshot

type AnonymousDisposalSnapshot struct {
	Authority        AnonymousAuthorityRecord
	LegalHold        bool
	LegalHoldVersion uint64
}

AnonymousDisposalSnapshot preserves the primary kernel's original user, placeholder, three independent authority epochs and legal-hold generation. It grants no session possession, risk or retention permission. A protected disposal compares this whole snapshot again under the existing Work lock.

func (AnonymousDisposalSnapshot) Format

func (AnonymousDisposalSnapshot) Format(s fmt.State, _ rune)

func (AnonymousDisposalSnapshot) MarshalJSON

func (AnonymousDisposalSnapshot) MarshalJSON() ([]byte, error)

type AnonymousExpiryDisposalMigrationSource

type AnonymousExpiryDisposalMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

AnonymousExpiryDisposalMigrationSource appends the exact service-expiry purpose after the selected kernel disposal history. Install optional upgrade purpose extensions first: this suffix preserves their admission but does not enable an upgrade workflow. Existing SQL and populated evidence are unchanged. No destructive downgrade or automatic migration is provided.

func (AnonymousExpiryDisposalMigrationSource) Load

Load validates the selected increasing history without IO. The existing migration runner owns installation. Missing, duplicated or out-of-order disposal histories and cancellation fail closed.

type AnonymousIdentityMigrationSource

type AnonymousIdentityMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

AnonymousIdentityMigrationSource selects the kernel-owned non-contact placeholder namespace. Base must include identifier retirement and comparison normalization histories, plus every installed successor; Version follows all of them. Existing identifiers and immutable predecessor SQL are unchanged. This forward migration enables no anonymous lifecycle, session or endpoint; their owning adapters and explicit composition remain separately required.

func (AnonymousIdentityMigrationSource) Load

Load returns independently owned forward-only history without IO. Missing predecessors, invalid ordering, cancellation and zero configuration fail closed. The existing migrations runner owns installation and recovery.

type AnonymousUpgradeContributor

type AnonymousUpgradeContributor interface {
	FeatureCommitContributor
	ValidateAnonymousUpgrade(identity.Command, CapabilityPlan) error
}

AnonymousUpgradeContributor is the closed native upgrade owner. Its pure bounded validation must bind the original permanent-target credential, guest possession, typed merge decisions and one-use declaration to the exact command. ApplyFeature must fence both identities and current policy, dispose only the guest through the kernel owner, persist the anonymous transition and replace its sessions through the session owner, all in the sole Work. Commit checks repeat current authority and earliest original expiry without renewal. The capability participant, not scalar metadata, verifies and consumes the proof.

type AnonymousUpgradeDisposalMigrationSource

type AnonymousUpgradeDisposalMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

AnonymousUpgradeDisposalMigrationSource appends the explicit upgrade purpose to existing kernel disposal evidence. All populated predecessor SQL and unique guest tombstones remain unchanged. Select this forward-only suffix before the upgrade workflow; the original deletion profile needs no new migration.

func (AnonymousUpgradeDisposalMigrationSource) Load

Load validates the selected predecessor and increasing suffix without IO.

type AnonymousUpgradePreparationContributor

type AnonymousUpgradePreparationContributor interface {
	FeaturePreparationContributor
	FeatureCommitContributor
	ValidateAnonymousUpgradePreparation(identity.Command, *CapabilityIssuancePlan) error
}

AnonymousUpgradePreparationContributor owns the closed, internal issuance phase preceding an anonymous upgrade. It authenticates both original sessions, target and guest scope, merge decisions and unchanged remember policy before generation, Apply and final commit. Preparation cannot consume the target's action proof or mutate either identity/session. Validation is pure and bounded; a nil issuance plan is the original pre-generation declaration. The capability owner still signs, stages and durably persists the one-use grant. Implementations retain original credentials only in the existing encrypted preparation, never in a new bearer store, and never renew their earliest authoritative deadline.

type AuditContributor

type AuditContributor interface {
	Contributor
	PersistAudits(context.Context, Work) error
}

AuditContributor is the open, versioned durable audit phase implemented by audit/postgres. Only the sole Coordinator invokes PersistAudits, after every required event is staged, through the same generation-bound Work as the protected mutation. Implementations must write canonical records and their command/index binding atomically, treating exact replay as idempotent and changed bytes or event-ID reuse as integrity failure. They must not retain Work, close/begin transactions, perform network I/O or invoke caller hooks. A nil error means staging succeeded, not that the Coordinator committed.

type AuditPlan

type AuditPlan struct {
	EventType              string
	SchemaVersion          uint32
	EventIndex             uint16
	BindingDigest          [32]byte
	RetentionPolicyVersion uint64
	RequiredRecordCount    uint16
	MaxRecordBytes         uint32
	MaxAggregateBytes      uint32
	Required               bool
	// RetentionClass is required by native v2 feature plans: standard or
	// protected, selected by the owning native policy. Kernel/v1 plans leave
	// it empty and preserve their established action-to-retention mapping.
	RetentionClass string
}

AuditPlan declares one required security event slot before SQL execution. Values are copied by the coordinator, never changed in flight. SchemaVersion is the audit canonical schema (currently 1), not the command schema. Each index requires exactly one record; indices increase strictly, at most 64. Byte bounds may lower but never exceed the 16 KiB identity security profile. RetentionPolicyVersion is the exact durable policy selected at admission; staging does not read or mutate retention policy. The closed API-key verification profile declares its maximum slots; the coordinator selects the update slot only for an actual strict permission reduction, and rollback selects authentication alone. Other profiles require every declared slot. Zero and Required=false are invalid. This declaration alone grants no persistence authority.

type AuthenticatedFeatureContributor

type AuthenticatedFeatureContributor interface {
	FeatureExecutionContributor
	ValidateAuthenticatedFeature(identity.Command, authentication.AuthenticatedProofSpec) error
	CheckAuthenticatedFeature(context.Context, Work, identity.Command, authentication.AuthenticatedProofSpec, bool) error
}

AuthenticatedFeatureContributor owns the exhaustive native mapping and the current eligibility of a final-authentication operation. Validate is pure, bounded and compares every original proof/credential field with native command intent. Check runs under the original Work before apply and again before terminalization (final=true); it must lock/check every applicable original authority, preserve freshness, and check original native session lifetime. It must not mutate state, mint tokens, consume proof, retain Work, perform network IO or close transactions. Errors/panics/unfinished rows poison Work. Only the exact registered feature owner is invoked. Current support is the authenticated session-issue profile; anonymous issuance is a separate profile.

type CapabilityApplyWork

type CapabilityApplyWork struct {
	// contains filtered or unexported fields
}

CapabilityApplyWork is an invocation-only capability to consume an original reserved token provisionally. Zero, foreign, stale, wrong-phase and retained handles fail. Copies share lifetime; serial use only. All rows must close before return. There is no constructor, raw driver or transaction closure.

func (CapabilityApplyWork) Binding

Binding returns the frozen input and current generation to the exact owner.

func (CapabilityApplyWork) DatabaseTime

func (w CapabilityApplyWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary time without renewing original expiry or Work.

func (CapabilityApplyWork) Exec

func (w CapabilityApplyWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec executes one bounded trusted provisional statement, never closure.

func (CapabilityApplyWork) Format

func (CapabilityApplyWork) Format(s fmt.State, _ rune)

Format redacts retained command, proof and transaction metadata.

func (CapabilityApplyWork) MarshalJSON

func (CapabilityApplyWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of invocation authority.

func (CapabilityApplyWork) MarshalText

func (CapabilityApplyWork) MarshalText() ([]byte, error)

MarshalText rejects implicit text and map-key disclosure.

func (CapabilityApplyWork) Query

func (w CapabilityApplyWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns bounded invocation-owned rows, which must be closed.

type CapabilityExecutionContributor

type CapabilityExecutionContributor interface {
	CapabilityReleaseContributor
	ApplyCapability(context.Context, CapabilityApplyWork) error
	FinalizeCapability(context.Context, CapabilityFinalizeWork) error
}

CapabilityExecutionContributor supplies provisional consumption and terminal finalization in the sole coordinator's domain transaction. Apply must lock the exact reserved input, check exclusive primary expiry and increment only below its signed maximum. Finalize must recheck expiry and CAS that same current command/fingerprint/generation to finalized. Neither phase may issue, release, renew, retry, retain handles, invoke network callbacks or close a transaction. Success is participant evidence, not a committed command outcome. This seam alone does not activate Begin: the native domain owner must also be complete.

type CapabilityFinalizeWork

type CapabilityFinalizeWork struct {
	// contains filtered or unexported fields
}

CapabilityFinalizeWork grants invocation-only terminal mutation in the same domain transaction. It is distinct from apply and noncommit release authority. Copies expire on callback return, including panic; use serially, close rows, and never retain the handle. Finalization remains provisional until commit.

func (CapabilityFinalizeWork) Binding

Binding returns exact original current-generation custody to its owner.

func (CapabilityFinalizeWork) DatabaseTime

func (w CapabilityFinalizeWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary time without renewing original expiry or Work.

func (CapabilityFinalizeWork) Exec

func (w CapabilityFinalizeWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec executes one bounded trusted terminal statement, never closure.

func (CapabilityFinalizeWork) Format

func (CapabilityFinalizeWork) Format(s fmt.State, _ rune)

Format redacts retained command, proof and transaction metadata.

func (CapabilityFinalizeWork) MarshalJSON

func (CapabilityFinalizeWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of terminal authority.

func (CapabilityFinalizeWork) MarshalText

func (CapabilityFinalizeWork) MarshalText() ([]byte, error)

MarshalText rejects implicit text and map-key disclosure.

func (CapabilityFinalizeWork) Query

func (w CapabilityFinalizeWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns bounded invocation-owned rows, which must be closed.

type CapabilityIssuanceBinding

type CapabilityIssuanceBinding struct {
	Command                        identity.CommandBinding
	Plan                           CapabilityIssuancePlan
	Fingerprint                    [32]byte
	Generation, PreviousGeneration uint64
}

CapabilityIssuanceBinding is original-command metadata, never a proof of authorization or committed outcome. PreviousGeneration is zero in persistence; recovery supplies the original previous generation and the new fenced owner. Plan is an owned copy. Neither generation changes the signed credential expiry.

func (CapabilityIssuanceBinding) Format

func (CapabilityIssuanceBinding) Format(s fmt.State, _ rune)

Format hides retained correlation and signed-envelope metadata.

func (CapabilityIssuanceBinding) MarshalJSON

func (CapabilityIssuanceBinding) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of retained issuance bindings.

type CapabilityIssuanceContributor

type CapabilityIssuanceContributor interface {
	RecoveryContributor
	ValidateCapabilityIssuance(identity.CommandBinding, CapabilityIssuancePlan) error
	PersistCapabilityIssuance(context.Context, CapabilityIssuanceWork) error
}

CapabilityIssuanceContributor owns capability.issuance v1 persistence and recovery, not the originating mutation or its transaction. Validation is bounded and pure. Persistence must match the staged authenticated Grants to their exact original envelope fingerprints and independently keyed replay digests before inserting absent issued state. It must retain original command, fingerprint and generation separately from subsequent consumption binding; mismatched or terminal records must never be replaced/reactivated. No bearer, signer, network operation, caller hook or private transaction belongs here. Methods support concurrent independent commands; phase handles are serial-use.

type CapabilityIssuancePlan

type CapabilityIssuancePlan struct {
	Contributor ContributorDescriptor
	Grants      []CapabilityPlan
	// RegistrationUserID selects the frozen newly created user of native
	// anonymous password signup, not a replacement command subject. Empty
	// preserves existing command-user issuance. It grants no authority alone.
	RegistrationUserID identity.UserID
	// ResetRecipientUserID selects only the existing recipient independently
	// fenced by native anonymous reset-request execution. It is mutually
	// exclusive with RegistrationUserID and permits one reset-complete grant.
	// Metadata alone grants no selection, factor or issuance authority.
	ResetRecipientUserID identity.UserID
	// MagicLinkRecipientUserID selects an existing verified-email recipient only
	// under the anonymous magic-link request profile. It is mutually exclusive
	// with both password targets. Staging requires the same invocation's primary
	// recipient fence; this metadata grants neither authentication nor issuance.
	MagicLinkRecipientUserID identity.UserID
	// MFAContinuationUserID selects only the subject of the closed anonymous
	// magic-link challenge profile, after provisional primary consumption in
	// the same native Apply invocation. It cannot be combined with other targets
	// and permits one identity.mfa.complete grant, never session authentication.
	MFAContinuationUserID identity.UserID
}

CapabilityIssuancePlan declares 1..16 original-command one-use issuance effects. Grants contain only immutable signed-envelope/replay metadata, not bearer bytes or authority. Their purposes select future protected operations, not the originating command operation. The exact capability.issuance v1 owner must follow the base participants and precede optional delivery. Nil preserves historical plan bytes. The owner must authenticate each staged Grant against its original envelope fingerprint and independently keyed replay digest.

type CapabilityIssuanceWork

type CapabilityIssuanceWork struct {
	// contains filtered or unexported fields
}

CapabilityIssuanceWork is granted only during the exact enlisted owner's original-command persistence invocation. There is no constructor, general Work escape hatch or transaction closure. Aliases expire when the invocation returns, including panic. Close every row before return; existing Work bounds and earlier deadlines apply. A successful insert remains provisional.

func (CapabilityIssuanceWork) Binding

Binding supplies an owned snapshot only to the currently invoked exact owner.

func (CapabilityIssuanceWork) DatabaseTime

func (w CapabilityIssuanceWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime reads primary UTC without extending the lease or credential.

func (CapabilityIssuanceWork) Exec

func (w CapabilityIssuanceWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec executes bounded participant SQL, never transaction closure.

func (CapabilityIssuanceWork) Format

func (CapabilityIssuanceWork) Format(s fmt.State, _ rune)

Format hides invocation custody and transaction state.

func (CapabilityIssuanceWork) Grants

Grants returns immutable authenticated authority only during the owner phase. Payload accessors remain defensive copies. These grants carry no bearer bytes and do not prove current authorization or committed issuance. The owner must verify the original-envelope/replay bindings; metadata equality alone is not sufficient. Returning the slice conveys no SQL or future invocation authority.

func (CapabilityIssuanceWork) MarshalJSON

func (CapabilityIssuanceWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of phase authority.

func (CapabilityIssuanceWork) Query

func (w CapabilityIssuanceWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns invocation-owned bounded rows; close them before return.

type CapabilityPlan

type CapabilityPlan struct {
	CapabilityID     string
	Purpose          capability.Purpose
	ReplayDigest     [32]byte
	ReplayKeyVersion uint32
	ProofFingerprint [32]byte
	ExpiresAt        time.Time
	MaxUses          uint32
}

CapabilityPlan freezes one signed, single-use capability's participant input. Purpose must match the command operation exactly. CapabilityID, ExpiresAt and MaxUses are the signed consumption identity; MaxUses must be one. ExpiresAt is a positive whole-second UTC instant within PostgreSQL years 1..9999. ReplayDigest is the participant's independently keyed, domain-separated replay lookup, not Reference.Digest or raw bearer bytes; ReplayKeyVersion selects its retained key. ProofFingerprint binds the validated immutable proof envelope. Digests and key version must be nonzero. The enclosing command fingerprint separately binds target identities and expected authority versions.

This is declaration metadata, never cryptographic validation, freshness or transaction authority. The current Coordinator can reserve identifier intent through the typed contributor, but cannot Begin domain execution until the remaining participant phases exist. Do not mutate caller-owned inputs concurrently with digest preparation. Diagnostics are redacted and serialization is rejected; historical plans use the private canonical codec.

func (CapabilityPlan) Format

func (CapabilityPlan) Format(s fmt.State, _ rune)

Format hides retained proof and replay metadata for every formatting verb.

func (CapabilityPlan) MarshalJSON

func (CapabilityPlan) MarshalJSON() ([]byte, error)

MarshalJSON prevents accidental export of retained proof metadata.

type CapabilityReleaseContributor

type CapabilityReleaseContributor interface {
	CapabilityReservationContributor
	RecoveryContributor
	ReleaseCapability(context.Context, CapabilityReleaseWork) error
}

CapabilityReleaseContributor supplies authoritative status and terminal non-commit release for capability.one-use v1. Only Coordinator invokes these phases. Release must CAS the exact frozen reserved command, fingerprint and PreviousGeneration to terminal released (or expired after primary expiry), recording Generation. Recovery advances exactly one generation; proven live-owner rollback preserves it. It must never issue, consume or reactivate a capability. The coordinator grants release authority only after unanimous recovery noncommit evidence, or its own successful rollback and live-owner recheck, under journal and tenant exclusions. Release, failure audit and aborted receipt share one transaction; any failure rolls them back. Reservation callback restrictions, concurrency and resource limits also apply.

type CapabilityReleaseWork

type CapabilityReleaseWork struct {
	// contains filtered or unexported fields
}

CapabilityReleaseWork is an invocation-bound terminal-release capability. There is no constructor or transaction closure. Copies expire on callback return, including panic. Serial use only; close all rows before returning. It is never granted on lease/expiry alone or unresolved participant evidence.

func (CapabilityReleaseWork) Binding

Binding returns the exact frozen input and ownership generations, after checking the registered contributor's identity and invocation lifetime.

func (CapabilityReleaseWork) DatabaseTime

func (w CapabilityReleaseWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime reads primary UTC without extending the original lease.

func (CapabilityReleaseWork) Exec

func (w CapabilityReleaseWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec performs one bounded trusted participant statement, never closure.

func (CapabilityReleaseWork) Format

func (CapabilityReleaseWork) Format(s fmt.State, _ rune)

Format redacts transaction and retained binding metadata.

func (CapabilityReleaseWork) MarshalJSON

func (CapabilityReleaseWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of terminal-release authority.

func (CapabilityReleaseWork) Query

func (w CapabilityReleaseWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns invocation-owned bounded rows; close them before returning.

type CapabilityReservationBinding

type CapabilityReservationBinding struct {
	Command                        identity.CommandBinding
	Plan                           CapabilityPlan
	Fingerprint                    [32]byte
	Generation, PreviousGeneration uint64
}

CapabilityReservationBinding is an owned scalar snapshot of one invocation. Fingerprint is the authoritative retained-key command fingerprint, not a caller replacement. Generation is positive. PreviousGeneration is zero only for Reserve; Rebind requires its exact positive predecessor. Plan is the frozen capability input, never a proof of current authorization. No bearer bytes or cryptographic key material are included. Diagnostics are redacted. Release also uses this snapshot: proven live-owner rollback preserves the generation; recovery release requires the exact successor generation.

func (CapabilityReservationBinding) Format

Format redacts retained command and proof correlation metadata.

func (CapabilityReservationBinding) MarshalJSON

func (CapabilityReservationBinding) MarshalJSON() ([]byte, error)

MarshalJSON prevents export of retained correlation metadata.

type CapabilityReservationContributor

type CapabilityReservationContributor interface {
	Contributor
	ReserveCapability(context.Context, CapabilityReservationWork) error
	RebindCapability(context.Context, CapabilityReservationWork) error
}

CapabilityReservationContributor supplies the two atomic pre-domain phases for capability.one-use v1. Only Coordinator invokes these methods. Reserve locks an already-issued exact input and binds command/fingerprint/generation; it must not insert missing capability state or consume a use. Rebind must CAS an existing reserved row from exactly PreviousGeneration to Generation under the same command/fingerprint. Missing, terminal or mismatched rows fail without changing state. Both phases participate in the command reservation transaction. Implementations must validate Binding with their own registered identity before SQL, use primary time for expiry, close rows, return redacted errors and never retain Work, invoke caller hooks, perform network I/O or begin/close another transaction. This open interface grants no invocation authority. Domain/finalization phases remain separate.

type CapabilityReservationWork

type CapabilityReservationWork struct {
	// contains filtered or unexported fields
}

CapabilityReservationWork is a coordinator-created, invocation-bound SQL capability. There is no constructor, raw driver, closure or Work escape hatch. Copies share lifetime and expire when the callback returns, including panic. Serial use only; returned rows must be closed before return. Existing Work parameter/result/time budgets apply; earlier deadlines win. Zero is invalid.

func (CapabilityReservationWork) Binding

Binding returns an owned declaration after checking invocation lifetime and exact registered contributor identity. Comparable immutable values use value identity; pointer implementations use instance identity. Nil, noncomparable or foreign implementations fail before participant SQL.

func (CapabilityReservationWork) DatabaseTime

func (w CapabilityReservationWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime reads primary UTC without renewing the original lease/lifetime.

func (CapabilityReservationWork) Exec

func (w CapabilityReservationWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec executes one trusted participant statement, never transaction closure.

func (CapabilityReservationWork) Format

func (CapabilityReservationWork) Format(s fmt.State, _ rune)

Format hides the retained transaction and participant state.

func (CapabilityReservationWork) MarshalJSON

func (CapabilityReservationWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of invocation authority.

func (CapabilityReservationWork) Query

func (w CapabilityReservationWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns bounded invocation-owned rows; close/drain them before return.

type CaptchaApplyWork

type CaptchaApplyWork struct {
	// contains filtered or unexported fields
}

CaptchaApplyWork grants exact invocation-owned primary reads, not mutations, provider access or transaction closure. Trusted read/locking SQL only. Zero, foreign and returned handles deny; copies share cancellation and lifetime. Use serially and close rows before callback return.

func (CaptchaApplyWork) Binding

Binding returns current exact-owner custody; it grants no release authority.

func (CaptchaApplyWork) DatabaseTime

func (w CaptchaApplyWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary UTC without renewing original validity.

func (CaptchaApplyWork) Format

func (CaptchaApplyWork) Format(s fmt.State, _ rune)

Format redacts native custody and invocation authority.

func (CaptchaApplyWork) MarshalJSON

func (CaptchaApplyWork) MarshalJSON() ([]byte, error)

MarshalJSON denies invocation serialization.

func (CaptchaApplyWork) MarshalText

func (CaptchaApplyWork) MarshalText() ([]byte, error)

MarshalText denies invocation serialization.

func (CaptchaApplyWork) NativeCommand

NativeCommand returns immutable authenticated input to the exact owner.

func (CaptchaApplyWork) Query

func (w CaptchaApplyWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query reads bounded primary rows without escaping Work ownership.

type CaptchaEvidencePlan

type CaptchaEvidencePlan struct {
	IssuanceCommandID                            string
	KeyVersion                                   uint32
	PolicyVersion                                uint64
	OriginalSignature, EvidenceDigest, Signature [32]byte
	IssuedAt, CheckedAt, ExpiresAt               time.Time
}

CaptchaEvidencePlan freezes token-free signed consuming custody separately from CAPTCHA issuance replay ownership. OriginalSignature commits to the full original signed flow/configuration carried by the immutable native command. Its authoritative command fingerprint must also cover every target/version field. PolicyVersion belongs to risk, not the command's authorization policy. This scalar declaration proves neither authenticity nor durable state. The native risk owner must authenticate it and perform all one-use phases inside the sole coordinator. Execution remains closed until those phases exist. Copies own their scalars; callers must not mutate input during preparation.

func (CaptchaEvidencePlan) Format

func (CaptchaEvidencePlan) Format(s fmt.State, _ rune)

Format hides private issuance/consumer linkage for every format verb.

func (CaptchaEvidencePlan) MarshalJSON

func (CaptchaEvidencePlan) MarshalJSON() ([]byte, error)

MarshalJSON rejects private signed custody serialization.

func (CaptchaEvidencePlan) MarshalText

func (CaptchaEvidencePlan) MarshalText() ([]byte, error)

MarshalText rejects private signed custody serialization.

type CaptchaExecutionContributor

type CaptchaExecutionContributor interface {
	CaptchaUseReservationContributor
	CheckCaptchaEvidence(context.Context, CaptchaApplyWork) error
	FinalizeCaptchaEvidence(context.Context, CaptchaFinalizeWork) error
	ReleaseCaptchaEvidence(context.Context, CaptchaReleaseWork) error
}

CaptchaExecutionContributor opts the exact consuming owner into domain use. Check authenticates original/consumer custody, current flow/policy/profile and exclusive primary expiry under exclusion, before mutation and before finalize. Finalize rechecks then CASes exactly reserved command/fingerprint/generation to terminal finalized in the same transaction as domain/effects/result. Release runs only after coordinator-proven rollback or unanimous primary noncommit evidence; expiry/lease loss alone is never proof. All methods close rows, retain no handles, run no providers/private transactions or retries, and support independent concurrent invocations with serial-use handles. Domain owners separately check current user/session/factor and target authority.

type CaptchaFinalizeWork

type CaptchaFinalizeWork struct {
	// contains filtered or unexported fields
}

CaptchaFinalizeWork grants invocation-owned terminal CAS in the domain transaction after provisional protected effects. It permits no release, renewal, private commit or retained rows. Copies share lifetime; serial use.

func (CaptchaFinalizeWork) Binding

Binding returns exact current-generation custody, not noncommit proof.

func (CaptchaFinalizeWork) DatabaseTime

func (w CaptchaFinalizeWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime cannot renew evidence, command lease or invocation lifetime.

func (CaptchaFinalizeWork) Exec

func (w CaptchaFinalizeWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec performs trusted terminal SQL, never transaction closure.

func (CaptchaFinalizeWork) Format

func (CaptchaFinalizeWork) Format(s fmt.State, _ rune)

Format redacts terminal authority.

func (CaptchaFinalizeWork) MarshalJSON

func (CaptchaFinalizeWork) MarshalJSON() ([]byte, error)

MarshalJSON denies terminal authority serialization.

func (CaptchaFinalizeWork) MarshalText

func (CaptchaFinalizeWork) MarshalText() ([]byte, error)

MarshalText denies terminal authority serialization.

func (CaptchaFinalizeWork) NativeCommand

NativeCommand returns the same admitted input to the exact native owner.

func (CaptchaFinalizeWork) Query

func (w CaptchaFinalizeWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns bounded callback-owned rows; close them before returning.

type CaptchaReleaseWork

type CaptchaReleaseWork struct {
	// contains filtered or unexported fields
}

CaptchaReleaseWork grants terminal release only after primary noncommit proof. Binding carries the exact reserved predecessor and recovery successor, or the unchanged live owner after proven rollback. Expired evidence is releasable after proof, never reusable. Zero/foreign/retained handles deny, copies share lifetime; serial use and bounded SQL only, with no private closure.

func (CaptchaReleaseWork) Binding

Binding checks exact registered ownership and frozen original linkage.

func (CaptchaReleaseWork) DatabaseTime

func (w CaptchaReleaseWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary UTC; expiry alone is not release proof.

func (CaptchaReleaseWork) Exec

func (w CaptchaReleaseWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec performs bounded terminal release SQL without private commit.

func (CaptchaReleaseWork) Format

func (CaptchaReleaseWork) Format(s fmt.State, _ rune)

Format redacts proof-bound authority.

func (CaptchaReleaseWork) MarshalJSON

func (CaptchaReleaseWork) MarshalJSON() ([]byte, error)

MarshalJSON denies release authority serialization.

func (CaptchaReleaseWork) MarshalText

func (CaptchaReleaseWork) MarshalText() ([]byte, error)

MarshalText denies release authority serialization.

func (CaptchaReleaseWork) Query

func (w CaptchaReleaseWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query reads bounded primary rows; close each before callback return.

type CaptchaReplayContributor

type CaptchaReplayContributor interface {
	FeatureExecutionContributor
	ReserveCaptchaReplay(context.Context, CaptchaReservationWork) error
	RebindCaptchaReplay(context.Context, CaptchaReservationWork) error
}

CaptchaReplayContributor is the native risk store's pre-domain issuance participant, invoked only by the sole coordinator. Reserve must authenticate the original signed command and current immutable configuration, atomically claim every retained token alias under one winner, and deny any different winner even after expiry. Rebind must conserve those aliases and CAS exactly PreviousGeneration to Generation. Domain rollback must not erase winners; elapsed time alone cannot release unresolved ownership. These methods issue no evidence, consume no protected use and disclose no bearer. Implementations verify Binding with their exact registered instance before SQL, close every row, return redacted errors and support concurrent calls with independent serial-use handles. No private transaction, network/provider callback, transaction closure or retained handle is permitted.

type CaptchaReplayOwnership

type CaptchaReplayOwnership struct {
	Fingerprint [32]byte
	Generation  uint64
	// PreviousGeneration is nonzero only during primary recovery. It names
	// the retained participant owner being reconciled, not mutation authority.
	PreviousGeneration uint64
}

CaptchaReplayOwnership is the original authoritative fingerprint and current generation, exposed only during an exact declared native invocation. It is linkage, not current authorization, replay ownership or commitment proof. Adapters must compare both against their locked primary winner before use.

func (CaptchaReplayOwnership) Format

func (CaptchaReplayOwnership) Format(s fmt.State, _ rune)

Format redacts native command linkage.

func (CaptchaReplayOwnership) MarshalJSON

func (CaptchaReplayOwnership) MarshalJSON() ([]byte, error)

MarshalJSON rejects native custody serialization.

func (CaptchaReplayOwnership) MarshalText

func (CaptchaReplayOwnership) MarshalText() ([]byte, error)

MarshalText rejects native custody serialization.

type CaptchaReservationBinding

type CaptchaReservationBinding struct {
	Command                        identity.Command
	Fingerprint                    [32]byte
	Generation, PreviousGeneration uint64
}

CaptchaReservationBinding owns the immutable original native command and authoritative retained-key fingerprint. Generation is positive; PreviousGeneration is zero for first reservation or the exact predecessor. This is invocation custody, not proof that provider verification, durable evidence, current authority or replay ownership exists. The participant must authenticate all original signed fields before changing its owned tables.

func (CaptchaReservationBinding) Format

func (CaptchaReservationBinding) Format(s fmt.State, _ rune)

func (CaptchaReservationBinding) MarshalJSON

func (CaptchaReservationBinding) MarshalJSON() ([]byte, error)

func (CaptchaReservationBinding) MarshalText

func (CaptchaReservationBinding) MarshalText() ([]byte, error)

type CaptchaReservationWork

type CaptchaReservationWork struct {
	// contains filtered or unexported fields
}

CaptchaReservationWork is coordinator-created SQL authority limited to one native callback. Zero/foreign/expired handles deny; copies share lifetime. Existing Work cancellation, SQL and row budgets apply. Time reads and copies cannot renew the owner lease. Serial use only; close rows before returning. No constructor, raw driver, transaction closure or ordinary Work escape exists.

func (CaptchaReservationWork) Binding

Binding verifies callback lifetime and the exact registered participant identity before exposing original custody. Registration alone is not enough.

func (CaptchaReservationWork) DatabaseTime

func (w CaptchaReservationWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime reads authoritative primary UTC without renewing validity.

func (CaptchaReservationWork) Exec

func (w CaptchaReservationWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec runs one bounded trusted statement without transaction closure.

func (CaptchaReservationWork) Format

func (CaptchaReservationWork) Format(s fmt.State, _ rune)

func (CaptchaReservationWork) MarshalJSON

func (CaptchaReservationWork) MarshalJSON() ([]byte, error)

func (CaptchaReservationWork) MarshalText

func (CaptchaReservationWork) MarshalText() ([]byte, error)

func (CaptchaReservationWork) Query

func (w CaptchaReservationWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns bounded callback-owned rows; close them before returning.

type CaptchaUseReservationBinding

type CaptchaUseReservationBinding struct {
	Command                        identity.CommandBinding
	Plan                           CaptchaEvidencePlan
	Fingerprint                    [32]byte
	Generation, PreviousGeneration uint64
}

CaptchaUseReservationBinding is an owned snapshot of the exact original and consuming command. Fingerprint is the coordinator's authoritative complete intent fingerprint, not the provider-token replay fingerprint. Generation is positive. PreviousGeneration is zero for first reservation, otherwise the exact predecessor. This metadata is neither authentication nor commit proof.

func (CaptchaUseReservationBinding) Format

Format redacts original and consuming linkage.

func (CaptchaUseReservationBinding) MarshalJSON

func (CaptchaUseReservationBinding) MarshalJSON() ([]byte, error)

MarshalJSON denies private custody serialization.

func (CaptchaUseReservationBinding) MarshalText

func (CaptchaUseReservationBinding) MarshalText() ([]byte, error)

MarshalText denies private custody serialization.

type CaptchaUseReservationContributor

type CaptchaUseReservationContributor interface {
	RecoveryContributor
	ValidateCaptchaUseCommand(identity.Command, CaptchaEvidencePlan) error
	ReserveCaptchaEvidence(context.Context, CaptchaUseReservationWork) error
	RebindCaptchaEvidence(context.Context, CaptchaUseReservationWork) error
}

CaptchaUseReservationContributor owns the native protected-use reservation phases, not issuance replay ownership. ValidateCaptchaUseCommand is pure, bounded authentication of complete immutable command custody against current configuration and exact declared original. Reserve locks an already-issued row and binds the consuming command/fingerprint/generation. Rebind CASes the exact positive predecessor to its successor. Both authenticate signed input, check original exclusive expiry after locking using primary time, and deny missing, terminal, mismatched or foreign rows. They cannot issue, renew, release or consume evidence, call providers, open private transactions, close or retain Work. Copies share callback lifetime; use each handle serially and close every row before return. Independent invocations may be concurrent. This interface alone does not enable domain execution or recovery release.

type CaptchaUseReservationWork

type CaptchaUseReservationWork struct {
	// contains filtered or unexported fields
}

CaptchaUseReservationWork grants bounded SQL only during one native consuming reservation/rebind callback. It has no public constructor, driver, transaction closure or ordinary Work escape. Zero, foreign and returned handles deny. Copies share lifetime and cannot renew cancellation, SQL/result budgets, command generation, original expiry or owner lease. Serial use only.

func (CaptchaUseReservationWork) Binding

Binding checks active lifetime and exact registered instance before exposing owned scalar declarations. Nil/noncomparable/foreign owners fail without IO.

func (CaptchaUseReservationWork) DatabaseTime

func (w CaptchaUseReservationWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary UTC without renewing original validity.

func (CaptchaUseReservationWork) Exec

func (w CaptchaUseReservationWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec runs one bounded trusted statement without transaction closure.

func (CaptchaUseReservationWork) Format

func (CaptchaUseReservationWork) Format(s fmt.State, _ rune)

Format hides invocation authority.

func (CaptchaUseReservationWork) MarshalJSON

func (CaptchaUseReservationWork) MarshalJSON() ([]byte, error)

MarshalJSON denies invocation authority serialization.

func (CaptchaUseReservationWork) MarshalText

func (CaptchaUseReservationWork) MarshalText() ([]byte, error)

MarshalText denies invocation authority serialization.

func (CaptchaUseReservationWork) NativeCommand

NativeCommand exposes complete immutable admitted input only to that owner. Its keyed fingerprint includes every original-flow and target-version field.

func (CaptchaUseReservationWork) Query

func (w CaptchaUseReservationWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns bounded callback-owned rows; close them before returning.

type CommandAdmission

type CommandAdmission struct {
	Absent bool
	Record CommandRecord
}

CommandAdmission is either an authorized primary absence observation or safe historical command metadata. The zero value is invalid. Absent does not prove noncommit of a previously submitted command, reserve the command ID, grant execution authority, or prevent a concurrent reservation after the read. Record exposes no native payload or private command fingerprint. Copies are safe for concurrent reading; Record.Feature is an owned mutable scalar copy.

func (CommandAdmission) Validate

func (a CommandAdmission) Validate() error

Validate checks the exclusive observation shape, not authorization, primary provenance, intent equality or permission to evaluate providers. Native adapters must additionally match their retained pre-evaluation intent before replay; ReserveCommand remains the complete command-intent collision fence.

type CommandCounterAdmissionContributor

type CommandCounterAdmissionContributor interface {
	CommandCounterContributor
	CheckCommandCounters(context.Context, CommandCounterAdmissionWork) error
}

CommandCounterAdmissionContributor opts the exact native counter owner into protected domain execution. CheckCommandCounters must recheck original charge custody, current policy, freshness, authoritative counters and any selected lockout/override profile under the same domain transaction. It must not charge again, renew original evidence, run callbacks or open a private transaction. Nil success permits only this phase; it is not independent authorization or commitment. The feature owner separately checks current domain authority. Missing implementation leaves counter-bearing Begin unsupported.

type CommandCounterAdmissionWork

type CommandCounterAdmissionWork struct {
	// contains filtered or unexported fields
}

CommandCounterAdmissionWork is invocation-only current-check custody over the coordinator's domain transaction. It exposes bounded reads and primary time, no transaction, closure or increment API. Queries must be trusted read/locking statements, never mutations. Copies share lifetime, serial use only; close returned rows before return. Zero, foreign owners and retained handles fail.

func (CommandCounterAdmissionWork) Binding

Binding returns current-generation linkage, never predecessor transfer authority. A committed charge is a prerequisite, not domain commitment.

func (CommandCounterAdmissionWork) DatabaseTime

func (w CommandCounterAdmissionWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary time without renewing Work or original evidence.

func (CommandCounterAdmissionWork) Format

Format redacts native inputs and transactional custody.

func (CommandCounterAdmissionWork) MFACompletionScope

MFACompletionScope retains the same exact native counter-owner scope guard during current admission. It cannot authenticate a factor or consume a child.

func (CommandCounterAdmissionWork) MFALoginSendScope

MFALoginSendScope retains the same registered-source guard during current allowance checks. It neither charges again nor converts metadata to a proof.

func (CommandCounterAdmissionWork) MarshalJSON

func (CommandCounterAdmissionWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects export of transaction authority.

func (CommandCounterAdmissionWork) MarshalText

func (CommandCounterAdmissionWork) MarshalText() ([]byte, error)

MarshalText rejects export of transaction authority.

func (CommandCounterAdmissionWork) NativeCommand

NativeCommand returns the exact admitted immutable input only to this owner.

func (CommandCounterAdmissionWork) Query

func (w CommandCounterAdmissionWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query reads bounded current primary state in the domain transaction.

type CommandCounterBinding

type CommandCounterBinding struct {
	Command                        identity.CommandBinding
	Plan                           CommandCounterPlan
	Fingerprint                    [32]byte
	Generation, PreviousGeneration uint64
}

CommandCounterBinding supplies exact frozen scope and primary command ownership to the registered native participant. PreviousGeneration zero means first owner; a positive exact predecessor means reuse the recorded attempt, never increment again. Metadata alone grants no SQL authority or current allowance.

func (CommandCounterBinding) Format

func (CommandCounterBinding) Format(s fmt.State, _ rune)

Format redacts command and charge linkage from diagnostics.

func (CommandCounterBinding) MarshalJSON

func (CommandCounterBinding) MarshalJSON() ([]byte, error)

MarshalJSON rejects export of private charge linkage.

func (CommandCounterBinding) MarshalText

func (CommandCounterBinding) MarshalText() ([]byte, error)

MarshalText rejects export of private charge linkage.

type CommandCounterContributor

type CommandCounterContributor interface {
	Contributor
	ValidateCommandCounters(identity.Command, CommandCounterPlan) error
	ReserveCommandCounters(context.Context, CommandCounterWork) (CommandCounterDisposition, error)
}

CommandCounterContributor is the sole native protected-counter participant. Pure validation must reconstruct the complete trusted native scope and current core policy before SQL. ReserveCommandCounters increments once on first owner, records its original snapshot, and reuses that snapshot on exact takeover. Denial is a disposition, not an error: returning an error rolls back the unit. No private transactions, provider/caller callbacks, closure or retained handles are allowed. SQL is provisional; only coordinator commit establishes outcome. Recovery must validate the original charge as prerequisite evidence, never report a charged reservation as proof of domain commitment. Instances must be comparable and support concurrent independent serial-use invocations.

type CommandCounterDisposition

type CommandCounterDisposition uint8

CommandCounterDisposition is a provisional native reservation-phase decision. It never means the charge or protected domain mutation has committed.

const (
	// CommandCounterAllowed permits the pending reservation to commit.
	CommandCounterAllowed CommandCounterDisposition = iota + 1
	// CommandCounterDenied commits the attempt with a denied audit/aborted receipt.
	CommandCounterDenied
)

type CommandCounterPlan

type CommandCounterPlan struct {
	PolicyVersion uint64
	Fingerprint   [32]byte
}

CommandCounterPlan freezes the core's keyed complete protected counter scope. Fingerprint binds tenant, operation, attempt, phase, current policy bounds, dimensions and retained digest aliases. It is a declaration, not authority; the registered native participant must reconstruct every input from the exact native command and current configuration. No raw dimensions or keys persist. Copies own scalars. Zero is invalid; concurrent input mutation is forbidden.

func (CommandCounterPlan) Format

func (CommandCounterPlan) Format(s fmt.State, _ rune)

Format redacts scoped fingerprints from diagnostics.

func (CommandCounterPlan) MarshalJSON

func (CommandCounterPlan) MarshalJSON() ([]byte, error)

MarshalJSON rejects export of private scope metadata.

func (CommandCounterPlan) MarshalText

func (CommandCounterPlan) MarshalText() ([]byte, error)

MarshalText rejects export of private scope metadata.

type CommandCounterWork

type CommandCounterWork struct {
	// contains filtered or unexported fields
}

CommandCounterWork is invocation-only coordinator SQL authority. Zero and foreign instances fail. Copies share lifetime; serial use only, close rows before return. It exposes no raw transaction, constructor or closure API. NativeCommand returns trusted native input only to the exact registered participant, never into the frozen plan, journal columns or diagnostics.

func (CommandCounterWork) Binding

Binding validates exact-instance ownership and returns an owned scalar scope.

func (CommandCounterWork) DatabaseTime

func (w CommandCounterWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime reads primary UTC after locks without renewing ownership.

func (CommandCounterWork) Exec

func (w CommandCounterWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec executes one bounded trusted statement, never transaction closure.

func (CommandCounterWork) Format

func (CommandCounterWork) Format(s fmt.State, _ rune)

Format redacts invocation state and private native command input.

func (CommandCounterWork) MFACompletionScope

MFACompletionScope lends the exact frozen anonymous TOTP/OTP/recovery completion subject and child plan only to the registered counter owner. It grants no factor or consumption authority; its purpose is to prevent a caller-selected counter subject or fictitious session. Zero, other profiles and foreign custody deny.

func (CommandCounterWork) MFALoginSendScope

func (w CommandCounterWork) MFALoginSendScope(owner CommandCounterContributor) (user identity.UserID, browser string, err error)

MFALoginSendScope lends the registered MFA owner's original resolved account and immutable browser-flow ID only to this exact native counter invocation. The command journal remains anonymous. Closed, returned, foreign and other profiles deny; no factor comparison, child use, SQL or freshness renewal occurs. These scalars grant no independent authorization or transaction authority.

func (CommandCounterWork) MarshalJSON

func (CommandCounterWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of transaction authority.

func (CommandCounterWork) MarshalText

func (CommandCounterWork) MarshalText() ([]byte, error)

MarshalText rejects serialization of transaction authority.

func (CommandCounterWork) NativeCommand

NativeCommand returns the immutable original admitted command to this owner.

func (CommandCounterWork) Query

func (w CommandCounterWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns invocation-owned rows that must close before return.

type CommandPlan

type CommandPlan struct {
	// APIKeyVerification freezes the closed read-only authentication attempt and
	// its optional same-command permission reduction. Nil preserves existing
	// non-verification profiles; the native verification schema requires it.
	// It is not permission to commit an arbitrary error or omit ordinary effects.
	APIKeyVerification *APIKeyVerificationPlan
	// OrganizationInvitationOrigin retains original organization correlation in
	// the invitation-send journal before any generated output or domain row.
	// Nil preserves historical bytes; it cannot support origin lookup recovery.
	OrganizationInvitationOrigin *OrganizationInvitationOriginPlan
	// MFACompletion selects the closed session-producing factor profile, not
	// enrollment verification or a caller-provided authentication proof.
	MFACompletion *MFACompletionPlan
	// MFAContinuation freezes the challenge-only alternative to password or
	// magic-link session issuance. Metadata alone grants no authentication.
	MFAContinuation *MFAContinuationPlan
	// MagicLinkRegistration freezes a prospective account creation in the
	// consuming transaction. Nil preserves the existing signin declaration.
	// This structural input grants neither email-possession nor creation authority.
	MagicLinkRegistration *MagicLinkRegistrationPlan
	// PasskeyRegistration selects prospective passkey-only creation under the
	// exact anonymous signup verification profile. Nil preserves old plan bytes.
	PasskeyRegistration *PasskeyRegistrationPlan
	// SignupAcceptance declares the anonymous password-signup alternative which
	// commits a neutral acknowledgement rather than creating a conflicting account.
	// False preserves historical declarations; this flag grants no authority.
	SignupAcceptance bool
	// MagicLinkRequestAcceptance freezes the anonymous signup-by-link request's
	// neutral no-issuance/no-delivery alternative for a final mailbox collision.
	// It preserves the request lifecycle and audit; it does not grant permission
	// to suppress effects. Only the kernel's protected prospective selector can
	// select this branch. False preserves historical request declaration bytes.
	MagicLinkRequestAcceptance bool
	// IdentifierAdmission selects an exact read-only session checker, not a
	// durable effect participant. Nil preserves historical plan bytes. Public
	// identifier execution remains disabled until native composition is complete.
	IdentifierAdmission *ContributorDescriptor
	Contributors        []ContributorDescriptor
	Audits              []AuditPlan
	Lifecycle           *LifecyclePlan
	// Delivery enlists encrypted effects under this original command, never
	// an independently committable enqueue operation. Nil leaves bytes unchanged.
	Delivery *DeliveryPlan
	// CapabilityIssuance declares original-command production, independently
	// from consuming an existing one-use capability. Nil preserves history.
	CapabilityIssuance *CapabilityIssuancePlan
	// Capability declares a typed one-use participant input. Identifier reservation
	// requires its registered reservation contributor; domain execution is disabled.
	Capability *CapabilityPlan
	// AccountLinkState freezes the distinct original OAuth callback-state input
	// only for the closed explicit-self prepared account-link profile. Capability
	// remains nil before exchange and names the final canonical link grant after
	// authenticated output attachment. State is never substituted for that grant.
	// Nil preserves all historical single-input plan bytes. Metadata alone does
	// not enable preparation or execution; both inputs require complete phases.
	AccountLinkState *CapabilityPlan
	// OTP freezes one server-issued submission and its native scope versions.
	// Declaration alone cannot enable reservation, counted denial or execution.
	// Nil preserves historical plan bytes; the full native phases are required.
	OTP *OTPAttemptPlan
	// RiskEvidence freezes a signed reset-initiation precheck. The exact registered
	// risk reservation participant is required; domain execution remains disabled.
	RiskEvidence *RiskEvidencePlan
	// CaptchaEvidence declares consuming custody, not issuance replay. It shares
	// the exact risk owner with counters/phone evidence where declared. Preparation
	// and reservation require its typed native validation/reservation contributor.
	// Domain execution and pending release/recovery remain closed until their
	// current-check, finalization and proof-bound release phases are complete.
	CaptchaEvidence *CaptchaEvidencePlan
	// CommandCounters declares protected-command durable counter admission.
	// It requires the exact native risk participant; no raw dimensions are stored.
	CommandCounters *CommandCounterPlan
	// CaptchaReplayReservation declares the native CAPTCHA issuance participant's
	// durable alias reservation/rebind before domain work. False preserves old
	// plan bytes. Only the exact CAPTCHA issuance schemas admit this phase; the
	// immutable command carries its signed original aliases and configuration.
	CaptchaReplayReservation bool
	// Feature declares one exact registered feature schema. Kernel digests reject
	// it; native execution additionally requires SubjectType and typed phases.
	Feature *FeatureRegistration
	// SubjectType fixes the feature audit/lifecycle primary target kind. Empty
	// retains the historical structural-only v1 profile; native execution needs
	// a canonical lowercase audit kind and the registered typed feature phases.
	// Kernel plans reject it. It is copied and bound in the v2 feature digest.
	SubjectType string
	Digest      [32]byte
}

CommandPlan is the complete declaration supplied by a PostgreSQL composition adapter before reservation. Contributors are ordered exact registry entries; Audits declare mandatory event slots, and Digest binds this declaration to the exact command and its authoritative retained-key fingerprint. Callers must not mutate its slices during admission. Admission owns copies, so later changes do not affect execution. Zero is invalid. This value conveys no transaction authority. Typed Capability input can be frozen and inspected; execution requires its complete selected native profile, never contributor names or declaration metadata alone. Lifecycle, when present, requires the typed outbox contributor and declares the successful mutation notification. Nil preserves the older audit-only admission profile; it is not sufficient for a future successful mutation commit, which must require its lifecycle and full effect declarations.

type CommandQueryPolicy

type CommandQueryPolicy struct {
	Authorization authorization.Service
	Clock         clock.Clock
	PolicyVersion uint64
}

CommandQueryPolicy enables receipt disclosure using the existing policy service, not historical grants. PolicyVersion must be positive; Authorization and Clock must be nonnil, concurrency-safe and bounded. Authorization runs before SQL and must honor cancellation. Neither dependency runs in an open transaction. The constructor copies configuration; caller-owned services must retain their immutable revision contract for this Coordinator's lifetime.

func (CommandQueryPolicy) Format

func (CommandQueryPolicy) Format(state fmt.State, _ rune)

Format hides runtime policy dependencies in diagnostic formatting.

func (CommandQueryPolicy) MarshalJSON

func (CommandQueryPolicy) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of runtime policy composition.

type CommandRecord

type CommandRecord struct {
	Binding    identity.CommandBinding
	Outcome    identity.CommitOutcome
	RetryAfter time.Duration
	// Feature preserves the exact historical schema for feature-owned commands.
	// Nil denotes a kernel command. This owned scalar copy contains no native
	// receipt, current authority, contributor handle or feature result payload.
	Feature *identity.FeatureOperation
}

CommandRecord is a safe historical command observation. It contains scope, outcome and bounded retry delay only: no replayed user/profile values, credential/account payload, audit record or contributor authority. Historical bindings are correlation, not current authorization or credential freshness. The zero value is invalid. Values are immutable copies safe for concurrent reads; successful lookup may accompany a classified terminal failure error.

func (CommandRecord) Validate

func (r CommandRecord) Validate() error

Validate checks the closed public observation shape, not authority or proof that storage was read. Committed/NotCommitted have no retry delay; InProgress has a positive delay at most one minute. Unknown is not a primary observation.

type Config

type Config struct {
	MaximumDuration time.Duration
	// ListSnapshots bounds retained structural listing; zero selects documented
	// finite defaults. Existing get-only compositions need no additional config.
	ListSnapshots UserListSnapshotConfig
	// AttributeSchemas declares at most 32 immutable scalar-storage schemas.
	// Defaults/fields are copied. Indexed and secret fields require explicit
	// migration/encryption profiles and currently fail closed.
	AttributeSchemas []identity.AttributeSchema
	// ProfileSchema selects one of AttributeSchemas for self-profile reads.
	// Zero disables GetProfile. Use the same declaration in ProfileService;
	// stored versions are never guessed, migrated or default-filled on reads.
	ProfileSchema ProfileSchemaRef
}

Config defines finite per-operation budgets. MaximumDuration must be positive and at most one minute; an earlier caller deadline always wins. Zero is invalid.

func (Config) Format

func (Config) Format(state fmt.State, _ rune)

Format prevents schema defaults from appearing in diagnostics.

func (Config) MarshalJSON

func (Config) MarshalJSON() ([]byte, error)

MarshalJSON rejects configuration serialization containing private defaults.

type Contributor

type Contributor interface {
	Descriptor() ContributorDescriptor
}

Contributor is an open composition-time identity supplied by a durable adapter. Descriptor must be a pure, bounded local operation returning a stable compile-time identity; it must not perform I/O or call user hooks. Registration conveys no transaction, commit or cross-package authority. Phase capabilities are separately typed: AuditContributor supplies durable audit staging. Other participant phases remain under development.

type ContributorDescriptor

type ContributorDescriptor struct {
	Owner      string
	ContractID string
	Version    uint32
}

ContributorDescriptor identifies an exact public contributor contract. Owner is 1..128 lowercase printable ASCII bytes; ContractID is 1..256 printable ASCII bytes. Whitespace/control characters are rejected, not normalized. Version is positive. All fields are comparable; zero is invalid. Composition roots must supply canonical package owners and compile-time contract IDs, never user-supplied aliases or runtime-generated identities.

type ContributorRegistry

type ContributorRegistry struct {
	// contains filtered or unexported fields
}

ContributorRegistry is an immutable snapshot of 1..64 contributors, created only by NewContributorRegistry. Values may be copied and read concurrently; the zero value is invalid. There is no late registration or removal. It retains contributor references, not ownership of their resources. Those implementations remain responsible for synchronization and lifecycle.

func NewContributorRegistry

func NewContributorRegistry(contributors []Contributor) (*ContributorRegistry, error)

NewContributorRegistry validates and snapshots the complete composition before any transaction opens. Nil (including typed nil), malformed descriptors, duplicate ContractIDs (including different owners or versions), empty and oversized compositions return identity.InvalidInputError without input data. Descriptors are read exactly once and copied; mutating the input slice later cannot change admission. Contributors are trusted compile-time adapters, not arbitrary callbacks: panics in their Descriptor method are not recovered. Optional FeatureContributor declarations are read once and frozen as well; malformed/empty/oversized declarations, wrong owner relationships, duplicate operation schemas and cross-contributor operation ownership fail atomically. At most 64 schemas per feature contributor and 1024 total may be declared. Panics in these trusted composition methods are not recovered. Callers must not mutate contributor declarations during construction. Registration alone never enables an unsupported command codec or execution phase. This constructor performs no I/O and never grants mutation authority.

Example
package main

import (
	"fmt"

	identitypostgres "github.com/faustbrian/go-identity/postgres"
)

// A separately owned adapter can implement the open interface without private
// symbols. This example describes registration only, not an executable phase.
type exampleContributor struct{}

func (exampleContributor) Descriptor() identitypostgres.ContributorDescriptor {
	return identitypostgres.ContributorDescriptor{Owner: "example/postgres", ContractID: "example.domain", Version: 1}
}

func main() {
	r, err := identitypostgres.NewContributorRegistry([]identitypostgres.Contributor{exampleContributor{}})
	if err != nil {
		panic(err)
	}
	d := r.Descriptors()[0]
	fmt.Println(d.Owner, d.ContractID, d.Version)
}
Output:
example/postgres example.domain 1

func (*ContributorRegistry) Descriptors

func (r *ContributorRegistry) Descriptors() []ContributorDescriptor

Descriptors returns an owned snapshot in composition order. Changing the returned slice cannot affect registration. A nil/zero registry returns nil; it does not become a valid empty registry. No contributor method is called.

func (*ContributorRegistry) FeatureOperations

func (r *ContributorRegistry) FeatureOperations() []FeatureRegistration

FeatureOperations returns an owned copy in contributor/declaration order. Nil/zero registries and legacy contributors declare no features. No method on a contributor is called. Concurrent reads are supported; changing the result cannot change registry admission. A declaration is not runtime readiness, enabled HTTP discovery or evidence of an implemented execution phase.

type Coordinator

type Coordinator struct {
	// contains filtered or unexported fields
}

Coordinator owns bounded command reservation transactions against a caller-owned primary pool and immutable registry. It starts no goroutines and never closes the pool. Concurrent reservations are supported. This incremental implementation admits creation and field-update mutation with required audit and lifecycle declarations. Begin, the enlisted Repository, Commit/Abort and the owned service compositions control execution. Recovery supports conservative creation/profile reconciliation; other recovery profiles and deadline alerting remain under development. Reservation is bookkeeping, never proof of a user mutation or audit/outbox persistence.

func NewCoordinator

func NewCoordinator(pool *database.Pool, registry *ContributorRegistry, config CoordinatorConfig) (*Coordinator, error)

NewCoordinator validates and copies composition without I/O. Migrate the primary database before reservation. Registry implementations are trusted typed adapters; no contributor method or caller callback runs here. Registered capability reservation phases run only in coordinator-owned reservation transactions. Invalid configuration returns a redacted error.

func NewCoordinatorWithRequestKeys

func NewCoordinatorWithRequestKeys(pool *database.Pool, registry *ContributorRegistry, config CoordinatorConfig, requestKeys RequestKeyConfig) (*Coordinator, error)

NewCoordinatorWithRequestKeys opts into pre-preparation retry correlation without changing the existing CoordinatorConfig contract. It validates and copies both configurations without I/O or callbacks. The pool remains caller owned; dependencies must support concurrent bounded calls. Install the optional request-key migration before ResolveRequestKey. Invalid configuration returns a redacted error. NewCoordinator alone keeps request correlation disabled.

func (*Coordinator) Abort

func (c *Coordinator) Abort(w Work, cause error) (identity.CommandResult, error)

Abort proves domain rollback before attempting a separate guarded terminal transaction. A pre-staged exact failure/denial audit is required for a known NotCommitted receipt; missing or success evidence stays pending/Unknown for recovery. The terminal audit and receipt commit together. Lease loss, failed rollback or ambiguous terminalization is Unknown. Caller cancellation cannot prevent bounded detached cleanup. Errors are classified/redacted, never returned verbatim. Native non-one-time features use coordinator-prebuilt classified failure records. Risk/CAPTCHA one-time owners release only after proven rollback; other one-time profiles and retry bookkeeping remain closed.

func (*Coordinator) ApplyFeature

func (c *Coordinator) ApplyFeature(ctx context.Context, w Work, command identity.Command) (result identity.CommandResult, err error)

ApplyFeature invokes only the frozen exact native adapter once through Work. Input must equal the admitted command's complete keyed intent. It prebuilds bounded failure evidence from primary time before mutation, validates the native provisional receipt, and stages every declared security/lifecycle slot. This is a trusted adapter composition seam, not an authentication endpoint. No bearer is generated/revealed. A returned receipt is provisional until Commit succeeds; the caller must always defer Abort. Errors poison Work; contributor diagnostics/panics are redacted. No local retry is performed.

func (*Coordinator) Begin

func (c *Coordinator) Begin(ctx context.Context, r Reservation) (Work, error)

Begin opens one bounded primary domain transaction after rechecking the exact claim, frozen plan, generation, owner and database-time lease. The opaque reservation is single-use, including failed admitted attempts; copies cannot create another Work. Foreign/zero reservations are rejected without consuming them. No authority is renewed after a lock wait. The caller MUST use Work serially and close it with Commit or Abort on every path, including panic (normally a deferred Abort). No background goroutine owns closure. A bounded PostgreSQL idle timeout additionally releases server locks for an abandoned idle handle, but does not release caller-held pool ownership: explicit closure remains required. Constructor pools remain caller-owned. Pre-observation failures are redacted; unproven rollback is identity.UnknownCommitError. Creation and self-profile mutation are supported. One-use risk profiles additionally require the exact native current-check and finalize contributor; reservation/release-only owners remain unsupported. Protected feature counters additionally require the exact native current-check contributor. Begin grants no counter allowance: ApplyFeature and Commit each recheck under domain tenant exclusion, without recharging or renewing evidence.

func (*Coordinator) Commit

Commit verifies the receipt against the owned native result and required effects, persists registered audit/outbox phases through this same Work, and writes the terminal result before one primary commit. Ordinary mutations require their successful audit/lifecycle transition. Closed API-key verification independently records authentication and optional permission reduction; durable command commit does not imply successful authentication. A caller-authored receipt cannot fabricate a mutation or native disposition. All aliases and rows are invalidated before closure. Any error after commit begins returns Unknown with no rollback/retry. Pre-commit failures roll back through Abort; absent matching failure audit leaves pending/Unknown, not a fabricated terminal denial. No reveal-once output is produced. Zero/foreign/ already-closed handles return an invalid-input error without closing others.

func (*Coordinator) ExecutePreparedAPIKeyVerification

func (c *Coordinator) ExecutePreparedAPIKeyVerification(ctx context.Context, original identity.Command, declaration CommandPlan) (result identity.CommandResult, fingerprint [32]byte, err error)

ExecutePreparedAPIKeyVerification submits a closed native verification preparation through the existing coordinator and returns the original claim fingerprint actually matched under its reservation lock. A retained older key may win even after a prospective absence observation used a newer key. The returned nonzero commitment must accompany original outcome recovery, including failed acknowledgement; it is not proof of commit or authority. Zero means no matching claim was established. No second journal, credential comparison or freshness source is introduced. Other feature profiles use ExecutePreparedFeature and cannot request this output. Original must bind the declared KeyVersion in its uint64 field apikey.verify.key-version so a later invocation cannot substitute that fence.

func (*Coordinator) ExecutePreparedFeature

func (c *Coordinator) ExecutePreparedFeature(ctx context.Context, original identity.Command, declaration CommandPlan) (result identity.CommandResult, err error)

ExecutePreparedFeature executes a native generated-output feature under its original code-free caller intent, using the existing claim/journal owner. declaration fixes feature, subject, mandatory audits and lifecycle before generation; the authenticated final plan may additionally enlist Delivery and exact anonymous-signup new-user verification issuance. Closed reset and magic-link consumption retain their original one-use input unchanged while generating the replacement/session. Other one-use profiles are rejected, not silently omitted. Explicit protected counters require CounterPreparationMigrationSource and a native current-check owner; their charge commits before generation and survives final rollback. Install PreparationMigrationSource before enabling this opt-in composition.

Current native admission precedes the committed start marker. Entropy never runs under SQL or after a lost start acknowledgement. Started-without-output remains pending even after lease expiry; retained output resumes without regeneration or renewed provenance. Matching terminal replay returns original receipts without generation/restoration; changed intent conflicts. Only the exact registered owner may reconstruct final custody. The original request fingerprint remains unchanged and generated-command substitution remains rejected. Final execution rechecks native authority and commits all effects through Begin/ApplyFeature/Commit. Earlier deadlines win; panics/diagnostics are redacted and uncertain durable outcomes return UnknownCommitError. This trusted adapter seam is not a public authentication endpoint or proof.

func (*Coordinator) ExecutePreparedMFAOTPFeature

func (c *Coordinator) ExecutePreparedMFAOTPFeature(ctx context.Context, original, prepared identity.Command, declaration CommandPlan) (identity.CommandResult, error)

ExecutePreparedMFAOTPFeature freezes the native mapped attempt before any session generation in the existing immutable preparation declaration. The original submitted code/browser defines journal identity; the exact OTP, child, counter and lifecycle owners retain atomic execution and recovery. Retained output never regenerates, terminal replay never compares again, and uncertain outcomes disclose no session. Restore frozen metadata before retry.

func (*Coordinator) ExecutePreparedMFARecoveryFeature

func (c *Coordinator) ExecutePreparedMFARecoveryFeature(ctx context.Context, original, prepared identity.Command, declaration CommandPlan) (identity.CommandResult, error)

ExecutePreparedMFARecoveryFeature retains original recovery/browser identity while executing the validated counter-enriched native declaration. Generation, atomic code consumption and session effects remain with the registered owner in the sole coordinator transaction. Replay cannot regenerate bearer custody or substitute original intent; uncertain outcomes require original recovery.

func (*Coordinator) ExecutePreparedMFATOTPFeature

func (c *Coordinator) ExecutePreparedMFATOTPFeature(ctx context.Context, original, prepared identity.Command, declaration CommandPlan) (identity.CommandResult, error)

ExecutePreparedMFATOTPFeature uses original submitted intent for the sole journal and a separately validated counter-enriched command for native admission/generation/execution. Only the closed anonymous TOTP transformation is permitted. Full frozen-plan, counter and factor checks remain mandatory; no retry may replace original preparation or regenerate lost bearer custody.

func (*Coordinator) ExpirePreparedFeatureCommand

ExpirePreparedFeatureCommand resolves an abandoned exact mapped origin after its immutable preparation deadline. Definitive noncommit requires a permanent global command-ID fence; mere absence or elapsed time never proves rollback. Existing commands remain under the ordinary recovery owner, never retirement. Install RequestKeyExpiryMigrationSource before selecting this API. The exact registered native codec and current query policy control disclosure. Before expiry, an absent claim remains Unknown. Concurrent original reservation wins or loses through the existing global primary key; it is never overwritten. A matching retained fence returns metadata-only NotCommitted and prevents every subsequent reservation of that ID. It cannot permit retrying effects. Generic recovery and ordinary retired-row privacy remain unchanged. Lost commit acknowledgement returns Unknown; retry this exact origin. The pool is borrowed, calls are bounded/concurrent and no goroutine or callback runs in SQL.

func (Coordinator) Format

func (Coordinator) Format(s fmt.State, _ rune)

Format prevents diagnostics from exposing retained keys and pool settings.

func (Coordinator) MarshalJSON

func (Coordinator) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of runtime composition and secret keys.

func (*Coordinator) ObserveAPIKeyVerificationCommand

func (c *Coordinator) ObserveAPIKeyVerificationCommand(ctx context.Context, command identity.Command, caller authorization.DecisionContext) (CommandAdmission, [32]byte, error)

ObserveAPIKeyVerificationCommand binds a trusted native verifier's complete original command to the sole coordinator claim. Authorized primary absence returns the prospective current-key fingerprint and Absent; existing history returns its exact retained-key fingerprint only after full intent comparison. Absence is neither reservation nor proof of rollback. Current AdmissionPolicy and the registered APIKeyVerificationContributor are mandatory. The read is bounded, uncached and effect-free; no participant, transaction or credential comparison is invoked. Generic metadata APIs still hide fingerprints.

Native code must preserve the actual commitment returned by ExecutePreparedAPIKeyVerification, not this prospective value, on ambiguous submission. Returned history never authenticates a credential or refreshes original validity. Concurrent calls share only immutable configuration; the caller retains pool ownership.

func (*Coordinator) ObserveCommandAdmission

ObserveCommandAdmission performs one bounded current-policy decision and one uncached primary command-ID read for trusted native composition. Only an authorized actual missing global claim returns Absent. Denied callers never learn absence or history; retired or wrong-scope claims return Forbidden, incomplete/corrupt history and outages fail closed. Terminal history preserves QueryCommand's safe outcome and classified error; pending remains pending, including expired leases. No transaction, participant, reservation or lease is created, locked, renewed or changed.

AdmissionPolicy is a separate opt-in from QueryPolicy. Its owned attributes set identity.command.read-admission=true and identity.command.recovery=false. The caller must be trusted authenticated composition bound to exact actor, tenant, operation and the exact identity.user or identity.anonymous-flow resource at the current configured policy revision, never a client-supplied override. This is not a public lookup route. Native adapters own further exact retained-intent matching and protected native-result recovery. Absence cannot substitute for ReserveCommand's atomic complete-intent fence or provide rollback proof after an ambiguous submission.

func (*Coordinator) PrepareAuthenticatedCommandPlan

func (c *Coordinator) PrepareAuthenticatedCommandPlan(b identity.CommandBinding, command identity.Command, proof authentication.AuthenticatedProof, p CommandPlan) (CommandPlan, error)

PrepareAuthenticatedCommandPlan freezes the exact original opaque proof into the existing keyed command intent and plan. It validates provenance against configured authority and the registered native mapping, not current authority or one-time use. No IO, reservation or credential delivery occurs. The same command and proof must accompany ReserveAuthenticatedCommand; an ordinary PrepareCommandPlan/ReserveCommand cannot substitute structural metadata.

func (*Coordinator) PrepareCommandPlan

func (c *Coordinator) PrepareCommandPlan(binding identity.CommandBinding, command identity.Command, plan CommandPlan) (CommandPlan, error)

PrepareCommandPlan checks the exact typed command binding and registry, computes the current-key fingerprint and returns an owned plan snapshot. The supplied Digest is replaced. It performs no I/O, reserves nothing and supplies no authorization: the identity service must authorize and prepare the command before calling the trusted composition adapter. Feature commands can prepare their exact registered schema, ordered mandatory contributors, bounded audit slots and lifecycle declaration. Historical v1 plans are structural-only. Native v2 plans additionally validate every native field/security action through the typed owner before reservation; preparation itself produces no execution handle. Event declarations alone do not prove native policy completeness. Identifier intent may prepare an exact typed capability reservation plan; other unsupported one-time/cascade profiles fail before SQL. Domain Begin for capability-bearing plans remains disabled until the complete workflow phases exist. Mutating returned slices affects only that caller's plan; do not mutate inputs during the call. A replay is rebound to its stored retained-key fingerprint inside ReserveCommand, never assigned a new fingerprint after key rotation.

func (*Coordinator) PrepareFeaturePreparationPlan

func (c *Coordinator) PrepareFeaturePreparationPlan(original identity.Command, declaration CommandPlan) (CommandPlan, error)

PrepareFeaturePreparationPlan validates and freezes an original generation declaration through the registered native preparation owner. Unlike ordinary PrepareCommandPlan, this may select original anonymous signup Secret/cookie custody before any generated verifier exists. Password and cookie intent are bounded and keyed by the existing claim codec; neither is persisted here.

This performs no SQL, generation, provider work or reservation. Success is not flow possession, current admission or execution authority: submit the exact original command and returned declaration to ExecutePreparedFeature. Ordinary reservation still rejects original signup input. Returned plan data is independently owned. Keep shared Secrets alive through bounded execution and Destroy afterward. Invalid input returns zero plan and redacted error.

func (*Coordinator) PrepareMFAOTPFeaturePlanWithOriginal

func (c *Coordinator) PrepareMFAOTPFeaturePlanWithOriginal(original, prepared identity.Command, p CommandPlan) (CommandPlan, error)

PrepareMFAOTPFeaturePlanWithOriginal validates the exact native consuming OTP attempt and protected-counter enrichment while preserving submitted code/browser/public intent as journal identity. The native OTP owner must authenticate its encrypted custody; all other field changes deny. Original transport.network must match the counter network; it remains only in opaque original intent, not the stored preparation declaration. No IO, comparison, charge, generation or session issuance occurs. Execute the exact pair through ExecutePreparedMFAOTPFeature; retries cannot remap the attempt.

func (*Coordinator) PrepareMFARecoveryAttemptPlan

func (c *Coordinator) PrepareMFARecoveryAttemptPlan(b identity.CommandBinding, command identity.Command, p CommandPlan) (CommandPlan, error)

PrepareMFARecoveryAttemptPlan freezes the closed recovery denial declaration. It performs no IO, comparison, reservation, burn or session issuance. The snapshot grants no authority and cannot enter ordinary structural execution.

func (*Coordinator) PrepareMFARecoveryAttemptPlanWithOriginal

func (c *Coordinator) PrepareMFARecoveryAttemptPlanWithOriginal(original, prepared identity.Command, p CommandPlan) (CommandPlan, error)

PrepareMFARecoveryAttemptPlanWithOriginal freezes validated counter enrichment while preserving the exact original recovery code, browser and public intent as journal identity. Only the six native counter fields may be added. No IO, comparison, charge, code consumption or session issuance occurs here.

func (*Coordinator) PrepareMFARecoveryFeaturePlanWithOriginal

func (c *Coordinator) PrepareMFARecoveryFeaturePlanWithOriginal(original, prepared identity.Command, p CommandPlan) (CommandPlan, error)

PrepareMFARecoveryFeaturePlanWithOriginal freezes the native retained-session declaration while keeping original recovery/browser custody as journal intent. Counter/child/lifecycle validation remains mandatory. This does not consume the recovery code or grant a session; pass the exact pair to the corresponding ExecutePreparedMFARecoveryFeature method without replacing retained evidence.

func (*Coordinator) PrepareMFATOTPAttemptPlan

func (c *Coordinator) PrepareMFATOTPAttemptPlan(b identity.CommandBinding, command identity.Command, p CommandPlan) (CommandPlan, error)

PrepareMFATOTPAttemptPlan freezes the native completion declaration for the denial-only route. It performs no IO, comparison, reservation or consumption. The returned owned snapshot is not authority; ordinary opaque execution denies.

func (*Coordinator) PrepareMFATOTPAttemptPlanWithOriginal

func (c *Coordinator) PrepareMFATOTPAttemptPlanWithOriginal(original, prepared identity.Command, p CommandPlan) (CommandPlan, error)

PrepareMFATOTPAttemptPlanWithOriginal freezes a native counter-enriched denial declaration while deriving journal identity only from original submitted intent and opaque code/browser custody. Only six validated native counter fields may be added; all other changes deny. It performs no IO or charging. Existing mapped-command APIs and generic fingerprint semantics are unchanged.

func (*Coordinator) PrepareMFATOTPFeaturePlanWithOriginal

func (c *Coordinator) PrepareMFATOTPFeaturePlanWithOriginal(original, prepared identity.Command, p CommandPlan) (CommandPlan, error)

PrepareMFATOTPFeaturePlanWithOriginal performs the same closed separation for retained session generation. The complete counter/child/lifecycle declaration remains frozen. Pass the exact pair to ExecutePreparedMFATOTPFeature; a current key or preparation time cannot replace historical command or plan evidence.

func (*Coordinator) PrepareOTPAttemptPlan

func (c *Coordinator) PrepareOTPAttemptPlan(b identity.CommandBinding, command identity.Command, p CommandPlan) (CommandPlan, error)

PrepareOTPAttemptPlan freezes a native counted-denial declaration without IO or authority. Ordinary PrepareCommandPlan/ReserveCommand still reject OTP; this seam admits RecordOTPAttemptDenial, not domain work. Consuming reserve additionally requires PrepareOTPReservationPlan's complete reservation owner. Native configuration authenticates the complete immutable submission before any transaction. Returned projections are owned copies; do not mutate input concurrently. Digest is replaced by the authoritative current-key mapping.

func (*Coordinator) PrepareOTPReservationPlan

func (c *Coordinator) PrepareOTPReservationPlan(b identity.CommandBinding, command identity.Command, p CommandPlan) (CommandPlan, error)

PrepareOTPReservationPlan freezes a consuming declaration after pure native validation, with no IO or authority. Denial-only owners and OTPCheck fail. Ordinary PrepareCommandPlan remains closed to opaque submissions. Returned custody is copied; callers must not mutate supplied plans concurrently.

func (*Coordinator) QueryAuthenticatedCommand

QueryAuthenticatedCommand is the owned final-authentication adapter's bounded primary receipt lookup, not a public login route. It requires the original native command, opaque proof and prepared plan plus current QueryPolicy authorization. It compares the complete intent under the claim's exact retained key version and the original frozen plan before returning only the supported final-authentication feature receipt. No user/profile payload or credential is returned. Generic QueryCommand remains metadata-only.

Original proof expiry is historical on this path: provenance is checked at its original issuance instant, never renewed. The receipt grants no current session authority or bearer delivery. Missing or retired claims deny without disclosing absence; incomplete evidence or missing retained keys fail closed. Exact changed input is Conflict. No reservation, lease, proof consumption, reconciliation, mutation, transaction or callback under a lock occurs.

func (*Coordinator) QueryCommand

QueryCommand performs one bounded, uncached primary observation and one current authorization decision. Caller is trusted authenticated composition, never a client-decoded identity override; it must bind actor, tenant, original operation and identity.user resource to query.UserID (or the exact identity.anonymous-flow resource to query.AnonymousFlowID) at the configured policy revision. Command possession is not authorization. The policy receives copied bounded inputs, trusted current time and recovery/read-admission attributes.

Valid missing, wrong-scope and denied requests take the same decision/read shape and return zero plus ForbiddenError; this does not promise identical network latency. Every RecoveryQuery field must match immutable stored scope. Successful observations preserve historical metadata, not current identity state or authority. Only safe scope/outcome metadata is returned; protected replay payloads stay inside the owned adapter/core recovery boundary.

Pending, even expired, returns InProgress; absence never proves NotCommitted. Terminal receipts are canonical and classification-checked. Matching claims without complete journals fail Unavailable. This method never locks for mutation, changes ownership, renews leases or invokes contributors. It is not RecoverCommand. QueryPolicy is opt-in; disabled/invalid composition fails before I/O. Earlier caller deadlines win; driver/policy errors stay redacted.

func (*Coordinator) QueryEmailVerificationMFAChallenge

func (c *Coordinator) QueryEmailVerificationMFAChallenge(ctx context.Context, q identity.RecoveryQuery, caller authorization.DecisionContext) (MFAContinuationPlan, CommandRecord, bool, error)

QueryEmailVerificationMFAChallenge returns authorized original challenge history for one exact separately committed verification parent. The native owner must derive RecordID from authenticated original child custody, not an unchecked caller claim. It is distinct from anonymous password/magic-link history. Only committed history discloses child scope; false identifies the ordinary known-empty-factor profile. Pending/aborted records have zero scope. This bounded journal query performs no reconciliation, signing, credential disclosure or validity renewal. Metadata is not primary or factor authority.

func (*Coordinator) QueryFeaturePreparation

QueryFeaturePreparation reads existing encrypted native output by exact original CommandID without requiring a request-key mapping. The configured current QueryPolicy and exact registered preparation owner must admit it. Pending output may precede final-plan attachment; terminal output may outlive today's aggregate version. Neither case grants execution or bearer authority. The native owner must authenticate configuration, binding, original generation and signed scope, then submit caller input to ExecutePreparedFeature for its complete original password/proof fingerprint comparison. Recovery instead uses RecoverFeatureCommand and never reconstructs an executable input.

Missing/retired/foreign history denies; incomplete, corrupt or absent output fails unavailable, never proving rollback or permission to regenerate. Reads neither reserve, take over, renew nor invoke participants/providers. Returned ciphertext is an independent caller-owned copy: clear after use and never log or serialize it. Failures return zero bytes/generation and redacted errors. The borrowed pool remains caller-owned. Immutable configuration permits concurrent calls; MaximumDuration and earlier caller deadlines bound all IO.

func (*Coordinator) QueryMFAOTPCommand

func (c *Coordinator) QueryMFAOTPCommand(ctx context.Context, command identity.Command, caller authorization.DecisionContext) (identity.CommandResult, bool, error)

QueryMFAOTPCommand observes the original opaque OTP/browser submission under its retained fingerprint key and current query authorization. Terminal denial or success is historical: it requires no live continuation, factor, OTP comparison or renewed allowance. Changed input conflicts, corrupt or retired custody denies, and only authorized absence returns false without an error. The returned receipt cannot disclose a session or authorize another attempt.

func (*Coordinator) QueryMFAOTPPreparation

QueryMFAOTPPreparation restores code-free native mapped metadata from the existing immutable declaration, including a checkpoint before session generation. Current query/admission policy and the original opaque code/browser fingerprint must match. Native OTP and counter owners validate the reconstructed command; this read grants no comparison or execution. Original intent must contain the immutable trusted transport.network field; raw network/base intent is never persisted in the preparation declaration. Authorized absence returns false; present incomplete/corrupt/retired evidence fails closed and cannot justify remapping or renewed freshness. Fields are independent trusted-adapter custody, never HTTP/diagnostic response data. Pool remains borrowed; cancellation and MaximumDuration bound all reads.

func (*Coordinator) QueryMFARecoveryCommand

func (c *Coordinator) QueryMFARecoveryCommand(ctx context.Context, command identity.Command, caller authorization.DecisionContext) (identity.CommandResult, bool, error)

QueryMFARecoveryCommand observes authorized original recovery-code history using its retained fingerprint key and frozen plan, without comparing against stored codes or charging an attempt. Matching denied retries remain observable after continuation changes; changed code/browser conflicts. Retired, missing or corrupt evidence fails closed. Presence includes conflicting input; only authorized absence returns false with no error. A receipt grants no factor authority, session delivery or permission to repeat uncertain consumption.

func (*Coordinator) QueryMFATOTPCommand

func (c *Coordinator) QueryMFATOTPCommand(ctx context.Context, command identity.Command, caller authorization.DecisionContext) (identity.CommandResult, bool, error)

QueryMFATOTPCommand compares original opaque TOTP input against retained command history under its original fingerprint key. It requires current query authorization but no live factor or mutable continuation projection: a counted denial must remain retryable after its budget version advances. The original frozen native completion plan is validated, never replaced.

The boolean reports authorized presence, including conflicting input. Only authorized absence returns false with nil error. Retired or unavailable evidence fails closed. Receipts are historical metadata, not permission to authenticate or reveal a session. No participant, code comparison, generation, reservation, consumption, mutation or recovery is invoked by this read.

func (*Coordinator) QueryManagedEmailPreparation

func (c *Coordinator) QueryManagedEmailPreparation(ctx context.Context, q identity.RecoveryQuery, caller authorization.DecisionContext, feature FeatureRegistration, owner FeaturePreparationContributor) (binding identity.CommandBinding, wire []byte, generation uint64, err error)

QueryManagedEmailPreparation reads original encrypted output for a committed native email-management request. The caller and q name current disclosure authority for verification-confirm, change-confirm or the closed OTP change request/confirm actions, not the historical human's session. q.CommandID names the original request; tenant, user and RecordID must match its committed scope. Link workflows first authenticate issued proof. Independent OTP change workflows instead authenticate original encrypted request custody through the exact registered preparation owner; a pending address alone is insufficient. The owner must authenticate/decrypt returned output and validate its original email intent. This read itself grants no mailbox ownership, credential use or current session authority.

Only self-user native-v1 verification-send and change-request origins match their respective confirmation actions. Missing, retired, foreign and noncommitted history denies. Incomplete/corrupt output fails unavailable. Generic original-actor recovery/query rules are unchanged. No preparation, generation, renewal, takeover, mutation or credential consumption occurs. Output is an owned sensitive copy; clear after use and never log/serialize it. The pool remains borrowed; immutable composition supports concurrent reads. MaximumDuration and earlier caller deadlines bound policy and primary IO. Failures return zero binding, bytes and generation with redacted typed errors.

func (*Coordinator) QueryOrganizationInvitationOrigin

QueryOrganizationInvitationOrigin reads original safe organization correlation from the sole command journal, including preparation-start history without a domain row or generated output. The current query policy and exact registered native invitation-send owner are required. Callers must authenticate a current session and separately authorize access to the returned organization before calling RecoverFeatureCommand; this read grants no recovery/execution authority.

Returns immutable scalar copies and historical outcome, never bearer, output, current permissions or a renewed deadline. Legacy, incomplete and corrupt origin declarations fail closed; absence never proves noncommit. A classified terminal failure may accompany valid metadata, matching QueryCommand. Policy runs outside SQL locks. The existing maximum/earlier caller deadline bounds this uncached read; concurrent calls borrow the coordinator's immutable config.

func (*Coordinator) QueryPasskeyMFAChallenge

QueryPasskeyMFAChallenge observes the exact original self-user UV assertion's challenge-only journal profile under current query authorization. The native owner must derive scope from authenticated original child/browser custody, never an unchecked target. Only committed history discloses frozen child scope; pending/aborted results contain zero scope. False denotes ordinary passkey signin, not absence or rollback. No assertion/factor verification, signing, reconciliation, mutation, credential disclosure or renewal occurs.

func (*Coordinator) QueryPasswordMFAChallenge

QueryPasswordMFAChallenge returns authorized original password-signin history and its closed MFA profile discriminator. Challenge scope is disclosed only for committed history; pending/aborted observations contain zero scope. False identifies an ordinary password-signin profile, not absence or rollback. This uses the existing query policy, journal and canonical frozen-plan decoder. It performs no reconciliation, signing, callback under locks or lease renewal. Returned metadata is historical correlation, never primary/factor authority. Earlier deadlines win and all operational errors remain redacted.

func (*Coordinator) QueryPreparedFeature

QueryPreparedFeature selects existing committed preparation by its original server CommandID. It requires current CommandQueryPolicy authorization, exact historical query scope and the exact registered request/preparation owner. Both original input and generated output must exist in the existing immutable mapping/journal. Legacy, pending, aborted, retired and incomplete history deny without creating, recovering or taking over work. No participant callback, entropy, external admission or domain mutation runs. Generic QueryCommand's metadata-only contract is unchanged.

Input provenance uses the original request policy/key version, not today's revision. OutputGeneration is the original ciphertext generation, never a later takeover generation. Neither value renews expiry or authority. Native owners must separately check current flow possession even on terminal history. Reads are uncached, bounded by MaximumDuration and earlier caller deadlines; all failures return zero custody and redacted classified errors. The borrowed pool stays caller-owned. Immutable configuration supports concurrent queries.

func (*Coordinator) QueryRegistrationPreparation

QueryRegistrationPreparation returns original encrypted signup input to its exact registered native owner for a currently authorized email confirmation. q.CommandID is the original signup command, q.UserID its separately selected registration user, and q.OperationID must be identity.email.verification-confirm. q.ActorID/ActorKind and caller describe the actual current caller, never the historical signup actor. Current CommandQueryPolicy must authorize that user and action. The committed original command, positive registration binding and immutable input provenance must all match; neutral acknowledgements, missing, pending, aborted, retired and foreign origins cannot disclose input.

The native owner must first authenticate the signed original registration proof, then authenticate this ciphertext and its complete binding, reconstruct the original email intent and authorize it with the email policy. This read grants neither mailbox ownership, current identity/session authority nor permission to consume. Confirmation must recheck current state and atomically mutate identity and consume the proof through the sole Coordinator transaction. No original cookie, live pre-auth flow or regenerated credential is required.

Returned bytes are caller-owned sensitive custody: clear them after use and never log/serialize them. No transaction, callback under locks, preparation, generation, takeover, mutation or goroutine is created. The pool is borrowed; immutable configuration permits concurrent calls. MaximumDuration and earlier deadlines bound all reads and policy work. Failure returns zero custody and typed redacted errors. Existing original-actor recovery APIs are unchanged.

func (*Coordinator) QueryRequestPreparation

QueryRequestPreparation reads only original encrypted input from an enrolled immutable request-key mapping. It does not need a password, initiating key, generated output or committed command. The exact registered input owner and current CommandQueryPolicy must admit the request. Namespace/key/feature and original actor/tenant/POST route provenance must match; retained fingerprint keys remain required. An existing claim must match full query scope and its journal. Retired, foreign or corrupt claims fail closed. Pending preparation may precede the final command plan; reading input does not approve that plan.

A mapping may precede its journal. In that case actor/tenant/route identify the mapping, but subject/flow/record cannot be checked until its native ciphertext is authenticated. The owner MUST authenticate every returned binding field, compare the decrypted original scope with q, and check original possession and current disclosure authority before returning any result to its caller. Encrypted input is not a receipt, proof of rollback or execution permission. QueryCommand and RecoverFeatureCommand remain the sole outcome/reconciliation owners; a missing journal never establishes NotCommitted.

No input preparation, generation, participant, takeover or mutation runs. Input bytes are caller-owned; clear them after use and never log/serialize them. Earlier deadlines win over MaximumDuration. Errors return zero custody and stay redacted. The pool remains borrowed; immutable configuration permits concurrent calls. QueryPreparedFeature retains its committed-output contract.

func (*Coordinator) ReadPreparedRequestKey

ReadPreparedRequestKey observes an existing original-input mapping by its initiating key under current exact request-admission policy and the retained intent fingerprint key. The native registered owner must authenticate the ciphertext and its complete binding before using any source projection. Found=false,nil means authorized absence only. Conflicting, corrupt, retired or unverifiable mappings return no custody and must not select a new source. No transaction, allocation, preparation callback, entropy, journal effect or takeover occurs; this observation grants no execution or result authority. Returned bytes are caller-owned and must be cleared after use. Pool/inputs remain borrowed; concurrent calls honor cancellation and MaximumDuration.

func (*Coordinator) RecordMFARecoveryAttemptDenial

func (c *Coordinator) RecordMFARecoveryAttemptDenial(ctx context.Context, b identity.CommandBinding, command identity.Command, p CommandPlan) (identity.CommandResult, error)

RecordMFARecoveryAttemptDenial uses the existing claim/journal transaction: exact replay precedes comparison, changed input conflicts, predecessor leases cannot be taken over, and ambiguous commit requires original recovery. No code, child or session is consumed here; correct comparison is not a proof.

func (*Coordinator) RecordMFARecoveryAttemptDenialWithOriginal

func (c *Coordinator) RecordMFARecoveryAttemptDenialWithOriginal(ctx context.Context, original, prepared identity.Command, p CommandPlan) (identity.CommandResult, error)

RecordMFARecoveryAttemptDenialWithOriginal uses original submitted custody for journal identity and validated counter-enriched custody for comparison. Exact replay does not charge again; substitution conflicts. Correct-code probing rolls back and grants no proof, code burn or session authority.

func (*Coordinator) RecordMFATOTPAttemptDenial

func (c *Coordinator) RecordMFATOTPAttemptDenial(ctx context.Context, b identity.CommandBinding, command identity.Command, p CommandPlan) (identity.CommandResult, error)

RecordMFATOTPAttemptDenial commits only native wrong-attempt accounting, denial audits and a stable aborted command, atomically in the existing journal transaction. Replay precedes comparison; changed input conflicts. Unchanged rolls back and returns Conflict, never successful authentication. Unresolved predecessors are not taken over or compared again. Commit ambiguity remains Unknown and requires observation of the original command, not replacement. A declared protected-risk charge uses the exact native counted callback and shares its transaction; omission or ignored risk denial aborts. Correct-code Unchanged rolls that provisional charge back with the callback. No child, OTP, session/domain reservation or lifecycle effect is invoked.

func (*Coordinator) RecordMFATOTPAttemptDenialWithOriginal

func (c *Coordinator) RecordMFATOTPAttemptDenialWithOriginal(ctx context.Context, original, prepared identity.Command, p CommandPlan) (identity.CommandResult, error)

RecordMFATOTPAttemptDenialWithOriginal charges the same native atomic denial lane using the original submitted claim and separately validated native counter-enriched command. Exact history remains original-input keyed; changed declarations still conflict and correct-code probing still rolls back.

func (*Coordinator) RecordOTPAttemptDenial

func (c *Coordinator) RecordOTPAttemptDenial(ctx context.Context, b identity.CommandBinding, command identity.Command, p CommandPlan) (identity.CommandResult, error)

RecordOTPAttemptDenial runs the narrow pre-reservation denial transaction. It locks the global command claim/journal before invoking the exact native OTP owner; no risk/CAPTCHA/capability/session/domain reservation is invoked. A committed wrong-attempt charge, exhaustion, required denial audits and stable aborted command result are atomic. Exact replay returns history without comparison or another charge; changed command/attempt/plan conflicts.

OTPAttemptUnchanged rolls back all provisional SQL and returns Conflict, granting no successful check or consuming authority. Expired pending history remains Unknown, never takeover/recomparison. Any commit-attempt failure is Unknown and must recover the original command AND server attempt identity; do not prepare a replacement submission. Current QueryPolicy authorizes safe observation; full consuming reservation/recovery remains in development. Earlier deadlines win; no local retry, callbacks under caller control, secret disclosure or private transaction ownership are exposed.

func (*Coordinator) RecordOTPMeteredCheck

func (c *Coordinator) RecordOTPMeteredCheck(ctx context.Context, b identity.CommandBinding, command identity.Command, p CommandPlan) (identity.CommandResult, error)

RecordOTPMeteredCheck commits only the separately limited identity.otp.check operation. Committed means that metering, check observation and required audit are durable, never that an account workflow committed or authentication was granted. Correct and incorrect comparisons charge the shared total budget and separate check budget exactly once. No proof, reservation, domain work, lifecycle event or session effect is produced. Exact replay returns retained history before comparison. Unknown commits require original-command recovery; never replace or remap an ambiguous submission. Context and resource budgets, current primary authority and original bearer requirements match denial.

func (*Coordinator) RecoverAPIKeyVerificationCommand

func (c *Coordinator) RecoverAPIKeyVerificationCommand(ctx context.Context, q identity.RecoveryQuery, fingerprint [32]byte, caller authorization.DecisionContext) (identity.CommandResult, error)

RecoverAPIKeyVerificationCommand narrows existing feature recovery to the exact original API-key attempt and nonzero coordinator fingerprint. Current QueryPolicy still authorizes the read. A mismatch fails before taking recovery locks or invoking participants; the same check repeats under the journal's existing recovery locks. Missing history never proves noncommit. No secret, native result or principal is returned, and no credential comparison, new command, alternate journal or freshness renewal occurs. Earlier deadlines win.

func (*Coordinator) RecoverAuthenticatedCommand

RecoverAuthenticatedCommand reconciles only an already observed exact pending command through the existing sole recovery owner, then repeats the original-intent receipt lookup. It never reserves or executes a missing command, creates a session, replaces a proof or reveals a credential. Live leases remain InProgress; ambiguous or incomplete evidence remains unknown. Current QueryPolicy and complete original input are required before recovery. The original command ID, namespace, policy, plan and retained-key bindings cannot change. Returned committed receipts remain historical metadata only.

func (*Coordinator) RecoverCommand

RecoverCommand authorizes current disclosure using QueryPolicy before attempting primary reconciliation. It exposes metadata only, never private replay fields. Missing/wrong-scope/denied requests retain QueryCommand's decision/read shape and perform no mutation. Live pending is observational. Expired creation, field-update and identifier-attachment recovery resolves only the exact frozen registry entries through RecoveryContributor, takes a new generation, and aborts only after all participants prove non-commit and a required failure audit is persisted in the same guarded transaction. Missing/unknown/conflicting evidence leaves pending; no success is reconstructed. Commit-attempt failure is Unknown. Identifier attachment additionally requires the typed capability release phase: only unanimous non-commit proof permits terminal release in the same transaction. It performs no command replay or network callbacks. Reset initiation additionally requires the typed risk release phase. Its release and aborted receipt commit only after unanimous retained noncommit proof; expiry alone never grants release. Other one-time profiles and recovery-deadline/operator alerting remain unfinished.

func (*Coordinator) RecoverFeatureCommand

RecoverFeatureCommand authorizes historical feature-receipt disclosure with the current QueryPolicy and reconciles pending commands through the same primary recovery owner as RecoverCommand. It returns the exact retained feature transition and audit metadata, never a user/profile payload, session, proof or credential. The receipt grants no current authority or permission to execute effects or reveal a credential.

Missing, wrong-scope and denied queries perform the same bounded primary read and never reserve a command. Non-feature commands are forbidden before any reconciliation. Live leases remain observational; expired leases require the existing frozen recovery participants. Unknown commits retain their binding and return UnknownCommitError; terminal failures retain their classification. Earlier caller deadlines win. Concurrent calls share the primary journal's generation fence; returned receipts are independently owned values.

func (*Coordinator) RecoverOTPAttemptDenial

RecoverOTPAttemptDenial observes the original command AND server-issued attempt without submitted code, comparison, charge, mutation or takeover. Caller must supply the original complete private attempt projection; neither command nor attempt possession authorizes disclosure. The existing current QueryPolicy and bounded primary read apply, including constant decision/read shape for valid denied requests. A changed attempt returns zero and Forbidden. Pending history remains InProgress, never proof of rollback or permission to replace the attempt. NotCommitted plus Forbidden is the historical denied result; committed/other terminal classes are not this narrow denial protocol. This does not recover or release a consuming reservation. Earlier deadlines win; no code or contributor callbacks are required or invoked.

func (*Coordinator) RecoverOTPFeatureCommand

func (c *Coordinator) RecoverOTPFeatureCommand(ctx context.Context, q identity.RecoveryQuery, expected OTPAttemptPlan, caller authorization.DecisionContext) (identity.CommandResult, error)

RecoverOTPFeatureCommand authorizes historical disclosure and matches every field of the original consuming OTP plan before observing or reconciling its feature outcome. It accepts no code or credential and never performs a new comparison, charge, reservation or protected mutation. Pending recovery uses the existing frozen participants and sole journal owner; exact correlation is checked again under the command locks before any recovery ownership change. The original pre-auth transaction need not remain executable. Native callers must separately authenticate original possession and current disclosure scope.

Both committed and classified aborted results remain historical, not current session authority or credential-delivery permission. No session or bearer is returned. Changed correlation returns zero plus ForbiddenError without taking ownership. Unavailable reconciliation preserves the original scope as Unknown; absence or expiry never proves rollback. QueryPolicy is required; the complete call shares one MaximumDuration bound and earlier caller deadlines win.

func (*Coordinator) RecoverOTPMeteredCheck

RecoverOTPMeteredCheck observes the exact original check command and server attempt through current QueryPolicy without code, bearer, comparison, charge, reservation or takeover. Committed is only the retained metering/check result; it grants no authentication proof or account-workflow success. Denied history returns NotCommitted with Forbidden. Pending history remains InProgress; ambiguity never permits remapping or a replacement logical submission. Changed mode/attempt and unrelated operation history fail closed. Original retained plan and outcome, not current challenge state, control replay.

func (*Coordinator) RecoverPreparedFeatureCommand

RecoverPreparedFeatureCommand observes/reconciles the exact original command using current query authorization, the existing immutable prepared-request mapping and its registered owner's authenticated native decoder. Neither an initiating key nor caller-constructed binding is accepted as outcome evidence. The complete decoded original scope must match q. The owner must additionally enforce its current session/domain disclosure policy before returning results.

An actual mapping whose claim is absent yields original correlation and UnknownCommitError, never NotCommitted, a receipt of effects or permission to execute again. A concurrent original may still create its journal. Existing journals use the ordinary sole recovery owner, historical scope checks and generation fence. Missing/foreign/corrupt mappings or denied current policy disclose no correlation. Generic QueryCommand/RecoverFeatureCommand preserve their uniform missing/denied contract. Earlier deadlines win; decoder errors and panics are redacted, resources remain borrowed, and no goroutine starts.

func (*Coordinator) ReserveAuthenticatedCommand

ReserveAuthenticatedCommand reserves only the original authenticated command through the existing global claim and scoped journal. Exact plan/proof intent is required; changed original metadata or namespace conflicts, including after fingerprint-key rotation. Primary time rechecks exclusive proof expiry after locks. Reservation consumes no proof and creates no session. Returned terminal replay is historical metadata only, never a bearer or refreshed authentication.

func (*Coordinator) ReserveCommand

ReserveCommand atomically locks the global ID claim before the scoped journal, freezes the complete supported plan and establishes a new or expired generation lease. A successful new reservation returns an opaque value plus InProgress, never Committed. Live replay returns zero reservation and bounded InProgress; exact terminal replay returns its historical receipt, not fresh authority. Changed scope/intent/plan returns Conflict. Missing keys, historical NULL plans or corrupt history fail closed. Invalid/pre-observation or proven-rollback failures return a zero result, not a fabricated durable NotCommitted. Any commit-attempt failure or unproven rollback returns Unknown with zero reservation; no automatic retry or local rollback after commit. Earlier caller deadlines win. All driver diagnostics are redacted. This phase performs no domain mutation or capability use. A typed capability reservation or exact predecessor rebind commits with the claim/journal, or every prefix rolls back together. Contributor errors, panic, unfinished rows or cancellation return no ownership. Invocation aliases expire before commit. It grants no proof that required audit/outbox effects have been written. Protected counter declarations invoke their registered native reservation phase. A denial commits its attempt with failure audit and an aborted receipt, returns NotCommitted for the domain plus ForbiddenError, and grants no handle. Matching terminal replay returns the recorded result without another charge.

func (*Coordinator) ReserveOTPCommand

ReserveOTPCommand uses the existing command claim/journal transaction and ordered one-use participants to reserve or CAS-rebind the native challenge. Exact live/terminal replay does not compare or charge again. Changed intent conflicts before invocation. Every participant prefix rolls back on failure; commit-attempt failure returns Unknown with no ownership and must recover the original command/attempt. Returned reservation does not enable domain Begin until the complete native current/finalize/release protocol exists. No local retry, renewal or independent transaction is introduced; deadlines only narrow.

func (*Coordinator) ResolvePreparedRequestKey

ResolvePreparedRequestKey retains original native code-free ciphertext in the existing immutable request-key mapping, atomically with its command ID. Install RequestKeyPreparationMigrationSource after RequestKeyMigrationSource. Existing rows are never backfilled or enrolled; missing/incompatible custody conflicts. Matching retries recover original ciphertext before native reads, counters or code generation; changed initiating intent returns no custody. Only the exact registered native feature may prepare input for its route. Preparation is outside SQL and may run more than once under races, but replay never invokes it. Returned bytes are owned, bounded to 1 MiB and must be authenticated by the native codec. Neither ciphertext nor binding proves current authority or grants journal execution. Unknown commit returns no binding/bytes; retry the same key/intent. Earlier deadlines win, callbacks and diagnostics are redacted, and the pool remains caller-owned.

func (*Coordinator) ResolveRequestKey

ResolveRequestKey authorizes and atomically correlates one scoped client key with an original server-random CommandID before generated command preparation. Matching retries verify the stored retained fingerprint key; changed intent returns Conflict with no ID. Missing historical keys fail closed. Mapping rows are immutable and never expire/reassign after 24 hours; journal cleanup, pending/unknown state and retired command claims do not reset the mapping. Feature owners supply complete schema-validated RequestIntent, including target, purpose, options, schema, policy and expected authority versions. The configured policy must allow the exact actor/tenant and RouteID action on resource type identity.request-admission with that same RouteID. Owned resource attributes identity.request.* replace caller overrides; authorization runs before SQL, outside transactions, with the trusted current clock/revision. Earlier caller deadlines win over MaximumDuration. Cancellation/dependency failures are redacted; lost commit acknowledgement returns UnknownCommitError and zero admission, never execution permission. Retry the same key/intent. No provider callbacks, goroutines or command journal/domain writes occur.

type CoordinatorConfig

type CoordinatorConfig struct {
	MaximumDuration              time.Duration
	LeaseDuration                time.Duration
	CurrentFingerprintKeyVersion uint32
	RetainedFingerprintKeys      map[uint32][32]byte
	// QueryPolicy enables authorized primary receipt lookup. Nil disables it.
	// The policy is copied; its dependencies must support concurrent calls.
	QueryPolicy *CommandQueryPolicy
	// AdmissionPolicy separately enables trusted pre-execution primary command
	// observation, including authorized absence. Nil disables it. A QueryPolicy
	// alone never enables absence disclosure; admission grants no reservation.
	AdmissionPolicy *CommandQueryPolicy
	// FinalAuthentication enables the protected final-signin command profile.
	// Nil disables it. The copied trusted authority and namespace are never
	// selected by a request; native owner checks remain mandatory.
	FinalAuthentication *FinalAuthenticationConfig
}

CoordinatorConfig supplies finite primary-operation and lease budgets and retained fingerprint keys. Durations must be positive, at most one minute; LeaseDuration must be microsecond-exact. The current positive key version must exist in the 1..32 retained nonzero 32-byte keys. Retain old keys while their command claims exist. Treat keys as secrets; the constructor copies the map. Do not mutate caller-owned configuration during construction.

func (CoordinatorConfig) Format

func (CoordinatorConfig) Format(s fmt.State, _ rune)

Format prevents diagnostic formatting from exposing fingerprint keys.

func (CoordinatorConfig) MarshalJSON

func (CoordinatorConfig) MarshalJSON() ([]byte, error)

MarshalJSON rejects configuration serialization rather than exposing keys.

type CounterPreparationMigrationSource

type CounterPreparationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

CounterPreparationMigrationSource appends protected-counter preparation to the existing command journal. Base must include AdmissionPreparationMigrationSource; Version follows installed history. Profiles 3/4 freeze the original code-free declaration before a counter charge and retain it across retries. Old readers reject these profiles; legacy rows and checksums remain unchanged. Install before selecting counters with ExecutePreparedFeature. No down SQL is provided.

func (CounterPreparationMigrationSource) Load

Load returns independently owned forward history without database IO. Nil, cancellation and version semantics follow PreparationMigrationSource.

type CreationUnitOfWork

type CreationUnitOfWork struct {
	// contains filtered or unexported fields
}

CreationUnitOfWork is the owned creation-only implementation of the core durable command seam. Use it only behind UserCreationService, which supplies current authorization, field preparation and output redaction. Direct calls do not authorize a caller. The exact Repository must already be enlisted with typed audit/outbox adapters in Coordinator. It starts no background work and owns no pool; immutable composition supports concurrent service calls. Zero is invalid. Creation recovery requires every frozen participant's typed recovery phase; other profiles/deadline alerting remain under development.

func NewCreationUnitOfWork

func NewCreationUnitOfWork(c *Coordinator, r *Repository, config CreationUnitOfWorkConfig) (*CreationUnitOfWork, error)

NewCreationUnitOfWork validates exact instance/phase composition without I/O or contributor callbacks. Consumers supply owned adapters, not a plan, audit builder, transaction, Work or command orchestration implementation.

func (*CreationUnitOfWork) Execute

func (o *CreationUnitOfWork) Execute(ctx context.Context, command identity.Command) (result identity.CommandResult, err error)

Execute maps the already admitted typed creation to the sole Coordinator. Replay preserves original receipts and event IDs. One primary transaction owns user/attributes/audit/lifecycle/result. Failure records are built from primary time before domain writes and staged only after proven rollback; no failed Work is revived. A failed audit commit or ambiguous closure remains Unknown. Unsupported commands/actor profiles fail before reservation. This trusted adapter seam is not an authenticated application endpoint.

func (CreationUnitOfWork) Format

func (CreationUnitOfWork) Format(s fmt.State, _ rune)

Format prevents runtime composition or retained dependencies from disclosure.

func (CreationUnitOfWork) MarshalJSON

func (CreationUnitOfWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of runtime composition.

func (*CreationUnitOfWork) Recover

Recover observes historical creation on the primary for the exact original scope, without constructing an authenticated DecisionContext from IDs. It belongs behind core current authorization/redaction, not a public transport. Missing/wrong scope reveals no receipt; live pending is InProgress. Expired creation may be aborted only with all frozen participants' negative evidence and atomically persisted failure auditing. Missing/unknown evidence stays pending. This never infers success from current user state or replays commands.

type CreationUnitOfWorkConfig

type CreationUnitOfWorkConfig struct{ RetentionPolicyVersion uint64 }

CreationUnitOfWorkConfig fixes the positive audit retention policy revision before admission. It is immutable copied configuration, not a callback or participant factory. Field-update compositions use the same retention input.

type CredentialAdmission

type CredentialAdmission struct {
	Credential                                                                   identity.CredentialRef
	UserAuthorityVersion, IdentifierAuthorityVersion, CredentialAuthorityVersion uint64
}

CredentialAdmission freezes the exact credential and three independently owned user security epochs. UserAuthorityVersion is not User.Version; IdentifierAuthorityVersion and CredentialAuthorityVersion cannot substitute for the exact credential record version. Zero is invalid. Native participants must bind every field into their immutable keyed command before reservation. This projection contains no proof and cannot grant authentication authority.

func (CredentialAdmission) Format

func (CredentialAdmission) Format(s fmt.State, _ rune)

Format omits correlated credential and authority scope from diagnostics.

func (CredentialAdmission) MarshalJSON

func (CredentialAdmission) MarshalJSON() ([]byte, error)

MarshalJSON rejects accidental export of correlated native admission input.

type CredentialCompromiseContributor

type CredentialCompromiseContributor interface {
	FeatureExecutionContributor
	CredentialCompromise(identity.Command) (CredentialCompromiseIntent, error)
}

CredentialCompromiseContributor is a native denial-only feature participant. CredentialCompromise is pure bounded mapping of its complete frozen command, not a callback supplied by a request. The identity-owned phase independently matches every metadata scalar before SQL. Actual detection/authorization and owned verifier state remain native responsibilities. A name or implementation alone grants no authority; the exact registered instance must be invoked. This phase cannot set/reset/change a password or enable a credential.

type CredentialCompromiseIntent

type CredentialCompromiseIntent struct {
	Credential               identity.CredentialRef
	ExpectedUserVersion      uint64
	ExpectedAuthorityVersion uint64
}

CredentialCompromiseIntent is exact denial-only native intent. All counters must have a positive uint64 successor. Credential.Version is the reference fence; ExpectedAuthorityVersion is the independent tenant/user epoch, not User.Version. No secret, proof, authorization or transaction is carried.

func (CredentialCompromiseIntent) Format

Format redacts reference and scope metadata.

type CredentialCompromiseLifecycleContributor

type CredentialCompromiseLifecycleContributor interface {
	LifecycleContributor
	PersistCredentialCompromise(context.Context, Work) error
}

CredentialCompromiseLifecycleContributor persists the normal staged lifecycle plus exact separate credential/user successors through the existing outbox participant. The coordinator invokes this instead of PersistLifecycle for a compromise, once. It must use StagedLifecycle and StagedCredentialCompromise, retain command-linked evidence and never close Work or perform network IO.

type CredentialCompromiseMigrationSource

type CredentialCompromiseMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

CredentialCompromiseMigrationSource adds retained kernel participant evidence after explicitly allocated Base history (including credential references). It changes no installed bytes. Load performs no SQL; the owned migration runner applies forward-only history. Retain evidence with command tombstones, never prune it with verifier/reference payloads: absence is negative recovery evidence. Missing infrastructure remains unknown, not proof of noncommit.

func (CredentialCompromiseMigrationSource) Load

Load returns independently owned history; nil/invalid composition or colliding versions return no history. Cancellation is preserved; no down SQL is supplied.

type CredentialCompromiseReceipt

type CredentialCompromiseReceipt struct {
	Credential              identity.CredentialRef
	BeforeUserVersion       uint64
	AfterUserVersion        uint64
	BeforeAuthorityVersion  uint64
	AfterAuthorityVersion   uint64
	BeforeCredentialVersion uint64
}

CredentialCompromiseReceipt is provisional safe metadata for the owned outbox phase. Only the journal's successful shared commit proves durability. It is not a current authority vector, completed cascade or authentication proof. Credential is the retained disabled reference's successor. Copies own their scalar values; aggregate, user credential epoch and record stay separate.

func (CredentialCompromiseReceipt) Format

Format redacts all scope and reference metadata.

type CredentialMigrationSource

type CredentialMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

CredentialMigrationSource composes immutable Base history with non-secret credential references and an independent user credential epoch. Version must be explicitly allocated after all Base versions and fit SQL migration storage. Existing MigrationSource and StatusMigrationSource history remains unchanged. Load performs no SQL; apply with the owned migrations Runner. The zero value is invalid. Destructive downgrade SQL is deliberately unavailable.

func (CredentialMigrationSource) Load

Load returns independently owned forward-only history. Migration defaults preserve existing status/aggregate/identifier epochs and old creation writers. Epoch 1 does not create a credential or grant authority: a missing reference still denies. References contain no secret/verifier; feature mutations must enlist through the sole coordinator rather than consumer SQL callbacks.

type CredentialReplacementContributor

type CredentialReplacementContributor interface {
	FeatureExecutionContributor
	CredentialReplacement(identity.Command) (CredentialReplacementIntent, error)
}

CredentialReplacementContributor is the exact native existing-password change participant. CredentialReplacement is pure mapping of the complete frozen command, independently checked by the kernel before SQL. ApplyFeature owns hash replacement and mandatory policy/proof checks, not kernel tables. This trusted composition seam is not an authenticated public endpoint. Registration, reset, enabling a disabled credential and hash-only upgrades are different profiles and cannot borrow this transition.

type CredentialReplacementIntent

type CredentialReplacementIntent struct {
	Credential               identity.CredentialRef
	ExpectedUserVersion      uint64
	ExpectedAuthorityVersion uint64
}

CredentialReplacementIntent binds an existing password reference and the independent user aggregate and credential-authority predecessors. Each must have a positive uint64 successor. It contains no password, hash, proof or authorization; the native workflow owns those policies and their custody.

func (CredentialReplacementIntent) Format

Format omits correlated credential and account metadata.

type CredentialReplacementLifecycleContributor

type CredentialReplacementLifecycleContributor interface {
	LifecycleContributor
	PersistCredentialReplacement(context.Context, Work) error
}

CredentialReplacementLifecycleContributor persists the staged lifecycle and exact separate version successors in the existing outbox transaction. The coordinator invokes this instead of PersistLifecycle, exactly once. It must not retain or close Work, perform network IO, or claim completed cascades.

type CredentialReplacementMigrationSource

type CredentialReplacementMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

CredentialReplacementMigrationSource appends retained password-change effect evidence after explicitly allocated Base history containing credential rows. Existing migration bytes are unchanged. Apply with the owned migration runner; Load performs no IO. Retain evidence with command tombstones, not credential payloads: an absent effect is used for pending-command negative recovery. Missing infrastructure must remain unknown. Zero composition is invalid.

func (CredentialReplacementMigrationSource) Load

Load returns owned forward-only history. Invalid/colliding versions return no partial history, cancellation is preserved, and destructive down SQL is absent.

type CredentialReplacementReceipt

type CredentialReplacementReceipt struct {
	Credential              identity.CredentialRef
	BeforeUserVersion       uint64
	AfterUserVersion        uint64
	BeforeAuthorityVersion  uint64
	AfterAuthorityVersion   uint64
	BeforeCredentialVersion uint64
}

CredentialReplacementReceipt is provisional metadata for the native outbox phase. Only the original journal's committed outcome proves durability. The reference remains enabled with its successor version and unchanged expiry. This is not a proof, renewable lease, current authority vector or session.

func (CredentialReplacementReceipt) Format

Format omits correlated credential and account metadata.

type CredentialResetContributor

type CredentialResetContributor interface {
	FeatureCommitContributor
	CredentialReset(identity.Command) (CredentialResetIntent, error)
}

CredentialResetContributor is the exact native reset-complete owner, distinct from authenticated password change. CredentialReset is pure bounded mapping; the kernel compares every predecessor and expected enablement. ApplyFeature must verify the original proof and issuance/profile/current recovery authority, replace the verifier and apply configured session effects through the same Work. CheckFeatureCommit must recheck original admission without renewing it. HIBP/risk preparation happens outside SQL before hashing. No private transactions, network IO under Work, kernel writes or retained Work are allowed. Methods may overlap on independent serial-use Work. This trusted composition seam is not a public authenticated endpoint or proof issuer.

type CredentialResetIntent

type CredentialResetIntent struct {
	Replacement     CredentialReplacementIntent
	ExpectedEnabled bool
}

CredentialResetIntent fixes the existing password reference and independent aggregate/credential-authority predecessors. ExpectedEnabled is the original primary reference state; a separately authorized reset may restore a disabled reference. Neither this metadata nor its fields authorize recovery. The native owner must check original signed reset scope, current factors/identifier/risk, and password policy. Reset never unblocks an inactive user or removes expiry.

func (CredentialResetIntent) Format

func (CredentialResetIntent) Format(s fmt.State, _ rune)

Format omits correlated account and credential metadata.

func (CredentialResetIntent) MarshalJSON

func (CredentialResetIntent) MarshalJSON() ([]byte, error)

MarshalJSON rejects accidental export of retained recovery scope.

type CredentialResetLifecycleContributor

type CredentialResetLifecycleContributor interface {
	LifecycleContributor
	PersistCredentialReset(context.Context, Work) error
}

CredentialResetLifecycleContributor persists the staged reset successors and required lifecycle/session effects in the existing transaction exactly once. It must propagate all errors, never close/retain Work or claim asynchronous cleanup complete. The credential epoch immediately invalidates prior bound authority; lifecycle consumers still own their required cleanup acknowledgements.

type CredentialResetMigrationSource

type CredentialResetMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

CredentialResetMigrationSource appends a forward-only reset extension to installed credential-replacement history. Existing migration bytes and password-change rows are unchanged. Install before selecting reset owners; old binaries remain change-only. Retained effects share command tombstone lifetime and do not store verifiers or bearers. Zero composition is invalid.

func (CredentialResetMigrationSource) Load

Load returns owned history without IO. Invalid/colliding versions return no partial history; cancellation is preserved. Destructive down SQL is absent.

type DeliveryContributor

type DeliveryContributor interface {
	RecoveryContributor
	ValidateDeliveryPlan(identity.CommandBinding, DeliveryPlan) error
	PersistDelivery(context.Context, Work) error
}

DeliveryContributor is the optional original-command encrypted-effect owner. ValidateDeliveryPlan is pure bounded validation, never authorization or IO. PersistDelivery is invoked only by the sole coordinator after mutation and before commit, using its exact enlisted instance and original Work. It must validate authenticated ciphertext/AAD and its confidential logical intent, persist custody and outbox admission together, and never call a sender, open a transaction, retain Work or stage kernel audit/lifecycle itself. Success is provisional. Recovery must inspect retained original bindings, not payload presence alone. Implementations support independent concurrent invocations. The registered owner must be comparable (normally a pointer): execution and recovery require exact instance identity, not descriptor equality.

type DeliveryEnvelope

type DeliveryEnvelope struct {
	EffectIndex uint16
	KeyID       string
	Ciphertext  []byte
}

DeliveryEnvelope contains authenticated ciphertext only, never plaintext. KeyID refers to the owner's retained secret-envelope key. The owning feature prepares encryption before the transaction and must not renew the credential or effect expiry. The coordinator does not invent a cryptographic verifier: the enlisted delivery owner verifies AAD and logical-input provenance.

func (DeliveryEnvelope) Format

func (DeliveryEnvelope) Format(s fmt.State, _ rune)

func (DeliveryEnvelope) MarshalJSON

func (DeliveryEnvelope) MarshalJSON() ([]byte, error)

MarshalJSON prevents ciphertext custody from entering diagnostics.

func (DeliveryEnvelope) MarshalText

func (DeliveryEnvelope) MarshalText() ([]byte, error)

MarshalText prevents implicit transport of runtime custody.

type DeliveryIntentPlan

type DeliveryIntentPlan struct {
	EffectID              string
	EffectIndex           uint16
	IntentDigest          [32]byte
	Purpose               string
	SubjectID             string
	TemplateID            string
	TemplateVersion       uint32
	ProviderConfigVersion uint64
	ExpiresAt             time.Time
}

DeliveryIntentPlan freezes one original-command effect. IntentDigest is the owner's confidential logical-input fingerprint, not a hash of randomized ciphertext. It must bind recipient, rendering, provider, no-op policy and all other behavior-affecting inputs. Metadata must contain only safe identifiers. Expiry is exclusive and never renewed by execution or recovery.

type DeliveryPlan

type DeliveryPlan struct {
	Contributor ContributorDescriptor
	Intents     []DeliveryIntentPlan
}

DeliveryPlan declares 1..16 encrypted effects and their exact versioned persistence owner. The contributor must be the last selected participant; every effect is required. Nil preserves historical no-delivery bytes. This declaration carries no plaintext, ciphertext or authorization proof.

type DirectoryAuthorityAdmission

type DirectoryAuthorityAdmission struct {
	Query                        DirectoryAuthorityQuery
	GlobalVersion, TenantVersion uint64
}

DirectoryAuthorityAdmission freezes both exact scope and expected epochs. Native participants must bind every field into their immutable keyed command before reservation, deriving deployment scope from trusted composition. It carries no proof, authorization decision or complete session authority vector.

func (DirectoryAuthorityAdmission) Format

Format redacts correlated admission input.

func (DirectoryAuthorityAdmission) MarshalJSON

func (DirectoryAuthorityAdmission) MarshalJSON() ([]byte, error)

MarshalJSON prevents accidental admission export.

type DirectoryAuthorityMigrationSource

type DirectoryAuthorityMigrationSource struct {
	Base              migrations.Source
	Version           migrations.Version
	GlobalAuthorityID string
	TenantIDs         []identity.TenantID
}

DirectoryAuthorityMigrationSource installs independent global/tenant epochs through the owned forward-only migration history. Base must be nonnil; Version must exceed every installed base version and fit signed SQL migration storage. GlobalAuthorityID is one explicit deployment authority. TenantIDs declares 0..256 exact bootstrap tenants, never inferred from users or authentication. Initial epoch 1/active state is a trusted operator decision, not authentication evidence. Missing tenants remain denied, including users created by old code. Copying/reordering the same tenant set produces identical migration bytes. Do not mutate caller-owned fields concurrently with Load. Zero is invalid.

func (DirectoryAuthorityMigrationSource) Load

Load supplies independently owned immutable install bytes and no destructive downgrade. Never change this configuration after its version is applied; new tenant onboarding and lifecycle mutations require their owned command APIs, not application-written SQL or edited historical migration checksums. Global compromise semantics and acknowledgement remain identity-owned and separate.

type DirectoryAuthorityQuery

type DirectoryAuthorityQuery struct {
	GlobalAuthorityID string
	TenantID          identity.TenantID
}

DirectoryAuthorityQuery selects an exact configured deployment authority and tenant. Both IDs follow the kernel's bounded opaque directory-ID policy; no normalization or caller identity inference occurs. Zero is invalid.

func (DirectoryAuthorityQuery) Format

func (DirectoryAuthorityQuery) Format(s fmt.State, _ rune)

Format redacts correlation-bearing authority scope.

func (DirectoryAuthorityQuery) MarshalJSON

func (DirectoryAuthorityQuery) MarshalJSON() ([]byte, error)

MarshalJSON rejects accidental correlated scope export.

func (DirectoryAuthorityQuery) Validate

func (q DirectoryAuthorityQuery) Validate() error

Validate rejects malformed scope before any primary read.

type DirectoryAuthorityRecord

type DirectoryAuthorityRecord struct {
	Query                        DirectoryAuthorityQuery
	GlobalVersion, TenantVersion uint64
	Enabled                      bool
}

DirectoryAuthorityRecord is a structural primary projection, not validity evidence or authentication. Epochs are positive full-width counters. Enabled is current tenant state, independent of any user's aggregate/status. Missing authorities never acquire a default epoch during reads.

func (DirectoryAuthorityRecord) Format

func (DirectoryAuthorityRecord) Format(s fmt.State, _ rune)

Format hides internal authority scope and version correlation.

func (DirectoryAuthorityRecord) MarshalJSON

func (DirectoryAuthorityRecord) MarshalJSON() ([]byte, error)

MarshalJSON rejects accidental authority projection export.

type EmailAttachmentContributor

type EmailAttachmentContributor interface {
	FeatureCommitContributor
	EmailAttachment(identity.Command) (EmailAttachmentIntent, *EmailAttachmentDomain, error)
}

EmailAttachmentContributor maps the original native command without IO or callbacks. ApplyFeature owns original fresh proof, current session, factor and risk admission/consumption; the kernel alone writes the pending email. Final checks conserve original validity and may not readmit a newer arbitrary directory epoch. Delivery and capability issuance remain separate enlisted owners. Implementations must not mutate or retain returned domain/intent.

type EmailAttachmentDomain

type EmailAttachmentDomain struct {
	// contains filtered or unexported fields
}

EmailAttachmentDomain borrows the exact enlisted kernel repository. Only the coordinator uses its immutable storage policy; it owns no transaction, retry, resource or goroutine. It is not an independently executable email service.

func NewEmailAttachmentDomain

func NewEmailAttachmentDomain(r *Repository, c EmailAttachmentDomainConfig) (*EmailAttachmentDomain, error)

NewEmailAttachmentDomain validates and copies explicit native composition without IO. Install IdentifierMutationMigrationSource before execution. This constructor does not authorize attachment or make a verification link valid.

func (EmailAttachmentDomain) Format

func (EmailAttachmentDomain) Format(s fmt.State, _ rune)

Format redacts borrowed directory and key custody.

func (EmailAttachmentDomain) MarshalJSON

func (EmailAttachmentDomain) MarshalJSON() ([]byte, error)

MarshalJSON refuses implicit export of borrowed native custody.

type EmailAttachmentDomainConfig

type EmailAttachmentDomainConfig struct {
	ComparisonProfile           string
	CurrentIdentifierKeyVersion uint32
	RetainedIdentifierKeys      map[uint32][32]byte
}

EmailAttachmentDomainConfig selects the versioned comparison profile and the retained identifier-reuse keys shared with removal/registration. Construction copies keys; a missing key referenced by live retirement history denies use.

func (EmailAttachmentDomainConfig) Format

Format redacts the immutable native key configuration.

func (EmailAttachmentDomainConfig) MarshalJSON

func (EmailAttachmentDomainConfig) MarshalJSON() ([]byte, error)

MarshalJSON refuses implicit export of native keys.

type EmailAttachmentIntent

type EmailAttachmentIntent struct {
	Change            identity.IdentifierChange
	ComparisonProfile string
	// ExistingCanonicalAddress is required only for pending resend. It cannot
	// replace or normalize the stored identity; attachment must leave it empty.
	ExistingCanonicalAddress string
	// Previous is mandatory for change-request and absent for verification.
	Previous ManagedEmailPrevious
}

EmailAttachmentIntent names a pending email and exact directory predecessors. Values must have been normalized by the selected versioned email owner. It is immutable command intent, not proof of possession, authentication or policy.

func (EmailAttachmentIntent) Format

func (EmailAttachmentIntent) Format(s fmt.State, _ rune)

Format redacts address, account and key material from implicit diagnostics.

func (EmailAttachmentIntent) MarshalJSON

func (EmailAttachmentIntent) MarshalJSON() ([]byte, error)

MarshalJSON refuses implicit export of correlated address intent.

type EmailRemovalAdministration

type EmailRemovalAdministration struct {
	GlobalAuthorityID            string
	GlobalVersion, TenantVersion uint64
}

EmailRemovalAdministration preserves original directory scope/epochs for explicitly administrative removal. Tenant comes from Change/CommandBinding; actor comes only from immutable ActorID. Zero retains the legacy self profile. The entire value must be frozen in EmailRemovalFields and retained custody.

type EmailRemovalContributor

type EmailRemovalContributor interface {
	FeatureCommitContributor
	EmailRemoval(identity.Command) (EmailRemovalIntent, *EmailRemovalDomain, error)
}

EmailRemovalContributor supplies immutable removal intent and the existing enlisted directory domain. ApplyFeature owns original primary proof, current factor/risk admission, actual surviving signin/reset eligibility and exact- target capability retirement. Only the kernel writes directory rows. Final authority checks and recovery must use the original generation and deadline.

type EmailRemovalDomain

type EmailRemovalDomain struct {
	// contains filtered or unexported fields
}

EmailRemovalDomain lends the enlisted directory's writer and copied policy. It owns no pool, transaction, journal, callbacks, workers or consumer closure.

func NewEmailRemovalDomain

func NewEmailRemovalDomain(r *Repository, c EmailRemovalDomainConfig) (*EmailRemovalDomain, error)

NewEmailRemovalDomain freezes native composition without IO. The existing retirement/status and identifier-removal-cascade migrations must be installed before use. Missing consumer contracts deny, not weaken the selected manifest.

func (EmailRemovalDomain) Format

func (EmailRemovalDomain) Format(s fmt.State, _ rune)

Format hides native directory and immutable key/policy custody.

func (EmailRemovalDomain) MarshalJSON

func (EmailRemovalDomain) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit native custody export.

type EmailRemovalDomainConfig

type EmailRemovalDomainConfig struct {
	Directory     EmailAttachmentDomainConfig
	ReuseCooldown time.Duration
	Cascade       IdentifierRemovalCascadeConfig
}

EmailRemovalDomainConfig selects the existing directory writer/reuse keys and exact immutable cascade policy. Native command fingerprints must bind this complete configuration. ReuseCooldown is microsecond-exact and within 0..365d; zero explicitly permits immediate canonical-value reuse, never ID resurrection.

func (EmailRemovalDomainConfig) Format

func (EmailRemovalDomainConfig) Format(s fmt.State, _ rune)

Format hides retained directory keys and policy configuration.

func (EmailRemovalDomainConfig) MarshalJSON

func (EmailRemovalDomainConfig) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit native key/configuration export.

type EmailRemovalIntent

type EmailRemovalIntent struct {
	Change                 identity.IdentifierChange
	ComparisonProfile      string
	Reason                 string
	LeavePrimaryUnassigned bool
	// ReplacementPrimary is omitted from legacy original custody when zero.
	// A selected value is independent exact intent, never an inferred successor.
	ReplacementPrimary identity.IdentifierPrimarySelection `json:",omitzero"`
	// Administration is nonzero only for a distinct human actor. It binds the
	// original directory epochs used before canonical actor/target row locks.
	// This is not an authorization decision or authentication proof.
	Administration EmailRemovalAdministration `json:",omitzero"`
}

EmailRemovalIntent freezes exact removal predecessors and explicit primary disposition. Reason is an owner-allowlisted code, not arbitrary audit text. It grants no authorization or claim of surviving credential/recovery paths.

func (EmailRemovalIntent) Format

func (EmailRemovalIntent) Format(s fmt.State, _ rune)

Format omits original account/address correlation and intent.

func (EmailRemovalIntent) MarshalJSON

func (EmailRemovalIntent) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit sensitive intent export.

type EmailVerificationContributor

type EmailVerificationContributor interface {
	FeatureCommitContributor
	EmailVerification(identity.Command) (EmailVerificationIntent, error)
}

EmailVerificationContributor is the native registration-link owner. Its pure mapper must agree with every frozen kernel field. ApplyFeature owns current proof, origin, callback and risk admission; only the kernel writes directory records. CheckFeatureCommit must recheck original admission without renewing it. Neither method may create sessions for this verification-only profile.

type EmailVerificationIntent

type EmailVerificationIntent struct {
	Change                identity.IdentifierChange
	CanonicalAddress      string
	ComparisonProfile     string
	RegistrationCommandID identity.CommandID
	// Empty retains the original password-signup encoding. The only additional
	// profile is the exact username-signup origin, never a caller-selected alias.
	RegistrationOperation string
}

EmailVerificationIntent names the original signup and exact current kernel predecessors for registration link confirmation. Change must be Verify of the original pending email record. CanonicalAddress and ComparisonProfile come from authenticated original signup intent, not callback request fields. This metadata carries no proof, session, policy or transaction authority.

func (EmailVerificationIntent) Format

func (EmailVerificationIntent) Format(s fmt.State, _ rune)

Format redacts original address and correlated account metadata.

func (EmailVerificationIntent) MarshalJSON

func (EmailVerificationIntent) MarshalJSON() ([]byte, error)

MarshalJSON rejects accidental disclosure of retained original intent.

type EmailVerificationMFAChallengeContributor

type EmailVerificationMFAChallengeContributor interface {
	FeatureCommitContributor
	ValidateEmailVerificationMFAChallenge(identity.Command, MFAContinuationPlan) error
}

EmailVerificationMFAChallengeContributor owns the challenge-only continuation after a separately committed registration verification. Validation is pure and bounded and must bind that committed parent, original signup browser, selected recipient, primary expiry, remember choice and unchanged current factor scope. ApplyFeature and CheckFeatureCommit independently fence the native parent's primary evidence and current account, identifier, risk and factor authority. Only the child challenge, continuation, audit and lifecycle share this Work; no parent consumption, password comparison or authenticated session is invented. Implementing this interface conveys no authentication or transaction authority.

type EmailVerificationMigrationSource

type EmailVerificationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

EmailVerificationMigrationSource appends retained command-linked verification evidence to explicit Base history containing registration bindings. Existing bytes and populated accounts remain unchanged. Allocate Version after all selected histories; Load performs no IO. Apply through the migration runner. Evidence follows command-tombstone retention, not bearer or address retention.

func (EmailVerificationMigrationSource) Load

Load returns owned forward-only history. Nil, colliding or out-of-range configuration denies; cancellation is preserved and no down SQL is supplied.

type FeatureAdmissionPreparationContributor

type FeatureAdmissionPreparationContributor interface {
	FeaturePreparationContributor
	PrepareFeatureAdmission(context.Context, identity.Command) (FeaturePreparationAdmission, error)
	RestoreFeatureAdmission(context.Context, identity.Command, uint64, []byte) (FeaturePreparationAdmission, error)
}

FeatureAdmissionPreparationContributor opts a registered preparation owner into external admission. Prepare runs outside SQL only for journal-owned, never-started generation. It receives bounded context and the immutable original command; nil admission denies. Restore is bounded, IO-free native authentication of original retained ciphertext/generation, not provider or counter work, generation, or renewed admission. Both return independent invocation state for the original request. Busy, started-without-output and terminal replays call neither method. Legacy preparation owners are unchanged.

type FeatureCommitContributor

type FeatureCommitContributor interface {
	FeatureExecutionContributor
	CheckFeatureCommit(context.Context, Work, identity.Command) error
}

FeatureCommitContributor optionally rechecks the exact native feature's original admission after all required persistence and journal writes, just before SQL commit. Existing contributors remain source-compatible. Check receives the original immutable command and serial generation-bound Work; FeatureScope is available only for this exact synchronous invocation, while Apply-only command identity is unavailable. The check may perform bounded primary reads and inspect original facts, never mutate, stage effects, renew admission, perform network IO, retain Work or begin another transaction. Errors or panics deny and roll back provisional effects; SQL commit ambiguity retains its existing Unknown outcome. Calls on independent Work may overlap.

type FeatureContributor

type FeatureContributor interface {
	Contributor
	FeatureOperations() []identity.FeatureOperation
}

FeatureContributor optionally declares the compile-time storage-neutral operations owned by a durable adapter. FeatureOperations must be a pure, bounded local method returning 1..64 stable descriptors; no I/O, hooks or runtime-generated request identities are allowed. Construction reads it once and owns a copy. Each descriptor's Owner plus "/postgres" must exactly equal the contributor's adapter Owner, except the closed username signup/signin profiles also admit the exact existing identity/password/postgres participant. Closed phone/password-signin v1 exclusively selects that password participant; a generic same-owner declaration cannot override this profile's native owner. Closed phone SMS-code signin v1 instead selects the existing OTP participant. All supported schema versions of an operation belong to one exact contributor identity. A schema may declare distinct user and anonymous-flow subjects; duplicates within either namespace are invalid. Declaration is not authorization, an executable command codec, transaction authority or a phase implementation. Phase capabilities remain separately typed and coordinator-owned.

type FeatureExecutionContributor

type FeatureExecutionContributor interface {
	FeatureContributor
	RecoveryContributor
	ValidateFeatureCommand(identity.Command, CommandPlan) error
	ApplyFeature(context.Context, Work, identity.Command) (identity.FeatureReceipt, error)
}

FeatureExecutionContributor is the native feature execution participant. Registration remains immutable; only the coordinator invokes ApplyFeature and recovery. ValidateFeatureCommand is a pure bounded local operation, validating every native field, declared security action, subject kind and transition before reservation. No request-generated callbacks, IO, mutation of the supplied plan, hooks or private transactions are permitted. ApplyFeature receives the sole generation-bound Work, performs current authority/optimistic checks and its owned mutation, and returns a provisional primary-record receipt. It must not stage audit/lifecycle, close or retain Work, mutate kernel-owned tables, perform network IO, or return secret material. The coordinator stages the declared effects and establishes durability. Closed API-key verification invokes APIKeyVerificationContributor instead of the generic mutation method, without changing other feature contracts. Methods must support concurrent calls with independent serial-use handles. Risk execution additionally requires its exact typed current-check/finalize owner. The exact registration-email, password-reset and magic-link profiles and organization invitation/anonymous upgrade profiles require their typed atomic participants. Other capability/OTP profiles remain rejected until their typed phases exist.

type FeatureInputAdmissionContributor

type FeatureInputAdmissionContributor interface {
	FeatureExecutionContributor
	AdmitFeaturePreparation(context.Context, Work, identity.Command) error
}

FeatureInputAdmissionContributor supplies the exact registered native feature's current original-input checks before another participant compares or charges a credential. The coordinator invokes it in its existing Work, never through a caller clearance callback or an OTP-handle conversion. FeatureScope identifies this synchronous owner; Apply-only command identity remains unavailable. Admission must perform only bounded owned primary reads and locks, not writes, generation, external IO, freshness renewal or retention. Errors/panics poison the complete provisional transaction. Implementations must support independent concurrent calls and immutable original input.

type FeaturePreparationAdmission

type FeaturePreparationAdmission interface {
	Check(context.Context) error
	Generate(context.Context, uint64) ([]byte, error)
}

FeaturePreparationAdmission is invocation-local state returned only by the exact registered native owner. Check is a bounded IO-free current validation of original admission facts; it must not renew them, call providers/stores, mutate state, or retain Work. Generate owns the original admitted request and embeds authenticated admission custody in its bounded encrypted output so a later native restore can recheck it without repeating external work. It runs outside SQL only after an acknowledged generation marker. Methods must obey cancellation; the owner must not share mutable invocation state across calls. This interface is neither an independently issued permission nor a journal.

type FeaturePreparationContributor

type FeaturePreparationContributor interface {
	FeatureInputAdmissionContributor
	ValidateFeaturePreparation(identity.Command, CommandPlan) error
	GenerateFeaturePreparation(context.Context, identity.Command, uint64) ([]byte, error)
	RestoreFeaturePreparation(context.Context, identity.Command, uint64, []byte) (identity.Command, CommandPlan, error)
}

FeaturePreparationContributor extends an exact registered native feature owner with original-request preparation. ValidateFeaturePreparation is pure, bounded schema/policy validation. AdmitFeaturePreparation borrows serial Work solely for current primary admission; it must not mutate domain state, stage effects, retain Work, perform network IO or generate secrets. Generation runs outside SQL only after the coordinator acknowledges the durable start marker. It returns bounded authenticated ciphertext, never plaintext credentials. RestoreFeaturePreparation authenticates that ciphertext against the complete original request and original generation, separately checks submitted bearer possession, and reconstructs the unchanged generated command and final plan. It must not generate, remap, renew authority/expiry or perform SQL/network IO. The same stable comparable owner handles every phase concurrently with invocation-local state. Final ApplyFeature still owns current authorization and atomic effects. No application-written workflow is required or permitted.

type FeatureRegistration

type FeatureRegistration struct {
	// Contributor is the exact adapter owner, contract ID and contract version.
	Contributor ContributorDescriptor
	// Operation is the exact core owner, operation, schema and record policy.
	Operation identity.FeatureOperation
}

FeatureRegistration binds a feature schema to one exact registered adapter. Its scalar fields are copied during composition. It grants no registry, transaction or execution authority; use only the registry's frozen projection for trusted composition, not request-supplied descriptors or HTTP discovery.

type FinalAuthenticationConfig

type FinalAuthenticationConfig struct {
	Authority *authentication.AuthorityAuthenticator
	Namespace string
}

FinalAuthenticationConfig selects one trusted final-signin authority and its stable durable proof namespace. Neither may come from request input. Namespace is bounded to 256 bytes and must remain unchanged while use tombstones exist. Authority owns concurrent pure proof validation; this configuration performs no authentication workflow, network IO, current-state refresh or token issuance.

type IdentifierAdmissionContributor

type IdentifierAdmissionContributor interface {
	Contributor
	CheckIdentifier(context.Context, IdentifierAdmissionWork) error
}

IdentifierAdmissionContributor performs primary session and applicable owner checks for one frozen self-user identifier command. It is a read-only role, not a durable effect owner: recovery never asks it to attest mutation outcome. Implementations must compare the frozen command, close rows, use bounded primary reads, and never retain Work, perform network calls or close a transaction. A successful check does not authenticate or authorize by itself.

type IdentifierAdmissionWork

type IdentifierAdmissionWork struct {
	// contains filtered or unexported fields
}

IdentifierAdmissionWork borrows the sole coordinator's transaction only for an exact registered check invocation. It permits bounded queries and current kernel eligibility checks, but no Exec or transaction closure. Copies share serial invocation lifetime; zero and retained handles deny. Errors on a live invocation poison the original Work even when ignored by the participant.

func (IdentifierAdmissionWork) Command

Command returns the complete frozen command and whether this is the terminal temporal recheck, only to the exact selected comparable participant. Neither phase renews authentication freshness or original session/proof expiry.

func (IdentifierAdmissionWork) DatabaseTime

func (h IdentifierAdmissionWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary time without creating or renewing a validity lease.

func (IdentifierAdmissionWork) Format

func (IdentifierAdmissionWork) Format(s fmt.State, _ rune)

Format hides command, proof and transaction correlation.

func (IdentifierAdmissionWork) IdentifierAuthorityVersion

func (h IdentifierAdmissionWork) IdentifierAuthorityVersion(p IdentifierAdmissionContributor) (uint64, error)

IdentifierAuthorityVersion returns the original command's identifier epoch during initial admission and only this transaction's persisted successor at the final check. It does not renew the original session snapshot or authorize adopting a newer external epoch. Only the selected live participant may call.

func (IdentifierAdmissionWork) MarshalJSON

func (IdentifierAdmissionWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects export of invocation authority.

func (IdentifierAdmissionWork) MarshalText

func (IdentifierAdmissionWork) MarshalText() ([]byte, error)

MarshalText rejects implicit export of invocation authority.

func (IdentifierAdmissionWork) Query

func (h IdentifierAdmissionWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query executes a bounded trusted primary query. Rows must close before the callback returns. This is not a sandbox for arbitrary caller SQL.

func (IdentifierAdmissionWork) RequireActiveCredential

RequireActiveCredential uses the existing kernel credential owner checks and retains its share locks until the original transaction closes.

func (IdentifierAdmissionWork) RequireActiveDirectoryAuthority

RequireActiveDirectoryAuthority checks exact configured global and tenant epochs.

func (IdentifierAdmissionWork) RequireActiveUserAuthorization

RequireActiveUserAuthorization borrows the existing authorization owner's implementation; it neither decides policy nor claims organization authority.

type IdentifierChangeCascadeConfig

type IdentifierChangeCascadeConfig = IdentifierRemovalCascadeConfig

IdentifierChangeCascadeConfig uses the same bounded consumer-policy shape as removal. Its definition is separately purpose-bound; retain a distinct policy version when both definitions share one tenant's policy namespace.

type IdentifierMutationMigrationSource

type IdentifierMutationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

IdentifierMutationMigrationSource appends non-reversible identifier retirement history to immutable Base migrations. Version must be allocated after every Base version. Existing directory data and explicit-column readers/writers are unchanged. Load performs no SQL; use the migrations Runner. Zero is invalid. Retirement history must outlive old proofs/imports; destructive down is absent.

func (IdentifierMutationMigrationSource) Load

Load returns independently owned forward-only history. Cancellation is preserved; nil/empty Base and non-successor versions fail closed. This schema does not authorize mutations or establish cleanup/retention policy.

type IdentifierNormalizationMigrationSource

type IdentifierNormalizationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

IdentifierNormalizationMigrationSource appends exact comparison-policy identity to directory rows. Empty/zero keeps historical records explicitly unbound; no canonical bytes or verification are rewritten. The feature that needs normalization binding must select this forward migration before writes. Base must include the identifier history; Version follows every Base version. It owns no runner, connection or transaction, and supplies no destructive down.

func (IdentifierNormalizationMigrationSource) Load

Load copies immutable forward history. Missing base, non-successor version, nil context or cancellation returns no migrations. SQL installation remains the existing migrations Runner's responsibility.

type IdentifierRemovalCascadeConfig

type IdentifierRemovalCascadeConfig struct {
	PolicyVersion     uint64
	Reasons           []string
	MaximumDuration   time.Duration
	ConsumerContracts map[string]StatusConsumerContract
}

IdentifierRemovalCascadeConfig freezes the exact ten-consumer pending admission. Contract fingerprints describe reviewed semantic contracts, not running adapters or acknowledgements. PolicyVersion shares the identity-owned cascade policy namespace with StatusUnitOfWorkConfig; incompatible stored definitions at the same tenant/version fail closed. Reasons are registered codes, not free text. MaximumDuration is microsecond-exact, positive and <=10y.

type IdentifierRemovalCascadeMigrationSource

type IdentifierRemovalCascadeMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

IdentifierRemovalCascadeMigrationSource extends the existing identity-owned cascade admission tables, not a second lifecycle journal. Base must contain StatusMigrationSource and Version must follow all base history. Existing status policy, rows, pending consumers and authority dimensions are unchanged. This migration admits identifier removal; consumer acknowledgement/closure is separate.

func (IdentifierRemovalCascadeMigrationSource) Load

Load returns owned forward-only history without IO or destructive rollback. Missing prerequisite, invalid ordering and cancellation fail closed.

type KernelAuthorityKeySet

type KernelAuthorityKeySet struct{ Global, Tenant, User, Identifier, Credential string }

KernelAuthorityKeySet contains dimension-qualified version-one scope keys for the five kernel-owned lifecycle epochs. Credential means the user's aggregate credential epoch, not an individual credential ID or version. Keys correlate identity state and must not be logged. This structural projection contains no versions, active-state evidence or authorization.

func KernelAuthorityKeys

func KernelAuthorityKeys(q DirectoryAuthorityQuery, user identity.UserID) (KernelAuthorityKeySet, error)

KernelAuthorityKeys derives exact scope keys from canonical UTF-8 directory IDs under DirectoryAuthorityQuery's existing bounded, non-control policy. Global binds the configured deployment ID; Tenant binds its tenant ID; User, Identifier and Credential bind tenant/user in that order. Each key is its dimension plus ":v1:" and an unpadded base64url SHA-256 of "golib.identity.authority.v1\x00", followed by the dimension and scope components, each framed by its big-endian uint16 byte length. Every component is at most128 bytes before conversion. No normalization or delimiter joining occurs. Historical caller-invented keys are not silently migrated.

The IDs remain necessary for primary lookups: hashing creates no independent identity, authentication proof or validity lease. Invalid input returns a redacted identity.InvalidInputError and zero output. No IO or callback occurs; callers must keep inputs immutable during this concurrency-safe operation.

func (KernelAuthorityKeySet) Format

func (KernelAuthorityKeySet) Format(s fmt.State, _ rune)

Format redacts internal correlation keys.

func (KernelAuthorityKeySet) MarshalJSON

func (KernelAuthorityKeySet) MarshalJSON() ([]byte, error)

MarshalJSON rejects accidental export of correlation keys.

func (KernelAuthorityKeySet) MarshalText

func (KernelAuthorityKeySet) MarshalText() ([]byte, error)

MarshalText rejects implicit export of correlation keys.

type LifecycleContributor

type LifecycleContributor interface {
	Contributor
	PersistLifecycle(context.Context, Work) error
}

LifecycleContributor is the open outbox-owned same-Work lifecycle phase. Only the Coordinator invokes it after complete staging. Implementations persist these safe events atomically with the mutation, preserve deterministic IDs and reject different bytes under an existing ID. They must not retain Work, close or begin transactions, invoke caller hooks or perform network I/O. Success means staging, not commit or downstream consumer acknowledgement.

type LifecyclePlan

type LifecyclePlan struct {
	EventType     string
	EventIndex    uint16
	BeforeVersion uint64
	AfterVersion  uint64
}

LifecyclePlan declares one kernel or registered feature lifecycle event before SQL. Kernel EventType is the exact supported command mapping. Kernel and record-targeted sequential feature versions use the checked successor. Kernel user creation and identifier attachment start at 0; account linking starts at 0 only for a never-used ID and otherwise preserves its tombstone predecessor. Other kernel operations start above 0. Record-free features use zero versions; explicit snapshot-import features preserve a positive source version from an absent-local predecessor of 0. Native owners fence that absence and source authority; lifecycle declaration grants neither. The full cascade consumer/checkpoint profile is separate and still pending.

type MFAAttemptDisposition

type MFAAttemptDisposition uint8

MFAAttemptDisposition is a provisional denial decision, never a successful factor proof. Unknown values abort; the coordinator owns the sole commit.

const (
	// MFAAttemptUnchanged rolls back all provisional effects. It grants no
	// authentication and permits no inference that the submitted code is valid.
	MFAAttemptUnchanged MFAAttemptDisposition = iota + 1
	// MFAAttemptDenied commits the native shared-budget charge together with
	// required denial audits and the original terminal command result.
	MFAAttemptDenied
)

type MFACompletionContributor

type MFACompletionContributor interface {
	FeatureCommitContributor
	ValidateMFACompletion(identity.Command, CapabilityPlan, MFACompletionPlan) error
}

MFACompletionContributor is the native owner of the session-producing alternative of a named factor operation. Validation is pure and bounded and must match the real verified continuation, original primary/browser/remember scope and immutable factor submission to this command and declaration. Apply must fence current authority and shared attempts, verify/consume the selected factor, advance the continuation and persist the original-primary session effects in this same Work. CheckFeatureCommit rechecks current validity and absolute expiry. No method or scalar declaration itself authenticates a factor.

type MFACompletionPlan

type MFACompletionPlan struct {
	ID                                                identity.CommandID
	UserID                                            identity.UserID
	ScopeDigest                                       [32]byte
	PolicyVersion, FactorVersion, ContinuationVersion uint64
}

MFACompletionPlan binds a named factor operation to the original partial authentication scope. It is metadata, not a factor proof or permission to issue a session. The native owner must authenticate the original scope, verify the selected factor, fence these versions and persist completion with session effects in the sole Work. ID is the original child capability ID; ContinuationVersion is the expected shared-attempt version, never a reset. Nil preserves existing feature profiles, including enrollment verification.

func (MFACompletionPlan) Format

func (MFACompletionPlan) Format(s fmt.State, _ rune)

Format hides correlated authentication metadata.

func (MFACompletionPlan) MarshalJSON

func (MFACompletionPlan) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit export; the kernel owns the historical codec.

type MFAContinuationPlan

type MFAContinuationPlan struct {
	ID            identity.CommandID
	UserID        identity.UserID
	ScopeDigest   [32]byte
	PolicyVersion uint64
	FactorVersion uint64
	IssuedAt      time.Time
	ExpiresAt     time.Time
}

MFAContinuationPlan declares a challenge-only result of admitting an original password/UV-passkey primary or consuming a magic-link proof. ScopeDigest binds immutable scope, including browser, primary proof, methods and remember policy. The child capability has this ID and expiry. Factor and policy versions must be fenced by their actual owners; this declaration proves neither MFA nor authentication. It cannot accompany signup or session creation. Times are UTC whole seconds, with a five-minute maximum and no extension beyond the original primary proof. Preparation alone may omit ID/digest/times together while fixing the selected user/policy/factor. The journal-owned generator supplies those original child fields once. Ordinary execution and history require the complete declaration; restoration preserves it and adds exactly one original-generation child.

func (MFAContinuationPlan) Format

func (MFAContinuationPlan) Format(s fmt.State, _ rune)

Format hides subject and retained scope metadata from diagnostics.

func (MFAContinuationPlan) MarshalJSON

func (MFAContinuationPlan) MarshalJSON() ([]byte, error)

MarshalJSON forbids exporting retained scope through general serialization. The coordinator's private canonical codec owns historical representation.

type MFALoginSendCounterContributor

type MFALoginSendCounterContributor interface {
	FeatureInputAdmissionContributor
	MFALoginSendCounterSubject(identity.Command) (identity.UserID, error)
}

MFALoginSendCounterContributor lends the authenticated original subject only to native counter execution. The registered MFA owner must bind it to the complete immutable command, signed child, confirmed factor and original consumed-primary browser. Its input-admission and commit checks separately fence current authority before charging/generation and after bounded waits. This pure method must not perform IO, sample a clock, mutate state or grant proof/consumption authority. Configuration and original inputs are immutable; independent calls may overlap. It does not introduce a session or journal.

type MFAOTPAttemptBinding

type MFAOTPAttemptBinding struct {
	Command     identity.CommandBinding
	Plan        MFACompletionPlan
	OTP         OTPAttemptPlan
	Fingerprint [32]byte
	Generation  uint64
}

MFAOTPAttemptBinding retains both exact frozen declarations and original command correlation. It is neither factor authority nor successful proof.

func (MFAOTPAttemptBinding) Format

func (MFAOTPAttemptBinding) Format(s fmt.State, _ rune)

Format redacts original continuation/challenge correlation.

func (MFAOTPAttemptBinding) MarshalJSON

func (MFAOTPAttemptBinding) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit correlation export.

func (MFAOTPAttemptBinding) MarshalText

func (MFAOTPAttemptBinding) MarshalText() ([]byte, error)

MarshalText rejects implicit correlation export.

type MFAOTPAttemptContributor

type MFAOTPAttemptContributor interface {
	MFACompletionContributor
	PrepareMFAOTPAttempt(context.Context, MFAOTPAttemptWork) (MFAAttemptDisposition, error)
	RecordMFAOTPAttemptDenial(context.Context, MFAOTPAttemptWork) error
}

MFAOTPAttemptContributor couples the original shared MFA budget to the real OTP owner's counted denial in the sole coordinator transaction. Preparation authenticates consumed-primary/browser custody, locks current authority and the original continuation, then reserves protected risk before any comparison. Unchanged permits only that transaction's native OTP callback; it is not proof. Denied records risk denial without comparing or charging a factor attempt. RecordMFAOTPAttemptDenial runs only after actual native OTP denial and debits the same locked continuation once. Never compare OTP here, consume the child, create a session, invoke providers, retain Work or own a transaction. Errors roll back both owners. Instances are comparable and safe for concurrent calls.

type MFAOTPAttemptWork

type MFAOTPAttemptWork struct {
	// contains filtered or unexported fields
}

MFAOTPAttemptWork borrows bounded SQL only during the registered MFA owner's admission/denial callback. It has no OTP comparison, general Work, capability, session or transaction accessor. Copies share serial-use budgets and lifetime; zero, foreign and returned handles deny. Close query rows before returning.

func (MFAOTPAttemptWork) Binding

Binding requires the exact registered instance and active callback lifetime.

func (MFAOTPAttemptWork) DatabaseTime

func (w MFAOTPAttemptWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary UTC without extending original validity.

func (MFAOTPAttemptWork) Exec

func (w MFAOTPAttemptWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec performs native continuation SQL without transaction closure.

func (MFAOTPAttemptWork) Format

func (MFAOTPAttemptWork) Format(s fmt.State, _ rune)

Format redacts borrowed authority and credential custody.

func (MFAOTPAttemptWork) MarshalJSON

func (MFAOTPAttemptWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects callback export.

func (MFAOTPAttemptWork) MarshalText

func (MFAOTPAttemptWork) MarshalText() ([]byte, error)

MarshalText rejects callback export.

func (MFAOTPAttemptWork) NativeCommand

NativeCommand borrows original code/browser custody, never persistence data.

func (MFAOTPAttemptWork) Query

func (w MFAOTPAttemptWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns callback-owned rows; close them before returning.

func (MFAOTPAttemptWork) RequireActiveDirectoryAuthority

func (w MFAOTPAttemptWork) RequireActiveDirectoryAuthority(ctx context.Context, owner MFAOTPAttemptContributor, expected DirectoryAuthorityAdmission) error

RequireActiveDirectoryAuthority fences original global/tenant observations.

func (MFAOTPAttemptWork) RequireOTPDenial

func (w MFAOTPAttemptWork) RequireOTPDenial(owner MFAOTPAttemptContributor) error

RequireOTPDenial proves only that this callback follows the actual native OTP owner's Denied result. It cannot be invoked to fabricate or repeat a charge. The native MFA owner must also retain/check its exact locked continuation.

func (MFAOTPAttemptWork) RequireRecipient

func (w MFAOTPAttemptWork) RequireRecipient(ctx context.Context, owner MFAOTPAttemptContributor, expected RecipientRecord) error

RequireRecipient fences the original user's account/identifier authority.

func (MFAOTPAttemptWork) RequireRecipientCredential

func (w MFAOTPAttemptWork) RequireRecipientCredential(ctx context.Context, owner MFAOTPAttemptContributor, recipient RecipientRecord, expected CredentialAdmission) (time.Time, error)

RequireRecipientCredential additionally fences the original password version and expiry without disclosing general Work or renewing primary freshness.

func (MFAOTPAttemptWork) ReserveCommandCounters

ReserveCommandCounters runs the original native protected-risk owner once, after current browser/authority admission and before the actual OTP comparison.

type MFARecoveryAttemptBinding

type MFARecoveryAttemptBinding struct {
	Command     identity.CommandBinding
	Plan        MFACompletionPlan
	Fingerprint [32]byte
	Generation  uint64
}

MFARecoveryAttemptBinding is immutable original correlation, not authority.

func (MFARecoveryAttemptBinding) Format

func (MFARecoveryAttemptBinding) Format(s fmt.State, _ rune)

Format redacts original credential and continuation correlation.

func (MFARecoveryAttemptBinding) MarshalJSON

func (MFARecoveryAttemptBinding) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit correlation export.

func (MFARecoveryAttemptBinding) MarshalText

func (MFARecoveryAttemptBinding) MarshalText() ([]byte, error)

MarshalText rejects implicit correlation export.

type MFARecoveryAttemptContributor

type MFARecoveryAttemptContributor interface {
	MFACompletionContributor
	RecordMFARecoveryAttemptDenial(context.Context, MFARecoveryAttemptWork) (MFAAttemptDisposition, error)
}

MFARecoveryAttemptContributor owns recovery-code comparison and shared-budget denial in the existing coordinator transaction. Original recovery/browser custody, current account/factor authority and policy must be fenced before comparison. Denied commits only the attempt, protected risk and denial audit; Unchanged rolls back and grants no factor proof. No code burn, child consumption, session issuance, external callback, transaction closure or retained Work is permitted here. Instances must be comparable and concurrency-safe.

type MFARecoveryAttemptWork

type MFARecoveryAttemptWork struct {
	// contains filtered or unexported fields
}

MFARecoveryAttemptWork borrows bounded SQL exclusively during the exact registered recovery callback. Copies share cancellation, budgets and lifetime; use serially and close rows. Zero, foreign and returned handles deny. It has no general Work, transaction, reservation, TOTP or session accessor.

func (MFARecoveryAttemptWork) Binding

Binding requires the exact live registered native recovery owner.

func (MFARecoveryAttemptWork) DatabaseTime

func (w MFARecoveryAttemptWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary UTC without renewing original validity.

func (MFARecoveryAttemptWork) Exec

func (w MFARecoveryAttemptWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec executes bounded trusted factor/continuation SQL, not transaction control.

func (MFARecoveryAttemptWork) Format

func (MFARecoveryAttemptWork) Format(s fmt.State, _ rune)

Format redacts borrowed callback authority.

func (MFARecoveryAttemptWork) MarshalJSON

func (MFARecoveryAttemptWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects borrowed custody export.

func (MFARecoveryAttemptWork) MarshalText

func (MFARecoveryAttemptWork) MarshalText() ([]byte, error)

MarshalText rejects borrowed custody export.

func (MFARecoveryAttemptWork) NativeCommand

NativeCommand lends distinct original recovery/browser custody only here.

func (MFARecoveryAttemptWork) Query

func (w MFARecoveryAttemptWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query lends bounded rows that must close before the callback returns.

func (MFARecoveryAttemptWork) RequireActiveDirectoryAuthority

func (w MFARecoveryAttemptWork) RequireActiveDirectoryAuthority(ctx context.Context, owner MFARecoveryAttemptContributor, expected DirectoryAuthorityAdmission) error

RequireActiveDirectoryAuthority fences original global/tenant epochs before factor locks. Every live failure poisons the sole transaction.

func (MFARecoveryAttemptWork) RequireRecipient

RequireRecipient fences the original selected user/identifier epochs. It grants no recovery proof or session and must precede factor locks.

func (MFARecoveryAttemptWork) RequireRecipientCredential

func (w MFARecoveryAttemptWork) RequireRecipientCredential(ctx context.Context, owner MFARecoveryAttemptContributor, recipient RecipientRecord, expected CredentialAdmission) (time.Time, error)

RequireRecipientCredential fences the original password credential and expiry without changing anonymous journal identity or renewing freshness. Versions must come from authenticated original primary custody; live errors poison the transaction even when a caller ignores them.

func (MFARecoveryAttemptWork) ReserveCommandCounters

ReserveCommandCounters invokes the registered protected-risk owner once, before comparison. Denied forbids comparison; Unchanged rolls the charge back.

type MFATOTPAttemptBinding

type MFATOTPAttemptBinding struct {
	Command     identity.CommandBinding
	Plan        MFACompletionPlan
	Fingerprint [32]byte
	Generation  uint64
}

MFATOTPAttemptBinding contains immutable correlation, not factor authority.

func (MFATOTPAttemptBinding) Format

func (MFATOTPAttemptBinding) Format(s fmt.State, _ rune)

Format redacts command and continuation correlation.

func (MFATOTPAttemptBinding) MarshalJSON

func (MFATOTPAttemptBinding) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit custody export.

func (MFATOTPAttemptBinding) MarshalText

func (MFATOTPAttemptBinding) MarshalText() ([]byte, error)

MarshalText rejects implicit custody export.

type MFATOTPAttemptContributor

type MFATOTPAttemptContributor interface {
	MFACompletionContributor
	RecordMFATOTPAttemptDenial(context.Context, MFATOTPAttemptWork) (MFAAttemptDisposition, error)
}

MFATOTPAttemptContributor owns counted wrong-code denial for the exact native TOTP completion operation. ValidateMFACompletion authenticates original opaque submission, continuation scope and server policy before any transaction. RecordMFATOTPAttemptDenial locks/rechecks current continuation, account and factor authority after the command journal, compares under bounded policy, and charges the shared budget once on denial. It must not consume a child, advance successful replay state, issue a session, mutate kernel tables, invoke external callbacks, retain Work or open/close transactions. Correct comparison returns Unchanged, not proof. Instances are comparable and concurrency-safe.

type MFATOTPAttemptWork

type MFATOTPAttemptWork struct {
	// contains filtered or unexported fields
}

MFATOTPAttemptWork exposes bounded SQL only during the exact native counted callback. Zero, foreign, returned and copied-after-return handles deny. Copies share cancellation, SQL/row budgets and lifetime; use serially and close rows. There is no general Work, transaction, reservation or session accessor.

func (MFATOTPAttemptWork) Binding

Binding requires live callback custody and the exact registered owner.

func (MFATOTPAttemptWork) DatabaseTime

func (w MFATOTPAttemptWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary UTC without extending original validity.

func (MFATOTPAttemptWork) Exec

func (w MFATOTPAttemptWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec executes bounded trusted factor/continuation SQL, not transaction closure.

func (MFATOTPAttemptWork) Format

func (MFATOTPAttemptWork) Format(s fmt.State, _ rune)

Format redacts callback authority and opaque input.

func (MFATOTPAttemptWork) MarshalJSON

func (MFATOTPAttemptWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects callback authority export.

func (MFATOTPAttemptWork) MarshalText

func (MFATOTPAttemptWork) MarshalText() ([]byte, error)

MarshalText rejects callback authority export.

func (MFATOTPAttemptWork) NativeCommand

NativeCommand borrows original opaque custody only for this counted callback.

func (MFATOTPAttemptWork) Query

func (w MFATOTPAttemptWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query lends bounded rows that must be closed before the callback returns.

func (MFATOTPAttemptWork) RequireActiveDirectoryAuthority

func (w MFATOTPAttemptWork) RequireActiveDirectoryAuthority(ctx context.Context, owner MFATOTPAttemptContributor, expected DirectoryAuthorityAdmission) error

RequireActiveDirectoryAuthority fences the original pre-decision global and tenant epochs during the exact native counted callback, before factor locks. It does not disclose general Work or refresh authority. Live failures poison the sole transaction even if ignored; zero/foreign/returned custody denies.

func (MFATOTPAttemptWork) RequirePasskeyCredential

func (w MFATOTPAttemptWork) RequirePasskeyCredential(ctx context.Context, owner MFATOTPAttemptContributor, expected CredentialAdmission) (time.Time, error)

RequirePasskeyCredential applies the identical exact-subject eligibility check before counted TOTP comparison/denial. It borrows only this original native callback's scope, SQL budget and cancellation. No child is consumed, factor compared, attempt charged or authentication granted. A current credential is a prerequisite to charging; failures poison the transaction.

func (MFATOTPAttemptWork) RequireRecipient

func (w MFATOTPAttemptWork) RequireRecipient(ctx context.Context, owner MFATOTPAttemptContributor, expected RecipientRecord) error

RequireRecipient fences the original selected user/identifier and security epochs during counted denial, using the same directory owner as successful completion. Take this before factor locks. It neither authenticates a code nor permits a session; live denied checks poison the transaction.

func (MFATOTPAttemptWork) RequireRecipientCredential

func (w MFATOTPAttemptWork) RequireRecipientCredential(ctx context.Context, owner MFATOTPAttemptContributor, recipient RecipientRecord, expected CredentialAdmission) (time.Time, error)

RequireRecipientCredential fences the original password credential before counted TOTP comparison or charging. It retains anonymous journal scope; selected-user eligibility is local to the locked directory read. Expected versions must come from authenticated original primary custody. No proof, session, fresh lease, independent transaction or general Work is exposed. Expiry is checked after locks; every live denial poisons the transaction.

func (MFATOTPAttemptWork) ReserveCommandCounters

ReserveCommandCounters invokes the exact registered protected-risk owner once inside this counted attempt transaction, after native browser/current authority admission and before factor comparison. Denied must return native MFAAttemptDenied without comparing a code. Wrong-code denial commits risk, budget and audit together; correct-code Unchanged rolls all of them back. No child, session, lifecycle or private transaction is invoked here.

type MagicLinkConsumptionContributor

type MagicLinkConsumptionContributor interface {
	FeatureCommitContributor
	ValidateMagicLinkConsumption(identity.Command, CapabilityPlan) error
}

MagicLinkConsumptionContributor is the closed native passwordless login owner. Validation must exhaustively match original verified grant/issuance, pre-auth, callback, recipient and prospective-session custody to the command and declared one-use input; it is pure, bounded and must not perform IO. Apply and CheckFeatureCommit enforce current recipient/factor/risk authority, original exclusive expiry and complete session effects in the sole Work. Signature/origin validation belongs to the real capability owner, not these scalar declarations. No projection or method implementation grants authority.

type MagicLinkMFAChallengeContributor

type MagicLinkMFAChallengeContributor interface {
	MagicLinkConsumptionContributor
	ValidateMagicLinkMFAChallenge(identity.Command, MFAContinuationPlan) error
}

MagicLinkMFAChallengeContributor owns the challenge-only alternative, not a session-producing login. Validation must match the complete original MFA scope and command in addition to the primary grant. It is pure and bounded. ApplyFeature must recheck enrolled methods and current policy/factor authority, persist the original continuation and stage its exact child issuance without calling a session issuer. CheckFeatureCommit must repeat current authority and absolute-expiry checks. Persistence, pre-auth transition, one-use, audit and challenge lifecycle share the sole Work; missing authority denies. Implementing the interface conveys no proof or independently committable work.

type MagicLinkRegistrationContributor

type MagicLinkRegistrationContributor interface {
	MagicLinkConsumptionContributor
	MagicLinkRegistration(identity.Command) (MagicLinkRegistrationIntent, error)
}

MagicLinkRegistrationContributor is the native consuming owner of a prepared prospective creation. The pure bounded mapping must retain original grant, browser, mailbox-policy and prospective identity custody without retargeting. Current policy, risk, factor and session checks remain its protected phases. Implementing this interface alone grants no invocation or SQL authority.

type MagicLinkRegistrationDomain

type MagicLinkRegistrationDomain struct {
	// contains filtered or unexported fields
}

MagicLinkRegistrationDomain borrows the enlisted kernel repository. It owns neither a transaction nor a retry/goroutine. Native registration requires exact consuming, creation, lifecycle and recovery contributor composition. Immutable configuration permits concurrent calls with separate owned Work.

func NewMagicLinkRegistrationDomain

func NewMagicLinkRegistrationDomain(r *Repository, c MagicLinkRegistrationDomainConfig) (*MagicLinkRegistrationDomain, error)

NewMagicLinkRegistrationDomain performs bounded structural validation without IO or policy callbacks. Install identifier/registration histories and the MagicLinkRegistrationMigrationSource first. This does not enable signup.

func (*MagicLinkRegistrationDomain) AdmitProspectiveMailbox

func (d *MagicLinkRegistrationDomain) AdmitProspectiveMailbox(ctx context.Context, w Work, p FeaturePreparationContributor, command identity.Command, canonical string) (bool, error)

AdmitProspectiveMailbox classifies a canonical email only during the exact native magic-link original-request preparation invocation. It checks every occupant and live retirement under the kernel's tenant fence, not merely eligible verified recipients. False is a private no-delivery selection, never an existence disclosure. Missing retained keys and infrastructure errors deny. The native owner supplies its email-owned canonical projection; this method neither normalizes nor proves possession. It allocates no future IDs, stages no effect and creates no user, verification, factor state or reusable proof. Generate future IDs only after the coordinator acknowledges generation start. Preparation releases its locks before generation, so final request Apply must repeat SelectProspectiveRecipient and consumption must recheck creation. Zero, foreign, reconstructed-command and non-preparation invocations deny. Borrow Work serially, close all rows, and retain neither Work nor command.

func (*MagicLinkRegistrationDomain) Apply

Apply creates a genuinely passwordless user and verified email only during the exact registered native Apply, after provisional original capability consumption in this Work. The frozen prospective IDs, policy and complete kernel field set must match. Existing/retired ownership conflicts deny rather than retarget. All writes and command-linked recovery evidence share the sole transaction. The returned user is provisional; audit, outbox, factors, session and final proof consumption must still commit together. Failure poisons Work.

func (MagicLinkRegistrationDomain) Format

func (MagicLinkRegistrationDomain) MarshalJSON

func (MagicLinkRegistrationDomain) MarshalJSON() ([]byte, error)

func (*MagicLinkRegistrationDomain) Recipient

Recipient reads the newly created verified email inside the same native consuming invocation. It cannot select a pre-existing or retargeted account, grant proof authority or renew original capability/session expiry.

func (*MagicLinkRegistrationDomain) RequireProspectiveRecipient

RequireProspectiveRecipient fences an unused email and prospective IDs during the original native magic-link request Apply. It creates no user, verification or empty MFA state. The same kernel tenant/retirement policy used by creation owns collision admission; consumption must independently create and recheck. Its frozen intent binds staged signed issuance, not current authentication. Errors poison Work. Call only in the serial invocation with the enlisted repository and retain neither Work nor intent across a callback.

func (*MagicLinkRegistrationDomain) SelectProspectiveRecipient

SelectProspectiveRecipient classifies prospective request availability under the enlisted kernel transaction's existing tenant and retirement fences. Canonical occupancy or live retirement returns false without poisoning Work, so the native request can commit its neutral acknowledgement without delivery. It never reveals the occupant or treats an unverified/blocked occupant as absent. Structural future-ID conflicts, invalid intent and unavailable authority remain errors that poison Work. A true result admits only this original request's prospective issuance: it creates no account or reusable availability proof. Preparation-time absence cannot replace this request Apply fence; consumption independently enforces creation eligibility. Call serially with the enlisted contributor; retain neither Work nor intent across callbacks.

type MagicLinkRegistrationDomainConfig

type MagicLinkRegistrationDomainConfig struct {
	ComparisonProfile            string
	EmailPossessionPolicyVersion uint64
	CurrentIdentifierKeyVersion  uint32
	RetainedIdentifierKeys       map[uint32][32]byte
}

MagicLinkRegistrationDomainConfig selects retained identifier retirement keys and explicit mailbox-possession policy version. These are server composition, never values chosen by an unauthenticated request. Construction copies keys.

func (MagicLinkRegistrationDomainConfig) Format

func (MagicLinkRegistrationDomainConfig) MarshalJSON

func (MagicLinkRegistrationDomainConfig) MarshalJSON() ([]byte, error)

type MagicLinkRegistrationIntent

type MagicLinkRegistrationIntent struct {
	Creation                     identity.CreateUserCommand
	Identifier                   identity.Identifier
	ComparisonProfile            string
	EmailPossessionPolicyVersion uint64
}

MagicLinkRegistrationIntent is a prospective passwordless account creation. Identifier must be an initially unverified non-primary email. Its eventual verification requires original capability consumption and explicit mailbox policy, not the caller's Verified flag. No password credential is created.

func (MagicLinkRegistrationIntent) Format

func (MagicLinkRegistrationIntent) MarshalJSON

func (MagicLinkRegistrationIntent) MarshalJSON() ([]byte, error)

type MagicLinkRegistrationLifecycleContributor

type MagicLinkRegistrationLifecycleContributor interface {
	LifecycleContributor
	PersistMagicLinkRegistration(context.Context, Work) error
}

MagicLinkRegistrationLifecycleContributor persists the normal authentication lifecycle and separate account-creation lifecycle in the existing outbox, atomically with the same consuming command. It must use both staged profiles and may not close Work, retain it, or perform network IO.

type MagicLinkRegistrationMigrationSource

type MagicLinkRegistrationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

MagicLinkRegistrationMigrationSource extends existing registration evidence for passwordless creation under the original magic-link consume command. Base must install PasswordRegistrationMigrationSource and its acceptance suffix. Version must follow Base. This installs storage, not signup policy, email-possession authority or permission to create an identity.

func (MagicLinkRegistrationMigrationSource) Load

Load preserves old history and returns a forward-only suffix without SQL IO.

type MagicLinkRegistrationPlan

type MagicLinkRegistrationPlan struct {
	UserID                       identity.UserID
	IdentifierID                 string
	CreationDigest               [32]byte
	EmailPossessionPolicyVersion uint64
	CreationEventIndex           uint16
}

MagicLinkRegistrationPlan declares the prospective account and identifier, exact prepared creation, and admitted email-possession policy. It contains no address, credential or caller attributes. The IDs cannot be retargeted when an account appears between request and consumption. Declaration is not proof of email possession, policy admission or completed creation. Execution remains closed until the native creation and lifecycle phases are enlisted.

type ManagedEmailPrevious

type ManagedEmailPrevious struct {
	ID                                     identity.IdentifierID
	CanonicalAddress                       string
	IdentifierVersion, VerificationVersion uint64
	Primary, AllowInitialPrimary           bool
}

ManagedEmailPrevious is original encrypted change intent, not authority. The email owner chooses it; the kernel repeats these exact facts under the complete partition lock before attaching or promoting the candidate.

func (ManagedEmailPrevious) Format

func (ManagedEmailPrevious) Format(s fmt.State, _ rune)

Format redacts notification intent and correlated predecessor metadata.

func (ManagedEmailPrevious) MarshalJSON

func (ManagedEmailPrevious) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit sensitive original-intent export.

type ManagedEmailVerificationContributor

type ManagedEmailVerificationContributor interface {
	FeatureCommitContributor
	ManagedEmailVerification(identity.Command) (ManagedEmailVerificationIntent, *EmailAttachmentDomain, error)
}

ManagedEmailVerificationContributor owns original managed intent and current policy/factor/risk admission. Only the kernel writes identifier rows. The pure mapper must match every owned field and the exact enlisted domain; Apply and final checks must enforce the original proof/time without renewing authority.

type ManagedEmailVerificationIntent

type ManagedEmailVerificationIntent struct {
	Change                              identity.IdentifierChange
	CanonicalAddress, ComparisonProfile string
	RequestCommandID                    identity.CommandID
	Previous                            ManagedEmailPrevious
}

ManagedEmailVerificationIntent freezes exact pending-address predecessors and original request. Link profiles select authenticated management provenance; the distinct OTP profile selects its independently issued OTP send command. Neither selection carries caller/proof authority. The initial managed link profile verifies a pending1/1 address without a primary swap, session issuance, email sender or signup reinterpretation.

func (ManagedEmailVerificationIntent) Format

Format redacts mailbox and correlated request/account metadata.

func (ManagedEmailVerificationIntent) MarshalJSON

func (ManagedEmailVerificationIntent) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit sensitive intent export.

type MigrationSource

type MigrationSource struct{}

MigrationSource supplies this adapter's complete immutable forward-only history to go-migrations. The zero value is usable and concurrent-safe. Load performs no I/O, creates no ledger and does not execute SQL. Compose it with the owned migrations PostgreSQL backend and Runner, not a private runner. The initial atomic install requires an unoccupied identity schema; conflicting unmanaged objects fail rather than silently becoming owned tables.

func (MigrationSource) Load

Load returns independently owned migration values or no history on failure. A nonnil context is required; cancellation and deadline errors are preserved. Migrations never provide destructive down SQL. Use reviewed forward fixes.

Example
package main

import (
	"context"
	"fmt"

	identitydb "github.com/faustbrian/go-identity/postgres"
)

func main() {
	history, err := (identitydb.MigrationSource{}).Load(context.Background())
	if err != nil {
		panic(err)
	}
	fmt.Println(history[0].Version(), history[0].Name(), history[0].DownSQL() == "")
}
Output:
1 identity_users true

type OAuthConsentContributor

type OAuthConsentContributor interface {
	FeatureCommitContributor
	ValidateOAuthConsent(identity.Command) error
}

OAuthConsentContributor is the closed native password/device OAuth consent owner. Pure validation exhaustively matches original consent ID/version, client and current command custody. Apply locks and writes the actual consent in the sole Work, recording its successful provisional mutation; final commit checks repeat original authority. The declaration is not consent or a grant.

type OAuthConsentLifecycleContributor

type OAuthConsentLifecycleContributor interface {
	LifecycleContributor
	PersistOAuthConsent(context.Context, Work) error
}

OAuthConsentLifecycleContributor atomically persists the grant's primary lifecycle and distinct consent event through the existing outbox. Use StagedOAuthConsent for the secondary record; no arbitrary caller payload, private transaction, retained Work, network IO or independent journal exists.

type OAuthConsentMutation

type OAuthConsentMutation struct {
	ID                          string
	BeforeVersion, AfterVersion uint64
	Created                     bool
}

OAuthConsentMutation is the trusted native owner's actual successful SQL mutation, still provisional. ID identifies the independent consent, never the grant. Creation is0→1; reconfirmation preserves ID and advances its own retained positive version. The value alone grants neither authority nor event staging.

type OAuthContinuationPreparationContributor

type OAuthContinuationPreparationContributor interface {
	FeaturePreparationContributor
	OAuthContinuationHandoff(identity.Command) (previous identity.CommandID, requested bool, err error)
	AdvanceOAuthContinuation(context.Context, Work, identity.Command, identity.CommandID) error
}

OAuthContinuationPreparationContributor opts the canonical OAuth native continuation owner into a new attempt AFTER its previous attempt is proven terminal reauthentication-required/NotCommitted by this coordinator. The pure selector returns zero/false for ordinary preparation. Advance runs only after ordinary current admission and locked same-human/flow predecessor proof, in the SAME transaction as the acknowledged preparation-start marker.

Advance must first call RequireOAuthContinuationHandoff, then CAS only its existing active continuation's attempt pointer from previous to this command. It must preserve the original token/request/expiry and require genuine newer authentication, original/current authority and the original deadline after waits. No code, consent, grant authority, effect or independent outcome store may be created here. No mutation is permitted in AdmitFeaturePreparation. Pending, unknown, committed and other failed predecessors never unlock it. Failed/ambiguous start never authorizes generation or another handoff. Advance is synchronous, bounded and callback-only; close rows, retain no Work, perform no external IO/crypto/generation/retries or transaction closure.

type OAuthReauthenticationMigrationSource

type OAuthReauthenticationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

OAuthReauthenticationMigrationSource appends the closed OAuth age-expiry terminal classification after installed terminal/preparation history. Prior migration bytes, receipts and all existing shape checks remain unchanged. Apply before selecting fresh-login continuation handoff, using readers that understand OAuthReauthenticationRequiredError. It adds no retry/outcome store or new command lifecycle and has no destructive down migration.

func (OAuthReauthenticationMigrationSource) Load

Load returns owned forward history without IO. Missing base, empty history, out-of-order/colliding versions and cancellation return no partial history.

type OAuthReauthenticationRequiredError

type OAuthReauthenticationRequiredError struct{}

OAuthReauthenticationRequiredError classifies an OAuth authentication-age denial, distinct from provider failure. Only its coordinator-owned terminal NotCommitted receipt proves noncommit; this error alone does not. It carries no credential or retry permission. Only a separately admitted genuine authentication may request the closed continuation handoff below. Install OAuthReauthenticationMigrationSource before enabling this profile; existing terminal receipts and their classifications remain immutable.

func (OAuthReauthenticationRequiredError) Error

type OTPApplyWork

type OTPApplyWork struct {
	// contains filtered or unexported fields
}

OTPApplyWork grants exact-owner primary reads during current checks, not mutation, submitted-code access or transaction closure. Zero/foreign/returned handles deny; copies share callback lifetime. Use serially and close rows.

func (OTPApplyWork) Binding

Binding returns live exact-owner frozen custody, not release proof.

func (OTPApplyWork) CommandSpec

CommandSpec returns code-free original feature scope to the exact owner.

func (OTPApplyWork) DatabaseTime

func (w OTPApplyWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary UTC without renewing challenge validity.

func (OTPApplyWork) Format

func (OTPApplyWork) Format(s fmt.State, _ rune)

Format redacts invocation authority.

func (OTPApplyWork) MarshalJSON

func (OTPApplyWork) MarshalJSON() ([]byte, error)

MarshalJSON denies authority serialization.

func (OTPApplyWork) MarshalText

func (OTPApplyWork) MarshalText() ([]byte, error)

MarshalText denies authority serialization.

func (OTPApplyWork) PreAuthCookie

PreAuthCookie lends only the actual submitted pre-auth bearer to the exact live owner, independently of the code-free CommandSpec. It grants neither cookie possession proof nor authentication; the owner must derive and check the original flow commitment against primary session state. Missing, foreign, zero and returned handles return zero and InvalidInput. Do not retain, log, persist or serialize the borrowed bearer. No OTP code is exposed.

func (OTPApplyWork) Query

func (w OTPApplyWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query grants bounded trusted primary reads; close rows before returning.

func (OTPApplyWork) RequireActiveCredential

func (h OTPApplyWork) RequireActiveCredential(ctx context.Context, p OTPReservationContributor, expected CredentialAdmission) (time.Time, error)

RequireActiveCredential checks original credential eligibility under locks in the protected transaction. Primary time is not a validity lease; denial returns zero time and poisons Work, including an ignored error.

func (OTPApplyWork) RequireActiveDirectoryAuthority

func (h OTPApplyWork) RequireActiveDirectoryAuthority(ctx context.Context, p OTPReservationContributor, expected DirectoryAuthorityAdmission) error

RequireActiveDirectoryAuthority checks original directory epochs under locks in the protected transaction. Only the live exact owner may call; failures poison Work. This does not establish session/pre-auth authority or consume OTP.

func (OTPApplyWork) RequireActiveUserAuthority

func (h OTPApplyWork) RequireActiveUserAuthority(ctx context.Context, p OTPReservationContributor, expected UserAuthorityAdmission) error

RequireActiveUserAuthority checks original user security epochs under primary locks in the protected transaction without a credential reference. Live denial poisons Work. Success alone neither authenticates nor consumes OTP.

func (OTPApplyWork) RequireActiveUserAuthorization

func (h OTPApplyWork) RequireActiveUserAuthorization(ctx context.Context, p OTPReservationContributor, expected UserAuthorizationAdmission) error

RequireActiveUserAuthorization checks the original user's authorization epoch through the existing owner in the protected transaction. It is not a policy decision. Failure poisons Work; all other applicable dimensions remain required.

func (OTPApplyWork) RequireFeatureOrigin

func (w OTPApplyWork) RequireFeatureOrigin(ctx context.Context, otpOwner OTPReservationContributor, featureOwner FeatureExecutionContributor, origin Work) error

RequireFeatureOrigin correlates an opaque native completion receipt with its originating protected Work during the final phone-reset OTP check. Both contributor instances must be the exact registered owners, and origin must share the live private Work state, original plan and generation. Identical scalar metadata from another Work is insufficient. Only a completed phone Apply is accepted; this grants no SQL, factor verdict or mutation authority. A trusted receipt owner may retain origin privately until this transaction closes, solely for this guard; callers must not retain or reuse general Work access. Zero, foreign, returned, canceled and other-profile handles deny. No IO, contributor callback, code comparison or freshness renewal occurs.

func (OTPApplyWork) SessionToken

SessionToken lends only the separately submitted session bearer to the exact live owner. Missing, pre-auth, foreign, zero and returned handles deny. This grants no authentication or validity; the owner must derive the original lookup digest and check every applicable primary authority. Never retain, log, persist or serialize the borrowed token. Neither code nor native Command is exposed; release/recovery phases deliberately have no bearer accessor.

type OTPAttemptBinding

type OTPAttemptBinding struct {
	Command     identity.CommandBinding
	Plan        OTPAttemptPlan
	Fingerprint [32]byte
	Generation  uint64
}

OTPAttemptBinding exposes exact frozen linkage and authoritative complete command fingerprint. Generation is positive and this counted phase permits only a first owner, never takeover of an unresolved one-time reservation. Copies are owned scalars, not authority, proof or public response data.

func (OTPAttemptBinding) Format

func (OTPAttemptBinding) Format(s fmt.State, _ rune)

Format hides attempt/command linkage.

func (OTPAttemptBinding) MarshalJSON

func (OTPAttemptBinding) MarshalJSON() ([]byte, error)

MarshalJSON denies export of private attempt custody.

func (OTPAttemptBinding) MarshalText

func (OTPAttemptBinding) MarshalText() ([]byte, error)

MarshalText rejects implicit conversion of private attempt custody.

type OTPAttemptContributor

type OTPAttemptContributor interface {
	RecoveryContributor
	ValidateOTPAttemptCommand(identity.Command, OTPAttemptPlan) error
	RecordOTPAttemptDenial(context.Context, OTPAttemptWork) (OTPAttemptDisposition, error)
}

OTPAttemptContributor owns the native pre-reservation wrong-code phase. Pure validation authenticates the complete server-issued attempt/command binding against retained keys and trusted configuration. RecordOTPAttemptDenial locks the exact challenge after the already locked command, checks current scope, authority, lockout, expiry and expected version, performs bounded comparison, and records exactly one wrong-attempt increment with exhaustion as required. It must retain server attempt ID and complete canonical fingerprint and reject changed-input re-entry without mutation. The coordinator handles command replay BEFORE invocation, and owns audits, terminal result and sole commit.

Never reserve/finalize a challenge, modify command/audit tables, use private transactions, run provider/caller callbacks, retain handles or close Work. Instances must be comparable and concurrency-safe; each Work is serial-use. Correct checks and consuming use remain separate native phases.

type OTPAttemptDisposition

type OTPAttemptDisposition uint8

OTPAttemptDisposition is a provisional counted-attempt decision, never proof of successful verification or commitment. Unknown/zero values abort the unit.

const (
	// OTPAttemptUnchanged records no denial; all provisional SQL is rolled back.
	// It grants no reservation, allowance, authentication or reusable precheck.
	OTPAttemptUnchanged OTPAttemptDisposition = iota + 1
	// OTPAttemptDenied requires the native owner to persist one exact attempt
	// charge/result proposal. The coordinator commits it with the aborted command
	// and required audits. Cross-scope/unknown denials must not charge another row.
	OTPAttemptDenied
	// OTPAttemptChecked proposes a persisted non-consuming metered-check result.
	// Only the explicit check phase accepts it; it grants no proof or reservation.
	OTPAttemptChecked
)

type OTPAttemptMode

type OTPAttemptMode uint8

OTPAttemptMode keeps separately metered checks distinct from consuming use. Zero and unknown modes are invalid; this tag conveys no verification result.

const (
	// OTPCheck counts a non-consuming comparison and never grants a reservation.
	OTPCheck OTPAttemptMode = iota + 1
	// OTPConsume selects counted verification and generation-bound reservation.
	OTPConsume
)

type OTPAttemptPlan

type OTPAttemptPlan struct {
	AttemptID             string
	AttemptFingerprint    [32]byte
	FingerprintKeyVersion uint32
	ChallengeID           string
	ScopeDigest           [32]byte
	DigestKeyVersion      uint32
	ExpectedVersion       uint64
	Mode                  OTPAttemptMode
}

OTPAttemptPlan freezes one server-prepared logical submission. AttemptID is random128 canonical base64url, not a client idempotency key. The native OTP owner must authenticate/reconstruct the complete attempt against immutable command custody and current configuration before SQL. AttemptFingerprint is its keyed submission binding, NOT the coordinator's authoritative fingerprint. ScopeDigest binds the complete purpose/subject/channel/workflow/authorization scope; no destination, code, pepper or authorization bearer is stored here. Every version is positive. ChallengeID is bounded to 256 UTF-8 bytes without controls. Changes mean different command intent, never a retry of this one.

These are declarations, not proof, current authority or durable outcomes. Native counted denial/reservation and domain phases remain mandatory and are not activated by this plan. Copies own all scalars; do not mutate caller input concurrently with preparation. Formatting redacts and serialization rejects.

func (OTPAttemptPlan) Format

func (OTPAttemptPlan) Format(s fmt.State, _ rune)

Format hides private attempt/challenge linkage for every format verb.

func (OTPAttemptPlan) MarshalJSON

func (OTPAttemptPlan) MarshalJSON() ([]byte, error)

MarshalJSON prevents accidentally exporting private attempt custody.

func (OTPAttemptPlan) MarshalText

func (OTPAttemptPlan) MarshalText() ([]byte, error)

MarshalText rejects implicit wire conversion of private attempt custody.

type OTPAttemptWork

type OTPAttemptWork struct {
	// contains filtered or unexported fields
}

OTPAttemptWork grants bounded SQL only within one coordinator-owned counted callback. Zero, foreign and returned handles deny. Copies share cancellation, row/SQL budgets and callback lifetime. Close rows before return, use serially, and never treat database time as renewal. There is no driver, transaction, constructor, closure, reservation or general Work accessor.

func (OTPAttemptWork) Binding

Binding validates active lifetime and exact registered instance ownership.

func (OTPAttemptWork) DatabaseTime

func (w OTPAttemptWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary UTC without changing original validity.

func (OTPAttemptWork) Exec

func (w OTPAttemptWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec performs trusted attempt/challenge SQL, never transaction closure.

func (OTPAttemptWork) Format

func (OTPAttemptWork) Format(s fmt.State, _ rune)

Format redacts invocation state and secret custody.

func (OTPAttemptWork) MarshalJSON

func (OTPAttemptWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of invocation authority.

func (OTPAttemptWork) MarshalText

func (OTPAttemptWork) MarshalText() ([]byte, error)

MarshalText rejects implicit serialization of invocation authority.

func (OTPAttemptWork) NativeCommand

func (w OTPAttemptWork) NativeCommand(owner OTPAttemptContributor) (identity.Command, error)

NativeCommand lends the original opaque submission only to this native owner for one counted locked comparison. Never persist or log it; discard copies.

func (OTPAttemptWork) Query

func (w OTPAttemptWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns bounded callback-owned rows; close them before return.

func (OTPAttemptWork) RequireActiveCredential

func (h OTPAttemptWork) RequireActiveCredential(ctx context.Context, p OTPAttemptContributor, expected CredentialAdmission) (time.Time, error)

RequireActiveCredential checks exact original user/identifier/credential epochs and credential eligibility in the denial transaction. Expiry uses primary time after locks; zero time accompanies denial. Failures poison live Work. Success is neither authentication nor session/pre-auth authority.

func (OTPAttemptWork) RequireActiveDirectoryAuthority

func (h OTPAttemptWork) RequireActiveDirectoryAuthority(ctx context.Context, p OTPAttemptContributor, expected DirectoryAuthorityAdmission) error

RequireActiveDirectoryAuthority compares original command-bound global and tenant epochs under primary share locks. Only the exact live OTP owner may call; any denial poisons the denial transaction even if ignored. Expectations must come from authenticated frozen intent, not newly observed versions. It creates no proof, session/pre-auth authority or renewable validity lease.

func (OTPAttemptWork) RequireActiveUserAuthority

func (h OTPAttemptWork) RequireActiveUserAuthority(ctx context.Context, p OTPAttemptContributor, expected UserAuthorityAdmission) error

RequireActiveUserAuthority locks the command-bound primary user and compares active status and all three original security epochs without requiring a credential reference. Only the exact live owner may call; denial poisons Work even if ignored. It never refreshes intent or grants authentication authority. Credential-bearing workflows must additionally check their exact credential.

func (OTPAttemptWork) RequireActiveUserAuthorization

func (h OTPAttemptWork) RequireActiveUserAuthorization(ctx context.Context, p OTPAttemptContributor, expected UserAuthorizationAdmission) error

RequireActiveUserAuthorization compares the frozen effective user's epoch through the existing authorization owner. It never chooses actor identity, decides policy or refreshes proof. All live invocation failures poison Work.

type OTPExecutionContributor

type OTPExecutionContributor interface {
	OTPReservationContributor
	CheckOTP(context.Context, OTPApplyWork) error
	FinalizeOTP(context.Context, OTPFinalizeWork) error
	ReleaseOTP(context.Context, OTPReleaseWork) error
}

OTPExecutionContributor opts the exact reservation owner into protected use. CheckOTP checks current purpose, subject, workflow, authorization, target versions, reserved generation and exclusive primary expiry under exclusion. It never compares or meters the submitted code again. FinalizeOTP rechecks those invariants and CASes reserved to finalized in the same transaction as protected effects and the result. ReleaseOTP terminally releases only after coordinator-proven rollback or unanimous primary noncommit evidence; expiry or lease loss alone is not proof. Methods retain no handles, close every row, open no private transaction, make no network calls and perform no retries. Instances support concurrent callbacks; each supplied handle is serial-use.

type OTPFinalizeWork

type OTPFinalizeWork struct {
	// contains filtered or unexported fields
}

OTPFinalizeWork grants terminal CAS in the protected transaction, never code comparison, private commit or release. Copies share callback lifetime; use serially and close rows. Zero/foreign/returned handles deny.

func (OTPFinalizeWork) Binding

Binding returns exact current-generation custody, not noncommit proof.

func (OTPFinalizeWork) CommandSpec

CommandSpec returns code-free immutable scope, never the submitted code.

func (OTPFinalizeWork) DatabaseTime

func (w OTPFinalizeWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime cannot renew original expiry or invocation lifetime.

func (OTPFinalizeWork) Exec

func (w OTPFinalizeWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec performs bounded trusted terminal SQL without transaction closure.

func (OTPFinalizeWork) Format

func (OTPFinalizeWork) Format(s fmt.State, _ rune)

Format redacts terminal authority.

func (OTPFinalizeWork) MarshalJSON

func (OTPFinalizeWork) MarshalJSON() ([]byte, error)

MarshalJSON denies authority serialization.

func (OTPFinalizeWork) MarshalText

func (OTPFinalizeWork) MarshalText() ([]byte, error)

MarshalText denies authority serialization.

func (OTPFinalizeWork) PreAuthCookie

PreAuthCookie lends the separately submitted original bearer only during exact-owner finalization. Semantics and secret-handling requirements match OTPApplyWork.PreAuthCookie; release and recovery never receive this access.

func (OTPFinalizeWork) Query

func (w OTPFinalizeWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query reads bounded callback-owned rows; close them before returning.

func (OTPFinalizeWork) RequireActiveCredential

func (h OTPFinalizeWork) RequireActiveCredential(ctx context.Context, p OTPReservationContributor, expected CredentialAdmission) (time.Time, error)

RequireActiveCredential rechecks frozen credential eligibility before terminal finalization, using primary time after locks. Denial returns zero time and poisons Work. It never renews original validity or issues a session.

func (OTPFinalizeWork) RequireActiveDirectoryAuthority

func (h OTPFinalizeWork) RequireActiveDirectoryAuthority(ctx context.Context, p OTPReservationContributor, expected DirectoryAuthorityAdmission) error

RequireActiveDirectoryAuthority rechecks frozen directory epochs before terminal finalization in the protected transaction. Failure poisons Work. Returned handles deny without affecting later phases. Release deliberately has no such gate: proven noncommit must permit release after revocation.

func (OTPFinalizeWork) RequireActiveUserAuthority

func (h OTPFinalizeWork) RequireActiveUserAuthority(ctx context.Context, p OTPReservationContributor, expected UserAuthorityAdmission) error

RequireActiveUserAuthority rechecks original user security epochs before finalization; live denial poisons Work. Returned handles cannot poison later invocations. Proven noncommit release intentionally has no such live gate.

func (OTPFinalizeWork) RequireActiveUserAuthorization

func (h OTPFinalizeWork) RequireActiveUserAuthorization(ctx context.Context, p OTPReservationContributor, expected UserAuthorizationAdmission) error

RequireActiveUserAuthorization rechecks the original user's epoch through its existing owner before terminal finalization. Failure poisons Work; it never changes epochs, chooses an actor or substitutes for a policy decision.

func (OTPFinalizeWork) SessionToken

SessionToken lends the original session bearer to its registered reservation owner during finalization. Its custody and authority rules are identical to OTPApplyWork.SessionToken. It does not provide the submitted code.

type OTPMeteredCheckContributor

type OTPMeteredCheckContributor interface {
	OTPAttemptContributor
	RecordOTPMeteredCheck(context.Context, OTPAttemptWork) (OTPAttemptDisposition, error)
}

OTPMeteredCheckContributor is an explicit additive non-consuming profile. The same registered native owner must authenticate complete original custody, charge both check and total budgets, and persist the proposal within Work. Existing denial-only contributors do not acquire this capability. The coordinator owns audit, stable receipt, replay and the sole commit. A checked result cannot reserve OTP, invoke protected domain work or change a session.

type OTPReleaseWork

type OTPReleaseWork struct {
	// contains filtered or unexported fields
}

OTPReleaseWork grants terminal release only after authoritative noncommit proof. Binding carries the exact reserved predecessor; recovery uses its successor, rollback its unchanged owner. Expiry alone grants no proof. Copies share lifetime; zero/foreign/returned handles deny. Use serially.

func (OTPReleaseWork) Binding

Binding checks exact registered ownership and frozen linkage.

func (OTPReleaseWork) DatabaseTime

func (w OTPReleaseWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary UTC; expiry alone is not release proof.

func (OTPReleaseWork) Exec

func (w OTPReleaseWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec performs terminal release SQL, never private transaction closure.

func (OTPReleaseWork) Format

func (OTPReleaseWork) Format(s fmt.State, _ rune)

Format redacts proof-bound authority.

func (OTPReleaseWork) MarshalJSON

func (OTPReleaseWork) MarshalJSON() ([]byte, error)

MarshalJSON denies authority serialization.

func (OTPReleaseWork) MarshalText

func (OTPReleaseWork) MarshalText() ([]byte, error)

MarshalText denies authority serialization.

func (OTPReleaseWork) Query

func (w OTPReleaseWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query reads bounded primary rows; close them before callback return.

type OTPReservationBinding

type OTPReservationBinding struct {
	Command                        identity.CommandBinding
	Plan                           OTPAttemptPlan
	Fingerprint                    [32]byte
	Generation, PreviousGeneration uint64
}

OTPReservationBinding is private frozen correlation, not verification or commitment proof. Positive Generation is the current owner; PreviousGeneration is zero for initial reserve or the exact predecessor for a successor CAS.

func (OTPReservationBinding) Format

func (OTPReservationBinding) Format(s fmt.State, _ rune)

Format hides attempt and command linkage.

func (OTPReservationBinding) MarshalJSON

func (OTPReservationBinding) MarshalJSON() ([]byte, error)

MarshalJSON denies private custody export.

func (OTPReservationBinding) MarshalText

func (OTPReservationBinding) MarshalText() ([]byte, error)

MarshalText denies implicit private custody export.

type OTPReservationContributor

type OTPReservationContributor interface {
	OTPAttemptContributor
	ReserveOTP(context.Context, OTPReservationWork) error
	RebindOTP(context.Context, OTPReservationWork) error
}

OTPReservationContributor owns counted correct verification and exact predecessor transfer in the sole coordinator's reservation transaction. ReserveOTP locks the declared issued challenge after the command, verifies current purpose/subject/channel/workflow/authorization, exclusive database expiry, expected version and digest-key version, then compares the opaque code once under the native bounded attempt policy. It binds the server attempt, complete command fingerprint, generation and target versions atomically. Wrong-code charges use RecordOTPAttemptDenial, not this rollback path. RebindOTP authenticates the original submission but never compares again; it CASes the exact prior reserved generation and complete original linkage. Missing, terminal, expired or mismatched rows deny without partial transfer. Neither method consumes, releases, renews validity, invokes network/provider callbacks, opens transactions, closes Work or retains any handle. Instances are comparable and concurrency-safe; handles are serial callback-only SQL. This phase set alone does not enable Begin or domain/recovery release.

type OTPReservationWork

type OTPReservationWork struct {
	// contains filtered or unexported fields
}

OTPReservationWork grants bounded SQL to one exact enlisted OTP owner during reserve/rebind. Zero, foreign and returned handles deny. Copies share callback lifetime, context and row/SQL budgets, with no driver, transaction closure or ordinary Work accessor. Close rows before returning; use serially.

func (OTPReservationWork) Binding

Binding requires live callback lifetime and exact registered instance.

func (OTPReservationWork) DatabaseTime

func (w OTPReservationWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary UTC; it does not renew challenge or owner expiry.

func (OTPReservationWork) Exec

func (w OTPReservationWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec executes bounded trusted challenge SQL, never transaction closure.

func (OTPReservationWork) Format

func (OTPReservationWork) Format(s fmt.State, _ rune)

Format hides invocation authority and code custody.

func (OTPReservationWork) MarshalJSON

func (OTPReservationWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects invocation serialization.

func (OTPReservationWork) MarshalText

func (OTPReservationWork) MarshalText() ([]byte, error)

MarshalText rejects invocation serialization.

func (OTPReservationWork) NativeCommand

NativeCommand lends the original immutable opaque submission to that owner only. Reserve may compare once; rebind must not compare or meter it again.

func (OTPReservationWork) Query

func (w OTPReservationWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns bounded rows that must be closed before callback return.

func (OTPReservationWork) RequireActiveCredential

func (h OTPReservationWork) RequireActiveCredential(ctx context.Context, p OTPReservationContributor, expected CredentialAdmission) (time.Time, error)

RequireActiveCredential checks frozen credential eligibility during exact owner reserve/rebind, with primary time after locks and zero time on denial. Failures poison Work; success neither reserves an OTP nor authenticates.

func (OTPReservationWork) RequireActiveDirectoryAuthority

func (h OTPReservationWork) RequireActiveDirectoryAuthority(ctx context.Context, p OTPReservationContributor, expected DirectoryAuthorityAdmission) error

RequireActiveDirectoryAuthority checks frozen directory epochs during exact owner reserve/rebind. Semantics and denial poisoning match OTPAttemptWork; original authority must not be refreshed during successor takeover.

func (OTPReservationWork) RequireActiveUserAuthority

func (h OTPReservationWork) RequireActiveUserAuthority(ctx context.Context, p OTPReservationContributor, expected UserAuthorityAdmission) error

RequireActiveUserAuthority checks original user security epochs during exact owner reserve/rebind. Semantics match OTPAttemptWork; takeover cannot renew expectations. Locks last until transaction end and live denial poisons Work.

func (OTPReservationWork) RequireActiveUserAuthorization

func (h OTPReservationWork) RequireActiveUserAuthorization(ctx context.Context, p OTPReservationContributor, expected UserAuthorizationAdmission) error

RequireActiveUserAuthorization checks the frozen effective user's epoch during exact owner reserve/rebind. It uses the existing owner, poisons live Work on failure and makes no policy decision or freshness renewal.

type OrganizationInvitationConsumptionContributor

type OrganizationInvitationConsumptionContributor interface {
	FeatureCommitContributor
	ValidateOrganizationInvitationConsumption(identity.Command, CapabilityPlan) error
}

OrganizationInvitationConsumptionContributor is the closed native invitation owner. Pure validation matches the original verified grant, invitation, recipient, organization and command; scalar declarations are not proof. ApplyFeature must fence current recipient/session/organization/policy and persist invitation acceptance plus membership in the sole Work. Its commit check repeats current authority and original exclusive expiry. The capability participant alone verifies and atomically consumes the original proof.

type OrganizationInvitationIssuanceContributor

type OrganizationInvitationIssuanceContributor interface {
	FeaturePreparationContributor
	FeatureCommitContributor
	ValidateOrganizationInvitationIssuance(identity.Command, CommandPlan) error
}

OrganizationInvitationIssuanceContributor owns the closed invitation-send and invitation-resend workflows. Preparation validates current genuine owner/session, organization, verified recipient and pending limits before acknowledged token generation. Validation is pure; generated proof/address custody is authenticated and encrypted by the existing preparation owner. Apply and final commit check repeat current authority; issuance and delivery share the sole transaction.

type OrganizationInvitationLifecycleContributor

type OrganizationInvitationLifecycleContributor interface {
	LifecycleContributor
	PersistOrganizationInvitation(context.Context, Work) error
}

OrganizationInvitationLifecycleContributor persists invitation acceptance and its distinct membership-created event atomically through the existing outbox. Neither callback may close/retain Work or perform network IO. The secondary event must come from StagedOrganizationInvitationMembership.

type OrganizationInvitationMembership

type OrganizationInvitationMembership struct {
	OrganizationID              string
	UserID                      identity.UserID
	BeforeVersion, AfterVersion uint64
}

OrganizationInvitationMembership is the trusted native owner's provisional successful membership mutation, never caller authority or a commit receipt. BeforeVersion is the actual retained tombstone version (zero only for a new member); AfterVersion is its checked successor, not the invitation's version.

type OrganizationInvitationOriginPlan

type OrganizationInvitationOriginPlan struct {
	OrganizationID      string
	OrganizationVersion uint64
}

OrganizationInvitationOriginPlan preserves the original invitation-send organization in the existing frozen command declaration. It is historical correlation, never current membership, permission or an execution lease. Native owners must supply the same values as the immutable original command's organization.id and organization.version fields before preparation starts.

type PasskeyMFAChallengeContributor

type PasskeyMFAChallengeContributor interface {
	FeatureCommitContributor
	ValidatePasskeyMFAChallenge(identity.Command, MFAContinuationPlan) error
}

PasskeyMFAChallengeContributor is the native challenge-only UV assertion owner. Pure bounded validation must bind the real verifier-issued transition, original browser, selected subject, primary expiry and exact child scope. ApplyFeature consumes the genuine ceremony and persists original primary provenance, continuation and child atomically in the sole Work, without a session. Current account/credential/passkey/policy/factor/risk and original expiry must be fenced both in Apply and CheckFeatureCommit. Implementing this interface does not itself authenticate a passkey, factor or browser.

type PasskeyRegistrationContributor

type PasskeyRegistrationContributor interface {
	FeatureCommitContributor
	PasskeyRegistration(identity.Command) (PasskeyRegistrationIntent, error)
}

PasskeyRegistrationContributor is the trusted native signup owner. Its pure bounded mapping retains the exact original prospective creation. This grants no invocation authority; real WebAuthn verification, risk, pre-auth custody, authorization, MFA initialization and session effects remain its obligations.

type PasskeyRegistrationDomain

type PasskeyRegistrationDomain struct {
	// contains filtered or unexported fields
}

PasskeyRegistrationDomain borrows the exact enlisted repository and sole coordinator Work. It has no transaction, pool, retry or goroutine of its own. Immutable composition supports concurrent calls with independent owned Work.

func NewPasskeyRegistrationDomain

func NewPasskeyRegistrationDomain(r *Repository) (*PasskeyRegistrationDomain, error)

NewPasskeyRegistrationDomain validates composition without IO. Install the credential and PasskeyRegistrationMigrationSource histories before use. Construction enables no public signup route or authentication authority.

func (*PasskeyRegistrationDomain) Apply

Apply creates only the original prospective active user, admitted attributes and initial passkey reference during the exact native signup Apply. Existing subjects, including blocked/deleted ones, conflict without resurrection. It creates no email, password, identifier or recovery method. Actual WebAuthn verification must precede this call, and protocol credential finalization, required authority/MFA/session effects, audit and both lifecycles must follow in this same Work. Returned User is provisional, not authentication or commit. Any live rejection poisons Work, including an ignored duplicate call.

func (PasskeyRegistrationDomain) Format

func (PasskeyRegistrationDomain) Format(s fmt.State, _ rune)

func (PasskeyRegistrationDomain) MarshalJSON

func (PasskeyRegistrationDomain) MarshalJSON() ([]byte, error)

type PasskeyRegistrationIntent

type PasskeyRegistrationIntent struct {
	Creation   identity.CreateUserCommand
	Credential identity.CredentialRef
}

PasskeyRegistrationIntent describes one prospective passkey-only account. Creation must contain already admitted attributes and a trusted generated user ID. Credential is an initial passkey-owned reference, not WebAuthn key material. Neither value proves registration, user verification or permission to create an account. The original anonymous-flow command remains the sole durable operation; Creation uses the structural kernel shape for validation.

func (PasskeyRegistrationIntent) Format

func (PasskeyRegistrationIntent) Format(s fmt.State, _ rune)

Format prevents disclosure of prospective account attributes and scope.

func (PasskeyRegistrationIntent) MarshalJSON

func (PasskeyRegistrationIntent) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit export of prospective account creation.

type PasskeyRegistrationLifecycleContributor

type PasskeyRegistrationLifecycleContributor interface {
	LifecycleContributor
	PersistPasskeyRegistration(context.Context, Work) error
}

PasskeyRegistrationLifecycleContributor persists the canonical credential creation and separate account creation lifecycles in the existing outbox, inside the sole signup command. It must use both staged profiles, never retain Work, close the transaction or perform network IO.

type PasskeyRegistrationMigrationSource

type PasskeyRegistrationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

PasskeyRegistrationMigrationSource extends the existing original-command registration evidence for passkey-only creation. Base must include credential references, PasswordRegistrationMigrationSource and its acceptance suffix. Install selected historical magic-link/username suffixes before this forward successor. Their disposition arms and all populated rows remain intact; no workflow is enabled by the schema alone. Version follows every Base version.

func (PasskeyRegistrationMigrationSource) Load

Load returns copied forward-only history without SQL IO or implicit backfill. Missing prerequisites are errors when the real migration is applied.

type PasskeyRegistrationPlan

type PasskeyRegistrationPlan struct {
	UserID             identity.UserID
	CredentialID       identity.CredentialID
	CreationDigest     [32]byte
	CreationEventIndex uint16
}

PasskeyRegistrationPlan freezes one prospective passkey-only creation in the original anonymous verification command. It is neither a WebAuthn proof nor signup permission. The native owner must enlist the creation and outbox phases.

type PasskeySignupSessionLifecycleContributor

type PasskeySignupSessionLifecycleContributor interface {
	PasskeyRegistrationLifecycleContributor
	PersistPasskeySignupSession(context.Context, Work) error
}

PasskeySignupSessionLifecycleContributor additionally persists the exact explicitly staged session creation alongside account and credential events. The coordinator requires this trait once session staging is selected; an old account-only contributor aborts instead of silently omitting a required event. Persist all three through the same Work without IO outside that transaction.

type PasswordHashUpgradeIntent

type PasswordHashUpgradeIntent struct {
	Admission           CredentialAdmission
	ExpectedUserVersion uint64
}

PasswordHashUpgradeIntent freezes independent predecessor versions for a hash-only upgrade inside the original password-signin command. It contains no hash, password, proof or grant. The native password owner must verify the original bytes and prepare bounded replacement material before opening Work. User aggregate, security epochs and credential record versions are distinct.

func (PasswordHashUpgradeIntent) Format

func (PasswordHashUpgradeIntent) Format(s fmt.State, _ rune)

Format redacts predecessor metadata for every formatting verb.

func (PasswordHashUpgradeIntent) MarshalJSON

func (PasswordHashUpgradeIntent) MarshalJSON() ([]byte, error)

MarshalJSON refuses general-purpose serialization of transaction metadata.

func (PasswordHashUpgradeIntent) MarshalText

func (PasswordHashUpgradeIntent) MarshalText() ([]byte, error)

MarshalText refuses general-purpose serialization of transaction metadata.

type PasswordHashUpgradeReceipt

type PasswordHashUpgradeReceipt struct {
	CommandID                                     identity.CommandID
	Credential                                    identity.CredentialRef
	BeforeUserVersion, AfterUserVersion           uint64
	BeforeAuthorityVersion, AfterAuthorityVersion uint64
	BeforeCredentialVersion                       uint64
}

PasswordHashUpgradeReceipt is provisional kernel-owned successor metadata. Only the original signin journal's committed outcome proves durability. Advancing credential authority invalidates predecessor-bound sessions; this receipt cannot preserve them, grant a session or renew any validity evidence.

func (PasswordHashUpgradeReceipt) Format

Format redacts provisional successor metadata for every formatting verb.

func (PasswordHashUpgradeReceipt) MarshalJSON

func (PasswordHashUpgradeReceipt) MarshalJSON() ([]byte, error)

MarshalJSON refuses to export provisional transaction metadata.

func (PasswordHashUpgradeReceipt) MarshalText

func (PasswordHashUpgradeReceipt) MarshalText() ([]byte, error)

MarshalText refuses to export provisional transaction metadata.

type PasswordMFAChallengeContributor

type PasswordMFAChallengeContributor interface {
	FeatureCommitContributor
	ValidatePasswordMFAChallenge(identity.Command, MFAContinuationPlan) error
}

PasswordMFAChallengeContributor is the closed native challenge-only password owner. Validation must match original password/browser custody, the signed comparison record, selected user, policy/factor authority and unchanged child scope; it is pure and bounded. ApplyFeature rechecks current credential, account, policy and factor authority, commits any exact hash upgrade and original password evidence, advances pre-auth and persists the continuation and its child without creating a session. CheckFeatureCommit repeats original expiry and live authority fences. All effects share the sole Work. The child cannot outlive original password/pre-auth evidence. No synthetic primary capability or session/proof obtained from projected metadata is permitted. Implementing this interface grants no authentication or transaction authority.

type PasswordRegistrationDomain

type PasswordRegistrationDomain struct {
	// contains filtered or unexported fields
}

PasswordRegistrationDomain owns only the kernel part of native signup. It borrows the exact enlisted repository and pool; it owns no transaction, store, goroutine, retry or resource lifetime. Zero denies. Immutable composition is concurrent-safe. Applications use the native password service, not this seam.

func NewPasswordRegistrationDomain

func NewPasswordRegistrationDomain(r *Repository, c PasswordRegistrationDomainConfig) (*PasswordRegistrationDomain, error)

NewPasswordRegistrationDomain validates explicit composition without IO or callbacks. Install the existing credential/retirement histories and additive PasswordRegistrationMigrationSource before use. This grants no signup policy.

func (*PasswordRegistrationDomain) Apply

Apply creates the user/attributes, unverified identifier and enabled initial password reference through the original signup Work. The exact native participant, command custody, scope, comparison profile and complete intent must match. Repeated/foreign/changed invocations poison Work. Canonical value uniqueness and retirement cooldown are checked under the existing tenant fence before writing. The returned User is provisional, not authentication. The password participant must persist its material before returning; required audit/outbox, native recovery and the sole coordinator establish durability.

func (*PasswordRegistrationDomain) ApplyOrAccept

ApplyOrAccept is the opt-in anonymous signup registration branch. A true accepted result contains no User and must not produce password material, sessions, verification credentials or delivery. The coordinator alone commits the original neutral acknowledgement and required security effects.

func (PasswordRegistrationDomain) Format

func (PasswordRegistrationDomain) MarshalJSON

func (PasswordRegistrationDomain) MarshalJSON() ([]byte, error)

type PasswordRegistrationDomainConfig

type PasswordRegistrationDomainConfig struct {
	ComparisonProfile           string
	CurrentIdentifierKeyVersion uint32
	RetainedIdentifierKeys      map[uint32][32]byte
}

PasswordRegistrationDomainConfig selects the same retained identifier-reuse keys used by identifier removal. Missing keys deny while live retirement history references them. ComparisonProfile is the exact versioned identifier owner's policy identity, not client input. Construction copies the key map.

func (PasswordRegistrationDomainConfig) Format

func (PasswordRegistrationDomainConfig) MarshalJSON

func (PasswordRegistrationDomainConfig) MarshalJSON() ([]byte, error)

type PasswordRegistrationIntent

type PasswordRegistrationIntent struct {
	Creation          identity.CreateUserCommand
	Identifier        identity.Identifier
	Credential        identity.CredentialRef
	ComparisonProfile string
	// Username optionally reserves one supplementary, initially unverified
	// username alongside the required email. Zero preserves legacy registration.
	// The native feature must supply the exact normalization binding and include
	// the returned fields in its original command; this is not a second signup.
	Username identity.Identifier
}

PasswordRegistrationIntent contains prepared structural creation and one owner-canonicalized, initially unverified channel identifier and password reference, optionally with one supplementary username in the same creation. Creation uses the existing structural command shape solely for validation; the durable command remains identity.password.signup. All versions start at one. It contains no password, hash, possession proof or authentication grant. Attributes must already be admitted by the identity field policy. The native password owner remains responsible for HIBP, risk, pre-auth and material.

func (PasswordRegistrationIntent) Format

func (PasswordRegistrationIntent) MarshalJSON

func (PasswordRegistrationIntent) MarshalJSON() ([]byte, error)

type PasswordRegistrationMigrationSource

type PasswordRegistrationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

PasswordRegistrationMigrationSource appends immutable original-command domain evidence, not a second command journal. Allocate Version after every Base migration, including credential references and identifier retirements. The binding survives payload pruning and proves only the exact original effect. Load performs no SQL; apply with the owned migrations Runner. Zero denies.

func (PasswordRegistrationMigrationSource) Load

Load preserves complete Base bytes and existing populated state; it returns independently owned forward-only history. Earlier cancellation wins. No destructive downgrade, implicit backfill or inferred existing signup occurs.

type PasswordSignupAcceptanceMigrationSource

type PasswordSignupAcceptanceMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

PasswordSignupAcceptanceMigrationSource appends the optional anonymous signup branch to existing registration evidence. Base must include the immutable PasswordRegistrationMigrationSource history. Version follows every base migration. Existing creation receipts and all old migration bytes remain unchanged. Apply with the migrations Runner; Load performs no database IO. Old readers fail closed on the new NULL subject arm rather than selecting an existing account. There is no destructive downgrade or historical inference.

func (PasswordSignupAcceptanceMigrationSource) Load

Load returns independently owned forward-only history. Cancellation wins; missing base, out-of-order versions and malformed history deny before SQL.

type PhoneChangeCascadeMigrationSource

type PhoneChangeCascadeMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

PhoneChangeCascadeMigrationSource extends the existing cascade tables for atomic verified-phone replacement. Base must retain the phone-removal and identifier-removal predecessors and Version must follow all installed history. Apply this forward-only migration before selecting replacement; it creates no journal, acknowledgement authority or active workflow by itself.

func (PhoneChangeCascadeMigrationSource) Load

Load copies history and appends bounded constraint changes without IO.

type PhoneChangeContributor

PhoneChangeContributor supplies exact original change intent. The native owner authenticates recent proof, session/CSRF, current factors/risk and usable independent recovery before code comparison and again at final commit. Only the kernel writes replacement/retirement and only OTP consumes the SMS code.

type PhoneChangeDomain

type PhoneChangeDomain struct {
	// contains filtered or unexported fields
}

PhoneChangeDomain borrows the enlisted directory and immutable policies. Its closure custody also hides keys from nested diagnostics that bypass Format. It owns no pool, transaction, callbacks, timers or goroutines.

func NewPhoneChangeDomain

func NewPhoneChangeDomain(r *Repository, c PhoneChangeDomainConfig) (*PhoneChangeDomain, error)

NewPhoneChangeDomain copies explicit native policy without IO or side effects. Its constructor does not enable replacement, issue SMS or grant possession.

func (*PhoneChangeDomain) Format

func (*PhoneChangeDomain) Format(s fmt.State, _ rune)

Format hides borrowed native owners and retained key policies.

func (*PhoneChangeDomain) MarshalJSON

func (*PhoneChangeDomain) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit owner/key export.

type PhoneChangeDomainConfig

type PhoneChangeDomainConfig struct {
	Directory PhoneEnrollmentDomainConfig
	Cascade   IdentifierChangeCascadeConfig
}

PhoneChangeDomainConfig selects the existing phone directory/recycling policy and exact pending identifier-change consumers. It creates no second writer, journal, OTP engine or acknowledgement authority.

func (PhoneChangeDomainConfig) Format

func (PhoneChangeDomainConfig) Format(s fmt.State, _ rune)

Format redacts ordinary configuration formatting; exported startup fields remain sensitive and must not be enclosed in diagnostics that bypass methods.

func (PhoneChangeDomainConfig) MarshalJSON

func (PhoneChangeDomainConfig) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit key/configuration export.

type PhoneChangeIntent

type PhoneChangeIntent struct {
	Change                       identity.IdentifierChange
	PreviousNumber               string
	PreviousNormalizationProfile string
	PreviousNormalizationVersion uint32
	SendCommandID                identity.CommandID
	Reason                       string
}

PhoneChangeIntent freezes replacement of an existing verified phone and the original SMS issuance. Change is ReplaceVerifiedPhone, not attach or caller-asserted verification. The native phone owner must authenticate original new-number OTP possession, recent action proof, session and current recovery/risk policy. Fields are sensitive original intent and confer no storage authority.

func (PhoneChangeIntent) Format

func (PhoneChangeIntent) Format(s fmt.State, _ rune)

Format hides original phone numbers and correlated identity/command fields.

func (PhoneChangeIntent) MarshalJSON

func (PhoneChangeIntent) MarshalJSON() ([]byte, error)

MarshalJSON requires explicit protected persistence projection.

type PhoneEnrollmentContributor

type PhoneEnrollmentContributor interface {
	FeatureCommitContributor
	PhoneEnrollment(identity.Command) (PhoneEnrollmentIntent, *PhoneEnrollmentDomain, error)
}

PhoneEnrollmentContributor supplies original phone intent to the coordinator. ApplyFeature must admit and consume the original action-bound proof, current session, factors and risk, and persist its OTP and delivery atomically in Work. Only the kernel writes the pending identifier. Final CheckFeatureCommit keeps the original validity bounds; it must not readmit a newer directory epoch.

type PhoneEnrollmentDomain

type PhoneEnrollmentDomain struct {
	// contains filtered or unexported fields
}

PhoneEnrollmentDomain retains the exact borrowed kernel writer and immutable identifier policy. It owns no pool, transaction, retry, callback or goroutine. Construction alone does not expose an enrollment operation or storage writer.

func NewPhoneEnrollmentDomain

func NewPhoneEnrollmentDomain(r *Repository, c PhoneEnrollmentDomainConfig) (*PhoneEnrollmentDomain, error)

NewPhoneEnrollmentDomain freezes explicit native policy without IO. Install the existing identifier normalization/retirement histories before execution. The native phone workflow must match this profile to its real NumberPolicy; this constructor neither supplies metadata validation nor reserves a number.

func (PhoneEnrollmentDomain) Format

func (PhoneEnrollmentDomain) Format(s fmt.State, _ rune)

Format hides borrowed writer custody and retained policy.

func (PhoneEnrollmentDomain) MarshalJSON

func (PhoneEnrollmentDomain) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit writer/key export.

type PhoneEnrollmentDomainConfig

type PhoneEnrollmentDomainConfig struct {
	NormalizationProfile        string
	NormalizationVersion        uint32
	CurrentIdentifierKeyVersion uint32
	RetainedIdentifierKeys      map[uint32][32]byte
	ReuseCooldown               time.Duration
}

PhoneEnrollmentDomainConfig binds the phone owner's stored normalization identity and explicit recycling policy. Retained reuse keys are copied. The positive microsecond-exact cooldown is at most 365 days; an existing retirement keeps its original expiry. A new metadata profile never rewrites old records.

func (PhoneEnrollmentDomainConfig) Format

Format hides retained reuse keys and correlated storage configuration.

func (PhoneEnrollmentDomainConfig) MarshalJSON

func (PhoneEnrollmentDomainConfig) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit key/configuration export.

type PhoneEnrollmentIntent

type PhoneEnrollmentIntent struct{ Change identity.IdentifierChange }

PhoneEnrollmentIntent is the kernel's original pending-phone input. The phone owner must first validate the number under its exact metadata-bound policy. These fields are sensitive intent, never ownership or authorization.

func (PhoneEnrollmentIntent) Format

func (PhoneEnrollmentIntent) Format(s fmt.State, _ rune)

Format prevents ordinary diagnostics from disclosing number intent.

func (PhoneEnrollmentIntent) MarshalJSON

func (PhoneEnrollmentIntent) MarshalJSON() ([]byte, error)

MarshalJSON requires an explicit protected persistence projection.

type PhonePasswordResetMigrationSource

type PhonePasswordResetMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

PhonePasswordResetMigrationSource appends the exact phone-reset operation to the canonical credential replacement receipt constraint. Base must include CredentialResetMigrationSource; allocate Version after its installed history. All predecessor SQL/checksums and existing password-change/email-reset rows stay unchanged. This enables no recovery workflow or new storage authority.

func (PhonePasswordResetMigrationSource) Load

Load returns forward transactional history without IO or destructive down SQL. Nil/canceled input, empty history and version collisions return no partial history. The existing migration runner owns application and replay.

type PhoneRemovalCascadeMigrationSource

type PhoneRemovalCascadeMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

PhoneRemovalCascadeMigrationSource extends the existing identifier-removal cascade constraint to the exact phone removal operation. Base must include IdentifierRemovalCascadeMigrationSource and every installed predecessor; Version follows them all. Existing status/email rows, checksums, pending consumers and command ownership are preserved. No new journal is created.

func (PhoneRemovalCascadeMigrationSource) Load

Load copies the selected history and appends a forward-only constraint change. It does no IO and enables no workflow or cleanup acknowledgement by itself.

type PhoneRemovalContributor

type PhoneRemovalContributor interface {
	FeatureCommitContributor
	PhoneRemoval(identity.Command) (PhoneRemovalIntent, *PhoneRemovalDomain, error)
}

PhoneRemovalContributor maps original self-removal intent. The native phase owns recent proof, current factors/risk, actual independent recovery eligibility and required notices. Only the kernel writes the exact phone/tombstone and admits the pending cascade. No OTP participant may be selected for removal.

type PhoneRemovalDomain

type PhoneRemovalDomain struct {
	// contains filtered or unexported fields
}

PhoneRemovalDomain borrows the exact enlisted directory and frozen policies. It owns no pool, transaction, worker, callback or lifecycle acknowledgement.

func NewPhoneRemovalDomain

func NewPhoneRemovalDomain(r *Repository, c PhoneRemovalDomainConfig) (*PhoneRemovalDomain, error)

NewPhoneRemovalDomain copies explicit native policy without IO. Install the phone directory and forward phone-removal cascade histories before execution. Construction grants neither a supported workflow nor arbitrary directory IO.

func (PhoneRemovalDomain) Format

func (PhoneRemovalDomain) Format(s fmt.State, _ rune)

Format hides the borrowed writer and retained policy/key custody.

func (PhoneRemovalDomain) MarshalJSON

func (PhoneRemovalDomain) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit native policy export.

type PhoneRemovalDomainConfig

type PhoneRemovalDomainConfig struct {
	Directory PhoneEnrollmentDomainConfig
	Cascade   IdentifierRemovalCascadeConfig
}

PhoneRemovalDomainConfig selects the existing phone directory/recycling and identifier-removal cascade policies. It creates no second writer or journal. Retained reuse keys and complete consumer contracts are copied at construction.

func (PhoneRemovalDomainConfig) Format

func (PhoneRemovalDomainConfig) Format(s fmt.State, _ rune)

Format redacts retained directory keys and cascade policy.

func (PhoneRemovalDomainConfig) MarshalJSON

func (PhoneRemovalDomainConfig) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit configuration export.

type PhoneRemovalIntent

type PhoneRemovalIntent struct {
	Change               identity.IdentifierChange
	CanonicalNumber      string
	NormalizationProfile string
	NormalizationVersion uint32
	Reason               string
}

PhoneRemovalIntent freezes one verified phone, its stored normalization profile and exact directory predecessors. Number and Reason are sensitive original intent, not phone possession, recent proof or recovery eligibility.

func (PhoneRemovalIntent) Format

func (PhoneRemovalIntent) Format(s fmt.State, _ rune)

Format omits original phone, reason and command correlation.

func (PhoneRemovalIntent) MarshalJSON

func (PhoneRemovalIntent) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit sensitive intent export.

type PhoneVerificationContributor

type PhoneVerificationContributor interface {
	FeatureCommitContributor
	FeatureInputAdmissionContributor
	PhoneVerification(identity.Command) (PhoneVerificationIntent, *PhoneEnrollmentDomain, error)
}

PhoneVerificationContributor admits original possession/current authority before OTP comparison or debit and repeats policy/factor/session checks during Apply and final admission. Its pure mapper must return the exact enlisted kernel domain. Only the kernel writes identifier verification; only the OTP participant reserves and consumes the submitted code in that same Work.

type PhoneVerificationIntent

type PhoneVerificationIntent struct {
	Change               identity.IdentifierChange
	CanonicalNumber      string
	NormalizationProfile string
	NormalizationVersion uint32
	EnrollmentCommandID  identity.CommandID
}

PhoneVerificationIntent identifies the exact initially pending phone and its original committed enrollment command. It does not authenticate the caller, code or enrollment; the native owner must restore those from retained custody. Change is Verify only, with pending identifier/verification predecessors 1/1. Number/profile fields compare stored identity; they never re-normalize it.

func (PhoneVerificationIntent) Format

func (PhoneVerificationIntent) Format(s fmt.State, _ rune)

Format redacts phone and original account/command correlations.

func (PhoneVerificationIntent) MarshalJSON

func (PhoneVerificationIntent) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit export of protected intent.

type PreparationMigrationSource

type PreparationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

PreparationMigrationSource appends optional pre-generation custody columns to the existing command journal. It creates no second workflow store and does not enroll historical commands or grant generation/execution authority. Compose with a Base containing the kernel history and an explicit later Version. Install before enabling a preparation-aware native composition; legacy commands and migration checksums remain unchanged. No down SQL exists.

func (PreparationMigrationSource) Load

Load returns independent immutable forward history, without I/O. Nil inputs, empty history and a non-successor version fail; cancellation is preserved.

type PreparedFeatureRecord

type PreparedFeatureRecord struct {
	InputBinding     RequestKeyPreparationBinding
	InputCiphertext  []byte
	OutputGeneration uint64
	OutputCiphertext []byte
}

PreparedFeatureRecord is original encrypted native custody, not a credential, permission, fresh authority or permission to reexecute a command. The exact registered owner must authenticate both envelopes and separately authenticate bearer possession and current authority before using their contents. Returned byte slices are owned by the caller; do not log or serialize them. Preserve InputBinding and OutputGeneration unchanged when restoring original custody.

func (PreparedFeatureRecord) Format

func (PreparedFeatureRecord) Format(s fmt.State, _ rune)

Format hides encrypted custody and correlation from diagnostics.

func (PreparedFeatureRecord) LogValue

func (PreparedFeatureRecord) LogValue() slog.Value

LogValue hides encrypted custody and correlation from structured logs.

func (PreparedFeatureRecord) MarshalJSON

func (PreparedFeatureRecord) MarshalJSON() ([]byte, error)

MarshalJSON rejects accidental persistence or transport of native custody.

func (PreparedFeatureRecord) MarshalText

func (PreparedFeatureRecord) MarshalText() ([]byte, error)

MarshalText rejects accidental textual disclosure of native custody.

type PrivacyExportAdmissionContributor

type PrivacyExportAdmissionContributor interface {
	Contributor
	CheckPrivacyExport(context.Context, PrivacyExportAdmissionWork) error
}

PrivacyExportAdmissionContributor is the registered native session owner's read-only check for a frozen self-service privacy request. Checks must use the original session/version and all applicable primary authority owners. This role cannot attest mutation outcome, refresh evidence, consume proof, write rows, retain Work, open transactions or perform network IO. Its methods must support concurrent invocations with separate serial-use handles.

type PrivacyExportAdmissionWork

type PrivacyExportAdmissionWork struct {
	// contains filtered or unexported fields
}

PrivacyExportAdmissionWork borrows the original generation-bound transaction solely during its exact registered invocation. It exposes bounded reads and existing kernel checks, never writes or closure. Zero/retained handles deny; copies share serial invocation lifetime. Errors on live handles poison the original Work, even when ignored. Initial/final checks cannot renew original session/proof expiry or authoritative evidence. This is not authentication.

func (PrivacyExportAdmissionWork) Command

Command returns an owned projection copy and the terminal-recheck flag only to the exact selected participant. Expected identity/authority/session fields are always the original request, never a newer session or refreshed vector.

func (PrivacyExportAdmissionWork) DatabaseTime

func (h PrivacyExportAdmissionWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary time without restarting any validity interval.

func (PrivacyExportAdmissionWork) Format

Format redacts session/proof/transaction correlations for every verb.

func (PrivacyExportAdmissionWork) MarshalJSON

func (PrivacyExportAdmissionWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of invocation authority.

func (PrivacyExportAdmissionWork) MarshalText

func (PrivacyExportAdmissionWork) MarshalText() ([]byte, error)

MarshalText rejects implicit serialization of invocation authority.

func (PrivacyExportAdmissionWork) Query

func (h PrivacyExportAdmissionWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query executes one bounded trusted primary query with Work's existing limits. Close rows before returning; this is not an application SQL sandbox.

func (PrivacyExportAdmissionWork) RequireActiveCredential

RequireActiveCredential borrows exact kernel credential/user epoch checks; their primary locks remain until the original coordinator transaction closes.

func (PrivacyExportAdmissionWork) RequireActiveDirectoryAuthority

RequireActiveDirectoryAuthority checks configured global/tenant epochs without adopting a newer authority or claiming policy Allow.

func (PrivacyExportAdmissionWork) RequireActiveUserAuthorization

RequireActiveUserAuthorization borrows the existing authorization owner's primary checks; it does not create a separate identity policy engine.

type PrivacyExportJobMigrationSource

type PrivacyExportJobMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

PrivacyExportJobMigrationSource appends bounded privacy job/snapshot storage after immutable Base history. Base must include PrivacyExportMigrationSource. Allocate Version after every Base version; no destructive down is supported. Stored metadata is pseudonymous personal data, never bearer material. This schema does not enable admission, workers, publication or downloads.

func (PrivacyExportJobMigrationSource) Load

Load copies forward-only history without IO. Nil context/base, empty history and non-successor versions fail closed; cancellation and base errors propagate. Apply through the migration Runner; do not modify already applied SQL.

type PrivacyExportMigrationSource

type PrivacyExportMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

PrivacyExportMigrationSource adds authoritative privacy epoch and destructive admission fences to immutable Base history at an explicitly allocated later Version. Base must include StatusMigrationSource's authority/status columns. Existing users retain IDs, aggregate/security versions and blocked state. New creation writers use privacy epoch 1 and idle disposition. Anonymization and deletion owners must set their pending disposition under the same user lock before initiating cascades; idle is not current authorization. This forward-only schema does not create a job, consume proof or run exports.

func (PrivacyExportMigrationSource) Load

Load returns owned history without IO. Nil/empty Base, non-successor Version and nil context fail closed; cancellation is preserved. No destructive down is supported because resetting privacy epochs would revive old authority.

type ProfileSchemaRef

type ProfileSchemaRef struct {
	ID      string
	Version uint32
}

ProfileSchemaRef explicitly selects one frozen AttributeSchemas declaration for GetProfile. Both ID and Version must be present or both zero (disabled). This is storage configuration, not permission or schema migration authority.

type ProfileUnitOfWork

type ProfileUnitOfWork struct {
	// contains filtered or unexported fields
}

ProfileUnitOfWork is the opt-in durable profile command composition behind identity.ProfileService. It reuses the sole Coordinator and its typed audit/outbox phases. It does not authenticate direct callers, own the pool, run callbacks inside a transaction, or start background work. Immutable composition supports concurrent calls; zero is invalid.

func NewProfileUnitOfWork

func NewProfileUnitOfWork(c *Coordinator, r *Repository, config CreationUnitOfWorkConfig) (*ProfileUnitOfWork, error)

NewProfileUnitOfWork requires the exact enlisted Repository with a selected frozen ProfileSchema. Retention configuration has the same semantics as the creation composition. No I/O occurs. The existing creation-only API remains unchanged; this composition accepts profile commands only.

func (*ProfileUnitOfWork) Execute

Execute persists an admitted self-profile mutation, audit, lifecycle and immutable receipt together. Replay resolves before current-state CAS. Empty name/image are omitted; additional values replace individual named fields. A stale/blocked write closes with an audited NotCommitted outcome. Ambiguous closure stays Unknown; preserve command identity and use Recover.

func (ProfileUnitOfWork) Format

func (ProfileUnitOfWork) Format(s fmt.State, _ rune)

Format prevents dependency and command disclosure.

func (ProfileUnitOfWork) MarshalJSON

func (ProfileUnitOfWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of runtime composition.

func (*ProfileUnitOfWork) Recover

Recover observes the original self-scoped profile receipt, never infers success from current profile state and never reapplies a mutation. Current authorization and output redaction belong to identity.ProfileService.

type ProviderAccountAdmission

type ProviderAccountAdmission struct {
	Account           identity.Account
	SocialLinkVersion uint64
	Credential        CredentialAdmission
}

ProviderAccountAdmission freezes an exact provider account, its independent social-link version and original kernel credential authority. None of these scalar observations is provider proof or current authentication authority. The native owner must bind them into its immutable command before reservation.

func (ProviderAccountAdmission) Format

func (ProviderAccountAdmission) Format(s fmt.State, _ rune)

Format excludes provider subjects and correlated credential scope.

func (ProviderAccountAdmission) MarshalJSON

func (ProviderAccountAdmission) MarshalJSON() ([]byte, error)

MarshalJSON prevents accidental export of correlated admission state.

type RecipientEligibility

type RecipientEligibility uint8

RecipientEligibility is a closed, trusted workflow selection, not request permission. Verification/change workflows may select pending identifiers; signin/reset must require verified identifiers. Revoked is never eligible.

const (
	RecipientVerified RecipientEligibility = iota + 1
	RecipientPendingOrVerified
)

type RecipientQuery

type RecipientQuery struct {
	TenantID       identity.TenantID
	UserID         identity.UserID
	Kind           identity.IdentifierKind
	CanonicalValue string
	Eligibility    RecipientEligibility
	// An optional exact stored comparison binding. Both zero retain the legacy
	// channel projection unchanged; both present require this persisted pair.
	// Absent or different stored profiles suppress discovery, never reinterpret
	// byte-equal canonical values using today's normalization policy.
	NormalizationProfile string `json:",omitempty"`
	NormalizationVersion uint32 `json:",omitempty"`
}

RecipientQuery selects exactly one owner-canonical channel identifier in one tenant. UserID optionally restricts the original known subject. Empty UserID permits discovery without retargeting the command's anonymous flow. Values are already canonical under the email/phone owner's versioned policy; this storage port does not normalize input or grant authentication/authorization.

func (RecipientQuery) Format

func (RecipientQuery) Format(s fmt.State, _ rune)

func (RecipientQuery) MarshalJSON

func (RecipientQuery) MarshalJSON() ([]byte, error)

func (RecipientQuery) MarshalText

func (RecipientQuery) MarshalText() ([]byte, error)

func (RecipientQuery) Validate

func (q RecipientQuery) Validate() error

Validate bounds input before SQL. Only email/phone channel identifiers are accepted; username/provider subjects are not delivery addresses.

type RecipientRecord

type RecipientRecord struct {
	Query                                                                        RecipientQuery
	Suppressed                                                                   bool
	User                                                                         identity.User
	Identifier                                                                   identity.Identifier
	Verification                                                                 identity.Verification
	UserAuthorityVersion, IdentifierAuthorityVersion, CredentialAuthorityVersion uint64
	ObservedAt                                                                   time.Time
}

RecipientRecord is an explicit primary snapshot, never a clearance/proof or public response. Suppressed covers absent, foreign-subject, inactive and ineligible records uniformly and carries no resolved identity or versions. A selected record freezes exact identifier/verification/security versions; bind it into original workflow custody and recheck via RequireRecipient. ObservedAt is database observation time, not a renewable validity lease. Copies own scalar values; do not concurrently mutate an input record.

func (RecipientRecord) Format

func (RecipientRecord) Format(s fmt.State, _ rune)

func (RecipientRecord) MarshalJSON

func (RecipientRecord) MarshalJSON() ([]byte, error)

func (RecipientRecord) MarshalText

func (RecipientRecord) MarshalText() ([]byte, error)

func (RecipientRecord) Validate

func (r RecipientRecord) Validate() error

Validate checks structure only; manually populated records confer no current authority. Suppressed records must omit all selected fields.

type RecoveryContributor

type RecoveryContributor interface {
	Contributor
	RecoverParticipant(context.Context, RecoveryWork) (RecoveryStatus, error)
}

RecoveryContributor supplies local primary evidence for its exact frozen declaration. Only Coordinator calls this method. Implementations must inspect retained bindings, not merely prunable payloads, and own only their evidence. No network, hooks, private transactions, command-ledger changes or retained handles are allowed. A nil error is not commit proof. This interface grants evidence reads only. Identifier attachment's separate typed release phase is invoked only after every participant proves non-commit. Implementations must support concurrent invocations with independent handles.

type RecoveryStatus

type RecoveryStatus uint8

RecoveryStatus is authoritative participant evidence, never a command receipt. Zero, missing, conflicting or unknown evidence cannot terminalize a command. Committed evidence beside a pending kernel journal is an atomicity conflict, not permission to reconstruct a success from current user state.

const (
	// RecoveryUnknown supplies no conclusive participant outcome.
	RecoveryUnknown RecoveryStatus = iota
	// RecoveryNotCommitted proves no committed effect for the frozen input.
	RecoveryNotCommitted
	// RecoveryCommitted proves a committed participant effect, not a full receipt.
	RecoveryCommitted
)

type RecoveryWork

type RecoveryWork struct {
	// contains filtered or unexported fields
}

RecoveryWork is a bounded, generation-bound primary evidence capability for one frozen contributor invocation. It has no constructor, mutation staging, transaction closure, reservation or raw driver API. Query admits trusted compile-time evidence SELECTs under Work's size/result/parameter limits; adapters must not issue SQL mutations or ownership-changing SQL functions. Copies share lifetime and expire when the invocation returns. Use serially; retaining this value or its rows is forbidden. Zero is invalid.

func (RecoveryWork) AuditPlan

func (w RecoveryWork) AuditPlan() (AuditPlan, error)

AuditPlan returns the owned frozen audit declaration only to audit/postgres.

func (RecoveryWork) AuditPlans

func (w RecoveryWork) AuditPlans() ([]AuditPlan, error)

AuditPlans returns an owned copy of every frozen audit slot, in event-index order, only during audit/postgres's recovery invocation. Native feature commands may require several slots; absence of any retained slot cannot prove their atomic persistence. Copies do not grant authority after return.

func (RecoveryWork) CapabilityBinding

CapabilityBinding returns frozen participant input only to the exact registered capability instance. Generation is the recovery owner and PreviousGeneration is the reserved owner being reconciled. The handle grants evidence reads only: expiry or a negative capability observation alone cannot release it. Missing or mismatched retained bindings must remain unknown.

func (RecoveryWork) CapabilityIssuanceBinding

CapabilityIssuanceBinding returns frozen original-command metadata only to this exact issuer during its recovery phase. It grants primary evidence reads, not signing, issuing, release, bearer retrieval or command terminalization.

func (RecoveryWork) CaptchaBinding

CaptchaBinding returns frozen consuming custody only to the exact native CAPTCHA owner during primary recovery. It grants evidence reads, never release authority; absent/divergent/terminal evidence cannot prove noncommit.

func (RecoveryWork) CaptchaReplayOwnership

func (w RecoveryWork) CaptchaReplayOwnership(p CaptchaReplayContributor) (CaptchaReplayOwnership, error)

CaptchaReplayOwnership exposes frozen linkage during the exact native recovery-only invocation. It grants no SQL mutation, release or new issuance authority. Current disclosure authorization remains the coordinator's job.

func (RecoveryWork) CommandCounterBinding

func (w RecoveryWork) CommandCounterBinding(p CommandCounterContributor) (CommandCounterBinding, error)

CommandCounterBinding exposes only frozen charge linkage during recovery. A matching charge is prerequisite evidence, never proof of domain commit.

func (RecoveryWork) DeliveryScope

DeliveryScope exposes original frozen inputs only to this exact contributor during its recovery invocation. It grants reads, not enqueue or replay work.

func (RecoveryWork) EmailVerificationMFAChallenge

func (w RecoveryWork) EmailVerificationMFAChallenge(owner EmailVerificationMFAChallengeContributor) (MFAContinuationPlan, error)

EmailVerificationMFAChallenge returns unchanged committed-parent challenge scope to its exact native recovery participant. It grants neither mutation, primary/factor authentication nor replacement credential disclosure. Returned copies cannot change the frozen plan or extend its original expiry.

func (RecoveryWork) FeatureScope

FeatureScope verifies the exact native participant during its recovery-only invocation and returns its original frozen transition. It cannot reconstruct success from current state or grant mutation/transaction ownership. Nil, noncomparable or foreign instances and expired invocations fail without IO.

func (RecoveryWork) Format

func (RecoveryWork) Format(s fmt.State, _ rune)

Format hides runtime evidence scope and retained composition.

func (RecoveryWork) LifecyclePlan

func (w RecoveryWork) LifecyclePlan() (LifecyclePlan, error)

LifecyclePlan returns the owned frozen declaration only to outbox/postgres.

func (RecoveryWork) MagicLinkMFAChallenge

func (w RecoveryWork) MagicLinkMFAChallenge(owner MagicLinkMFAChallengeContributor) (MFAContinuationPlan, error)

MagicLinkMFAChallenge returns the complete original challenge declaration only to its exact native recovery participant. It grants historical primary evidence reads, never factor/session authority, mutation or bearer delivery. Zero, foreign, incomplete and returned invocations deny; the copy is owned.

func (RecoveryWork) MarshalJSON

func (RecoveryWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of transaction evidence authority.

func (RecoveryWork) OTPBinding

OTPBinding returns frozen consuming custody only to the exact registered OTP owner during primary recovery. It grants evidence reads, not release rights. Missing, divergent or terminal challenge evidence must remain unknown.

func (RecoveryWork) PasskeyMFAChallenge

func (w RecoveryWork) PasskeyMFAChallenge(owner PasskeyMFAChallengeContributor) (MFAContinuationPlan, error)

PasskeyMFAChallenge returns the unchanged historical declaration only to its original registered recovery owner. It is not evidence of commitment: recovery also inspects expired pending journals. It never repeats assertion/factor verification, creates another child or discloses credentials.

func (RecoveryWork) PasswordMFAChallenge

func (w RecoveryWork) PasswordMFAChallenge(owner PasswordMFAChallengeContributor) (MFAContinuationPlan, error)

PasswordMFAChallenge returns unchanged historical scope to the exact native recovery participant. It permits neither comparison, mutation nor credential delivery; original committed evidence and journal ownership remain required.

func (RecoveryWork) Query

func (w RecoveryWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query reads only this contributor's authoritative evidence using bounded coordinator-owned rows. Close/drain every cursor before returning; failures poison recovery and rows do not survive the invocation.

func (RecoveryWork) RiskBinding

RiskBinding returns frozen evidence custody only to the exact registered release participant during recovery. It grants reads, never release rights. Missing or mismatched native custody must remain unknown regardless of expiry.

func (RecoveryWork) Scope

Scope returns the original immutable command binding, not current authority.

type Repository

type Repository struct {
	// contains filtered or unexported fields
}

Repository reads and lists from a caller-owned primary pool and applies structural creation only through exact enlisted Coordinator Work. It never closes that pool, starts background work or caches authority. Configure the pool with primary endpoints only: replica reads cannot satisfy this repository's consistency contract. A read is a snapshot, not authorization or revocation evidence. Values are safe for concurrent calls; the zero value is invalid.

func NewRepository

func NewRepository(pool *database.Pool, config Config) (*Repository, error)

NewRepository constructs the primary read adapter without I/O. The caller must migrate the database before use and keep the pool alive until all reads finish. Reads support UserDirectoryRepository; ApplyUserCreation participates in the creation-only coordinator profile. Attribute projections and complete domain writes remain under development.

func (*Repository) ApplyProfileUpdate

func (r *Repository) ApplyProfileUpdate(ctx context.Context, w Work, command identity.Command) (identity.UserProfile, error)

ApplyProfileUpdate uses only this exact enlisted Repository's coordinator- owned Work. The returned profile is provisional, not a durable receipt or current authority. The existing tenant lock and an active/version CAS fence name, image and individually replaced typed fields with one aggregate bump. Omitted values remain unchanged; no defaults are invented. Corrupt/schema- mismatched storage fails closed. Unsupported secret/index profiles remain rejected. Every error poisons Work; callers must Abort. No policy callback runs inside SQL; identity.ProfileService owns admission and output policy.

func (*Repository) ApplyUserCreation

func (r *Repository) ApplyUserCreation(ctx context.Context, w Work, command identity.Command) (identity.User, error)

ApplyUserCreation inserts an active version-1 structural user through this exact enlisted repository's Work. Returned User is provisional, not durable and not fresh authorization. Only Coordinator.Commit establishes its result. A repeated apply, changed command, foreign repository or unsupported nonempty attribute profile fails closed without silently dropping fields. Registered ordinary scalar/list attributes persist with the same mutation; unsupported secret/index profiles fail closed. Primary/unique-key conflicts are redacted and poison further SQL; the caller must Abort.

func (*Repository) ApplyUserUpdate

func (r *Repository) ApplyUserUpdate(ctx context.Context, w Work, command identity.Command) (identity.User, error)

ApplyUserUpdate applies a constructor-validated administrative field command through this exact enlisted Repository's Work. It grants no policy authority. The locked nonterminal status and exact aggregate version fence one successor; whole values replace named fields, preserving omissions and explicit zeros. It does not modify names, images, status, credentials or identifiers. Unknown or mismatched schemas fail closed, and every error poisons Work for Abort. The returned structural user is provisional, never a durable commit receipt.

func (*Repository) Descriptor

func (*Repository) Descriptor() ContributorDescriptor

Descriptor identifies the owned kernel domain participant. Registration supplies identity only; ApplyUserCreation checks this exact instance is enlisted before using coordinator-owned Work. It performs no I/O.

func (Repository) Format

func (Repository) Format(state fmt.State, _ rune)

Format prevents private schema defaults or database configuration disclosure.

func (*Repository) Get

Get performs one bounded exact tenant/user lookup. Fields may select only id, tenant_id, status and version without duplicates; empty selects these structural fields. Typed attributes are not implemented by this adapter. Missing records return identity.ErrUserAbsent; invalid input, cancellation, deadline and unavailable failures use identity's redacted typed errors. No partial projection or driver diagnostics escape a failed read.

func (*Repository) GetAccountLinkState

GetAccountLinkState returns one bounded repeatable-read primary snapshot of the user, all live links, retained candidate tombstone, exact provider-subject collision and credential references. It never locks for mutation or treats a read as proof. The native protected owner must repeat/fence admission in Work. Unsupported implicit mode fails closed until its identifier projection is composed. Methods are conservative reference observations: Usable is false until the corresponding credential/factor/provider owners establish eligibility. This read cannot authorize unlink or session issuance. No token material is read.

func (*Repository) GetAnonymousAuthority

func (r *Repository) GetAnonymousAuthority(ctx context.Context, q identity.UserStatusQuery) (AnonymousAuthorityRecord, error)

GetAnonymousAuthority performs one bounded primary read of kernel-owned anonymous creation and all independent user epochs. It never infers guest status merely from missing credentials. Additional contacts/credentials or a changed placeholder deny; missing scope returns the existing absence error. Blocked status is returned unchanged, not accepted as current authentication. Callers own the original positive-evidence deadline across every owner read.

func (*Repository) GetAnonymousDisposal

GetAnonymousDisposal performs one bounded authoritative read, including legal hold and all anonymous ownership checks. Terminal/blocked snapshots remain terminal/blocked, never converted to deletion permission. Callers preserve the original read-start deadline across session, risk and retention decisions.

func (*Repository) GetCredentialAuthority

GetCredentialAuthority reads an exact user/reference and independent credential epoch from one primary statement. Missing exact user or reference is ErrUserAbsent; missing schema or corrupt data is redacted Unavailable, never a default version. Caller/configured deadlines bound the read. Disabled, expired and blocked states are preserved for the core eligibility decision, not hidden or restored. The reference contains no verifier and grants no lookup access, factor/provider assurance, proof provenance or renewable validity lease.

func (*Repository) GetDirectoryAuthority

GetDirectoryAuthority performs one bounded primary read of the exact scopes. Missing scope is redacted Forbidden; corrupt/missing schema is Unavailable. Disabled tenant state is returned, never restored. The read acquires no persistent lock, creates no validity lease, and supplies no issuance proof.

func (*Repository) GetIdentifierState

GetIdentifierState returns one complete tenant/user primary snapshot through the existing IdentifierRepository port. One statement observes the user, identifier authority and ordered identifier/verification rows consistently. MaximumIdentifiers must be 1..128. An extra row returns Unavailable with no partial result rather than silently truncating; a missing user is ErrUserAbsent. Stored canonical/display values are never normalized, defaulted or logged. Full uint64 versions and microsecond verification instants are preserved.

This trusted storage port confers no authorization, proof, uniqueness claim or freshness beyond its primary snapshot. IdentifierService owns admission; coordinated writes, proof consumption and tombstones remain separate work. Reads use the configured finite budget and earlier caller deadline. Returned slices own their memory; no pool, rows, transaction or callback is retained.

func (*Repository) GetProfile

func (r *Repository) GetProfile(ctx context.Context, q identity.ProfileQuery) (record identity.ProfileRecord, err error)

GetProfile implements the existing primary ProfileRepository port. One SQL statement observes the structural user, optional name/image and exact typed attribute document as one aggregate snapshot. It never fabricates defaults for old structural users or guesses a stored schema version. The selected ProfileSchema and immutable stored definition must agree exactly; corrupt or incompatible documents return Unavailable with no partial profile.

Empty Fields selects all output-readable fields. Explicit fields must be unique, known and output-readable, at most 128. ID, tenant and version always identify the returned snapshot; name/image and attributes are selected only when requested. Full stored values are validated before subset projection. Returned lists own their memory. No pool ownership, callback, transaction, cache or background work is retained. Earlier caller deadlines win.

This trusted storage port confers no human, tenant or read authority. Compose ProfileService for current-subject/active-state authorization, field redaction and image-origin policy. Stored images are never fetched or trusted as URLs. Profile writes and lifecycle/privacy erasure remain separate domain work.

func (*Repository) GetStatus

GetStatus returns the exact tenant/user's consistent primary status and independent security epoch. It does not auto-restore expired restrictions, infer authority from aggregate or identifier versions, or grant permission. A missing user returns ErrUserAbsent; missing schema/corrupt data is redacted Unavailable. Earlier caller/configured deadlines bound the one statement.

func (*Repository) List

List implements identity.UserListRepository using retained structural rows, not a live OFFSET query or an authority cache. New snapshots are atomically selected in bytewise ID order with exact status filters; continuations bind tenant, the canonical status set and original nanosecond expiry. IDs and all uint64 versions remain unchanged across live updates/deletion or process replacement. Pages contain at most 100 users. Empty means terminal; capacity failures are Unavailable, never silent truncation. Expired/mismatched cursors are InvalidInput. Cancellation/deadline retain their classifications.

Only structural fields and status filters are implemented in this development profile. Identifier filtering requires the remaining owned identifier store and fails closed; arbitrary attribute search is unsupported. The public core service must authorize collection and each row on every call. A snapshot's historical status/version grants no current identity authority. No caller callback runs under a transaction. The caller retains pool ownership.

func (*Repository) ListAccounts

ListAccounts returns one complete, ordered primary user/account snapshot. MaximumAccounts must be 1..100; overflow/corruption fails redacted Unavailable without partial rows. Missing user is ErrUserAbsent. Caller/configured budgets bound I/O, and returned slices own their memory. No authorization, provider proof, network work, credential usability or cache freshness is established.

func (*Repository) PruneUserListSnapshots

func (r *Repository) PruneUserListSnapshots(ctx context.Context, tenant identity.TenantID, maximum uint32) (uint32, error)

PruneUserListSnapshots removes at most maximum (1..32) expired snapshots for one exact tenant, including their rows, using primary time and SKIP LOCKED. This trusted maintenance storage seam grants no caller permission. Run it regularly for inactive tenants; no internal goroutine or pool ownership is created. Active/locked snapshots are never removed. Earlier deadlines win; errors return zero count, redacted and classified, without claiming cleanup.

func (*Repository) RecoverParticipant

func (r *Repository) RecoverParticipant(ctx context.Context, recovery RecoveryWork) (RecoveryStatus, error)

RecoverParticipant proves absence of a creation target on the locked primary. An existing user is not evidence that this command committed; without an original command linkage that case conservatively remains unknown. No live user data or receipt is reconstructed. Only this exact enlisted instance may inspect its evidence. For field mutation, only the unchanged original aggregate version is negative evidence under the coordinator's journal and tenant fences. A changed/missing aggregate remains unknown; it is never treated as a committed receipt. Identifier attachment requires target absence plus the other participants' retained negative evidence; any existing target remains unknown. Other domain profiles remain unsupported.

func (*Repository) ResolveRecipient

func (r *Repository) ResolveRecipient(ctx context.Context, q RecipientQuery) (RecipientRecord, error)

ResolveRecipient performs one bounded exact primary read. Missing/inactive or ineligible selection returns a suppressed record, never an existence error. Infrastructure/corrupt-state failures return Unavailable, not suppression. No lock, mutation, delivery, freshness renewal or ownership proof is created. Install the kernel identifier/status/credential-authority migrations first.

func (*Repository) ResolveUsername

func (r *Repository) ResolveUsername(ctx context.Context, q UsernameQuery) (UsernameRecord, error)

ResolveUsername performs one exact bounded primary read with no mutation, callback, lock, password work or freshness renewal. Unknown/ineligible names return Suppressed, while corrupt/unavailable storage returns Unavailable and no partial result. The earlier caller deadline bounds the repository budget. The returned snapshot must be admitted again in the protected transaction. Install status and credential-authority histories as well as identifiers; missing authority storage cannot be replaced with inferred epoch defaults.

type RequestKeyAdmission

type RequestKeyAdmission struct {
	CommandID             identity.CommandID
	FingerprintKeyVersion uint32
}

RequestKeyAdmission is correlation only: the confirmed original random command and retained fingerprint-key version. It grants no reservation, mutation, outcome, user authority or permission to regenerate secrets on replay. The feature must recover the original command journal and native prepared state before proceeding. Zero is invalid. Copies are safe for concurrent reads.

type RequestKeyConfig

type RequestKeyConfig struct {
	Namespace string
	Policy    CommandQueryPolicy
	// contains filtered or unexported fields
}

RequestKeyConfig opts the Coordinator into pre-preparation request correlation. Namespace is a trusted fixed deployment/environment identifier (1..128 bounded UTF-8 bytes), not request data. The lookup key is a secret random 32-byte key fixed for that namespace: changing it fails closed against installed storage. Policy is a distinct current request-admission policy. Nil configuration does not enable this feature; existing query/admission policies do not enable it. The constructor copies configuration without I/O. Dependencies must support bounded concurrent calls. Fingerprint keys retain CoordinatorConfig rotation. Construct with NewRequestKeyConfig; zero or literal configuration is invalid. The lookup key has no projection and is opaque through nested diagnostics.

func NewRequestKeyConfig

func NewRequestKeyConfig(namespace string, lookupKey [32]byte, policy CommandQueryPolicy) (RequestKeyConfig, error)

NewRequestKeyConfig validates and copies a nonzero lookup key and trusted namespace/policy without I/O or policy callbacks. Its private closure prevents recursive diagnostic reflection from disclosing key bytes, including when fmt cannot dispatch Format through private caller fields. Zero/invalid input returns a redacted error and no usable configuration. Copies share immutable key custody; edits to public policy/namespace fields are revalidated and copied by NewCoordinatorWithRequestKeys. Never mutate input during construction.

func (RequestKeyConfig) Format

func (RequestKeyConfig) Format(s fmt.State, _ rune)

Format redacts configuration keys and runtime policy dependencies.

func (RequestKeyConfig) LogValue

func (RequestKeyConfig) LogValue() slog.Value

LogValue never exposes the lookup key.

func (RequestKeyConfig) MarshalJSON

func (RequestKeyConfig) MarshalJSON() ([]byte, error)

MarshalJSON rejects persistence of lookup keys and policy composition.

type RequestKeyExpiryContributor

type RequestKeyExpiryContributor interface {
	RequestKeyRecoveryContributor
	RestoreRequestKeyExpiry(context.Context, RequestKeyPreparationBinding, []byte) (identity.CommandBinding, time.Time, error)
}

RequestKeyExpiryContributor restores the exact authenticated original binding and exclusive preparation deadline without refreshing any authority or input. The deadline is the earliest original preparation/session validity ceiling, never reconstructed from the current clock or a replacement session. The native codec must authenticate the complete RequestKeyPreparationBinding and immutable configuration alongside it. Like RestoreRequestKey, this is bounded pure decoding outside SQL: no callbacks, generation, counters or side effects.

type RequestKeyExpiryMigrationSource

type RequestKeyExpiryMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

RequestKeyExpiryMigrationSource appends optional irreversible mapped-origin refusal to the existing global command-ID claim, not another journal. Base must include request-key preparation; Version follows every installed step. Existing history/rows and ordinary retirement semantics remain unchanged. The keyed origin commitment contains no plaintext subject or credential. Typed fences cannot be updated/deleted/truncated; no downgrade is supported.

func (RequestKeyExpiryMigrationSource) Load

Load returns owned forward history without I/O. Cancellation and source errors are preserved; absent preparation history or non-successor versions fail closed.

type RequestKeyMigrationSource

type RequestKeyMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

RequestKeyMigrationSource appends optional immutable request correlation storage to Base at an explicit later Version. Base must contain the kernel schema; its installed history is unchanged. Mapping is not an execution journal and has no mutable state, lease or outcome. Removal/reassignment is unsupported: retaining correlation prevents unknown work becoming a new command after the replay window. No destructive down migration is provided.

func (RequestKeyMigrationSource) Load

Load returns caller-owned forward-only history without I/O. Nil/empty Base, nil context and non-successor Version fail closed; cancellation is preserved.

type RequestKeyPreparationBinding

type RequestKeyPreparationBinding struct {
	Namespace     string
	Scope         RequestKeyScope
	Admission     RequestKeyAdmission
	Feature       FeatureRegistration
	PolicyVersion uint64
	IntentDigest  [32]byte
}

RequestKeyPreparationBinding is original input provenance, not execution or current authority. Authenticate the complete scalar binding as envelope AAD. Namespace, scope, feature and policy are trusted composition; admission and intent digest are coordinator-derived. No raw initiating key is included. Copies are immutable by convention and safe for concurrent reads.

func (RequestKeyPreparationBinding) Format

Format hides correlation and intent provenance from diagnostics.

func (RequestKeyPreparationBinding) LogValue

LogValue redacts original request provenance.

func (RequestKeyPreparationBinding) MarshalJSON

func (RequestKeyPreparationBinding) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization outside the native authenticated codec.

type RequestKeyPreparationContributor

type RequestKeyPreparationContributor interface {
	FeatureExecutionContributor
	PrepareRequestKey(context.Context, RequestKeyPreparationBinding, identity.RequestIntent) ([]byte, error)
}

RequestKeyPreparationContributor is an optional exact registered native feature owner. PrepareRequestKey performs bounded reads and authenticated encryption of original code-free input outside SQL. It must not assess risk, charge counters, generate OTPs, deliver messages or mutate domain state. Concurrent missing-key callers may prepare discarded candidates. Only the acknowledged immutable mapping winner may proceed to the existing journal. The ciphertext must bind every PreparationBinding field and the owner's immutable configuration. Include configuration identity in RequestIntent. Never retain raw bearer/code/key material. Methods must support concurrency.

type RequestKeyPreparationMigrationSource

type RequestKeyPreparationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

RequestKeyPreparationMigrationSource appends optional immutable code-free input custody to existing request-key mappings. Base must include the original RequestKeyMigrationSource; Version must follow all installed history. Existing checksums and rows are unchanged, and legacy mappings are never backfilled. The existing mapping trigger prohibits modification/removal of either new field. This adds no journal, lease, outcome or execution authority. No destructive downgrade is supported; install before enabling the new API.

func (RequestKeyPreparationMigrationSource) Load

Load returns owned forward history without I/O; nil, cancelled, empty or non-successor input fails without fabricating a migration.

type RequestKeyRecoveryContributor

type RequestKeyRecoveryContributor interface {
	RequestKeyPreparationContributor
	RestoreRequestKey(context.Context, RequestKeyPreparationBinding, []byte) (identity.CommandBinding, error)
}

RequestKeyRecoveryContributor optionally restores original correlation from its existing authenticated request-key ciphertext. The exact registered native owner must authenticate every RequestKeyPreparationBinding field and its immutable configuration, decode the complete original CommandBinding and return no binding on failure. RestoreRequestKey is a bounded, concurrency-safe decoder outside SQL: no input preparation, authority refresh, execution, counters, entropy, delivery, external callbacks or mutation may occur. Borrowed ciphertext is valid only during the call and must not be retained or logged.

type RequestKeyScope

type RequestKeyScope struct {
	TenantID  identity.TenantID
	ActorID   identity.ActorID
	ActorKind authorization.SubjectKind
	Method    string
	RouteID   string
}

RequestKeyScope is the exact lookup scope, independent of body, target user, purpose, expected versions and all other intent. Actor includes its closed authorization kind. Method is POST, PUT, PATCH or DELETE, without normalization; RouteID is the trusted canonical route identifier (not a URL or raw path). IDs are 1..128 bounded UTF-8 bytes without controls/space. Trusted feature/HTTP composition selects method/route; direct callers must use that same mapping.

type Reservation

type Reservation struct {
	// contains filtered or unexported fields
}

Reservation is opaque, generation-bound ownership from a proven durable reservation commit. Copies share the private snapshot and single-use state. It grants no Work, SQL, closure or independently usable execution authority; zero is invalid. It cannot be serialized and diagnostics are redacted. Begin consumes it once, including a failed admitted attempt. Retain it only for the owning Coordinator; it is not authority to renew the lease.

func (Reservation) Format

func (Reservation) Format(s fmt.State, _ rune)

Format hides command, tenant, lease owner and retained private command data.

func (Reservation) MarshalJSON

func (Reservation) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of opaque reservation ownership.

type RiskApplyWork

type RiskApplyWork struct {
	// contains filtered or unexported fields
}

RiskApplyWork grants invocation-only bounded primary reads and exact native input to the registered risk owner. It exposes no mutation or raw driver. Trusted read/locking SQL only; zero, foreign and retained handles fail. Copies share lifetime; serial use only, and rows must close before callback return.

func (RiskApplyWork) Binding

Binding returns exact current-generation custody; no takeover/release proof.

func (RiskApplyWork) DatabaseTime

func (w RiskApplyWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary time; it cannot renew original evidence or Work.

func (RiskApplyWork) Format

func (RiskApplyWork) Format(s fmt.State, _ rune)

Format redacts command inputs and transaction custody for every format verb.

func (RiskApplyWork) MarshalJSON

func (RiskApplyWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of invocation authority, including zero.

func (RiskApplyWork) MarshalText

func (RiskApplyWork) MarshalText() ([]byte, error)

MarshalText rejects serialization of invocation authority, including zero.

func (RiskApplyWork) NativeCommand

NativeCommand returns immutable admitted input only to the exact owner.

func (RiskApplyWork) Query

func (w RiskApplyWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query reads bounded primary state without exposing transaction closure.

type RiskEvidencePlan

type RiskEvidencePlan struct {
	IssuanceCommandID, Tenant, Subject, IssuerActor string
	Purpose, Phase, RecoveryOperation               string
	PolicyVersion                                   uint64
	KeyVersion                                      uint32
	IntentDigest                                    [32]byte
	ConsumerCommandID, ConsumerActor                string
	EvidenceDigest, ProofDigest, Signature          [32]byte
	IssuedAt, CheckedAt, ExpiresAt                  time.Time
}

RiskEvidencePlan is the consumer-owned scalar projection of risk's signed PreparedEvidenceUse. Issuance identity and consuming command identity remain separate; digests bind the omitted raw recovery/configuration/bearer scope. IssuedAt and ExpiresAt are original UTC microsecond instants; CheckedAt is the original UTC precheck instant, possibly nanosecond precision. Nothing here renews freshness or proves cryptographic authenticity or row existence. The registered risk adapter must authenticate every scalar, match current policy and native command scope, and reserve the existing authoritative row. Reset initiation and the closed completion conjunction are admitted; the latter requires separate capability, consuming OTP and completion-risk participants. Copies own their scalars. Diagnostics and serialization are redacted.

func (RiskEvidencePlan) Format

func (RiskEvidencePlan) Format(s fmt.State, _ rune)

func (RiskEvidencePlan) MarshalJSON

func (RiskEvidencePlan) MarshalJSON() ([]byte, error)

func (RiskEvidencePlan) MarshalText

func (RiskEvidencePlan) MarshalText() ([]byte, error)

type RiskExecutionContributor

type RiskExecutionContributor interface {
	RiskReleaseContributor
	ValidateRiskEvidenceCommand(identity.Command, RiskEvidencePlan) error
	CheckRiskEvidence(context.Context, RiskApplyWork) error
	FinalizeRiskEvidence(context.Context, RiskFinalizeWork) error
}

RiskExecutionContributor opts the exact durable owner into one-use domain execution. ValidateRiskEvidenceCommand is pure bounded native scope/policy authentication. CheckRiskEvidence rechecks the reserved original row, current authority, policy/provider versions, counters and exclusive expiry in the domain transaction, before mutation and again before finalization. Finalize must CAS the same reserved command/fingerprint/generation to terminal used after rechecking expiry; zero affected rows is failure. All phases must deny missing/mismatched/terminal rows, never issue, renew, release or run provider callbacks. No private transaction, retry, retained handle or closure is allowed. The feature owner separately checks current user/factor/domain authority. Reservation/release-only implementations remain closed to domain execution.

type RiskFinalizeWork

type RiskFinalizeWork struct {
	// contains filtered or unexported fields
}

RiskFinalizeWork grants invocation-only terminal mutation in the same domain transaction after current checks and provisional feature/audit/outbox effects. The exact owner must recheck expiry and CAS original custody. No resurrection, release or private commit is permitted. Copies share lifetime, serial use only; close rows before return. All effects remain provisional until coordinator commit.

func (RiskFinalizeWork) Binding

Binding returns original current-generation custody, not release authority.

func (RiskFinalizeWork) DatabaseTime

func (w RiskFinalizeWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime samples primary time without renewing validity or Work lifetime.

func (RiskFinalizeWork) Exec

func (w RiskFinalizeWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec runs one bounded trusted terminal statement, not transaction closure.

func (RiskFinalizeWork) Format

func (RiskFinalizeWork) Format(s fmt.State, _ rune)

Format redacts command inputs and transaction custody for every format verb.

func (RiskFinalizeWork) MarshalJSON

func (RiskFinalizeWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of terminal authority, including zero.

func (RiskFinalizeWork) MarshalText

func (RiskFinalizeWork) MarshalText() ([]byte, error)

MarshalText rejects serialization of terminal authority, including zero.

func (RiskFinalizeWork) NativeCommand

NativeCommand returns the same immutable admitted command to the exact owner.

func (RiskFinalizeWork) Query

func (w RiskFinalizeWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns bounded invocation-owned rows from the domain transaction.

type RiskReleaseContributor

type RiskReleaseContributor interface {
	RiskReservationContributor
	RecoveryContributor
	ReleaseRiskEvidence(context.Context, RiskReleaseWork) error
}

RiskReleaseContributor supplies native noncommit evidence and terminal release. The coordinator invokes release only after all frozen participants prove recovery noncommit, or after it proves rollback and rechecks the live owner, under primary command and tenant exclusions. Release must CAS the exact reserved command/fingerprint/PreviousGeneration to terminal released, recording Generation. Recovery advances exactly one generation; proved live-owner rollback preserves generation. Expiry alone is never proof; expired reservations remain releasable after proof. No provider callbacks, private transactions, retained handles or reactivation are permitted. Independent invocations may run concurrently; their handles remain serial-use and invocation-bound.

type RiskReleaseWork

type RiskReleaseWork struct {
	// contains filtered or unexported fields
}

RiskReleaseWork grants bounded terminal release, not reservation or domain authority. Zero and foreign handles are invalid. Copies expire on callback return or panic. Close rows before return; no transaction closure is exposed.

func (RiskReleaseWork) Binding

Binding checks exact registered identity and returns original frozen custody. PreviousGeneration is the reserved owner. Generation is the recovery successor, or the same live owner after the coordinator proves rollback.

func (RiskReleaseWork) DatabaseTime

func (w RiskReleaseWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime reads primary UTC without renewing ownership or evidence expiry.

func (RiskReleaseWork) Exec

func (w RiskReleaseWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec executes one bounded native release statement, never transaction closure.

func (RiskReleaseWork) Format

func (RiskReleaseWork) Format(s fmt.State, _ rune)

Format redacts retained ownership and evidence metadata.

func (RiskReleaseWork) MarshalJSON

func (RiskReleaseWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of release authority.

func (RiskReleaseWork) MarshalText

func (RiskReleaseWork) MarshalText() ([]byte, error)

MarshalText rejects serialization of release authority.

func (RiskReleaseWork) Query

func (w RiskReleaseWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns invocation-owned bounded rows; close them before return.

type RiskReservationBinding

type RiskReservationBinding struct {
	Command                        identity.CommandBinding
	Plan                           RiskEvidencePlan
	Fingerprint                    [32]byte
	Generation, PreviousGeneration uint64
}

RiskReservationBinding is an owned scalar snapshot, never raw bearer or key material. Fingerprint is the authoritative retained-key consuming command fingerprint. Generation is positive; PreviousGeneration is zero for first reservation, otherwise the exact positive predecessor. Plan is declaration metadata, not proof of current authority, scope validation or row existence. Release reuses this snapshot: after proved live-owner rollback the two generations are equal; recovery release requires an exact successor.

func (RiskReservationBinding) Format

func (RiskReservationBinding) Format(s fmt.State, _ rune)

func (RiskReservationBinding) MarshalJSON

func (RiskReservationBinding) MarshalJSON() ([]byte, error)

func (RiskReservationBinding) MarshalText

func (RiskReservationBinding) MarshalText() ([]byte, error)

type RiskReservationContributor

type RiskReservationContributor interface {
	Contributor
	ReserveRiskEvidence(context.Context, RiskReservationWork) error
	RebindRiskEvidence(context.Context, RiskReservationWork) error
}

RiskReservationContributor supplies risk's pre-domain phases. Only the sole Coordinator invokes them, inside the command reservation transaction. Reserve must authenticate the signed declaration, match current native scope/policy, and lock an already-issued exact row; it never inserts missing evidence or consumes a use. Rebind must CAS the same command/fingerprint from exactly PreviousGeneration to Generation. Missing, terminal, expired or mismatched rows fail closed, using primary database time and the original expiry. Implementations must verify their exact registered identity through Binding before SQL, close rows and return redacted errors. No provider/caller callbacks, retained Work, private transactions or transaction closure are permitted. Implementations must support concurrent invocations with serial-use handles. Registration/declaration alone supplies no authority to execute domain phases.

type RiskReservationWork

type RiskReservationWork struct {
	// contains filtered or unexported fields
}

RiskReservationWork is coordinator-created invocation-bound SQL authority. Zero and foreign instances are invalid. Copies share lifetime and expire on callback return or panic. Serial use only; close all rows before return. There is no raw driver, constructor, transaction closure or Work escape. Existing Work budgets apply; neither database time nor copies renew them.

func (RiskReservationWork) Binding

Binding verifies lifetime and exact registered participant identity before disclosing owned declarations. Pointer implementations use instance identity; comparable immutable values use value identity. Noncomparable/nil/foreign participants are denied before participant SQL.

func (RiskReservationWork) DatabaseTime

func (w RiskReservationWork) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime reads authoritative primary UTC without renewing expiry.

func (RiskReservationWork) Exec

func (w RiskReservationWork) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec runs one bounded trusted statement, never transaction closure.

func (RiskReservationWork) Format

func (RiskReservationWork) Format(s fmt.State, _ rune)

func (RiskReservationWork) MarshalJSON

func (RiskReservationWork) MarshalJSON() ([]byte, error)

func (RiskReservationWork) MarshalText

func (RiskReservationWork) MarshalText() ([]byte, error)

func (RiskReservationWork) Query

func (w RiskReservationWork) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query returns bounded invocation-owned rows; close them before return.

type SignInProofUseMigrationSource

type SignInProofUseMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

SignInProofUseMigrationSource appends final-authentication proof-use tombstones to immutable Base history. Allocate Version explicitly after every Base version. The zero value is invalid; no destructive downgrade is supplied. This storage is not a session issuer or an authentication authority. It must be composed with the protected issuer's current checks and same-transaction session, audit, lifecycle and terminal command effects before activation.

func (SignInProofUseMigrationSource) Load

Load performs no SQL and preserves all previously applied migration bytes. Proof identity is unique within its stable trusted authentication namespace, across tenants and proof versions. Session deletion must not remove or reset these tombstones. Exact replay belongs to the original command journal, never another insertion or a reconstructed bearer. Full-width versions and original nanosecond expiry are preserved without PostgreSQL timestamp rounding.

type StagedAudit

type StagedAudit struct {
	Plan   AuditPlan
	Record audit.Record
	// Feature and SubjectType are the owned frozen native scope needed by
	// audit/postgres to recompute FeatureAuditBindingDigest. Both are zero for
	// kernel commands; this projection is not current authority or a receipt.
	Feature     identity.FeatureOperation
	SubjectType string
}

StagedAudit is an owned declaration/immutable record pair selected before SQL and admitted by Work.StageAudit. This is not a persistence receipt.

type StagedLifecycle

type StagedLifecycle struct {
	ID            string
	CommandID     identity.CommandID
	TenantID      identity.TenantID
	UserID        identity.UserID
	OperationID   string
	EventType     string
	EventIndex    uint16
	SubjectType   string
	SubjectID     string
	BeforeVersion uint64
	AfterVersion  uint64
	OccurredAt    time.Time
	// Cascade references the exact pending identity-owner admission, not any
	// consumer acknowledgement. Both fields are omitted for non-cascade events.
	CascadeID         identity.CascadeID `json:",omitempty"`
	CascadeGeneration uint64             `json:",omitempty"`
}

StagedLifecycle is an owned, scalar-only safe outbox record. It intentionally cannot carry attributes, identifier values, tokens or arbitrary payloads. ID is deterministic from command ID, lifecycle class and index; event bytes also bind tenant, subject, operation, version transition and occurrence time. This projection does not imply a completed cascade or external effect.

type StatusConsumerContract

type StatusConsumerContract struct {
	Version     uint32
	Fingerprint [32]byte
}

StatusConsumerContract identifies one immutable public consumer contract. Fingerprint is its reviewed nonzero SHA-256 identity, not an acknowledgement or a running adapter. Unavailable consumers must remain in the manifest.

type StatusMigrationSource

type StatusMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

StatusMigrationSource composes immutable kernel history with lifecycle admission storage at an explicitly allocated later version. Base may include session adapters; Version must exceed every base version and fit signed SQL migration storage. Existing MigrationSource and its installed bytes are unchanged. Load performs no SQL; the owned migration Runner applies it.

func (StatusMigrationSource) Load

Load returns caller-owned forward-only history. Nil/invalid composition fails closed; cancellation is preserved. Migration initialization deliberately persists security epoch 1 without changing aggregate/identifier versions or blocked status. Old creation/profile writers remain compatible with defaults.

type StatusUnitOfWork

type StatusUnitOfWork struct {
	// contains filtered or unexported fields
}

StatusUnitOfWork implements the core status command seam through the sole Coordinator with exact enlisted repository/audit/outbox instances. Direct calls do not authorize callers: compose behind identity.UserStatusService. Immutable copied policy supports concurrent calls. It owns no pool, worker, callback, transaction protocol or consumer closure. Zero is invalid.

func NewStatusUnitOfWork

func NewStatusUnitOfWork(c *Coordinator, r *Repository, config StatusUnitOfWorkConfig) (*StatusUnitOfWork, error)

NewStatusUnitOfWork copies and validates policy without I/O or callbacks. Apply StatusMigrationSource before use. Every consumer starts pending; naming one or storing its fingerprint never asserts that its cleanup has run.

func (*StatusUnitOfWork) Execute

Execute resolves exact replay before locked dual-version CAS. A fresh command advances aggregate and user-security epochs once, persists policy, reason/absolute expiry, pending cascade/consumer snapshot, required audit, lifecycle and original receipt in one commit. Restore and unban cannot revive old credentials. Ambiguous closure returns Unknown, never a fabricated user.

func (StatusUnitOfWork) Format

func (StatusUnitOfWork) Format(s fmt.State, _ rune)

Format hides runtime composition and retained policy data.

func (StatusUnitOfWork) MarshalJSON

func (StatusUnitOfWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of runtime composition.

func (*StatusUnitOfWork) Recover

Recover observes the exact original receipt without another mutation or cascade. Core current authorization/redaction governs disclosure. Expired pending work requires all original participants' evidence; current status alone never proves commitment. Preserve the original scope and command ID.

type StatusUnitOfWorkConfig

type StatusUnitOfWorkConfig struct {
	RetentionPolicyVersion uint64
	PolicyVersion          uint64
	Policy                 identity.StatusPolicy
	Reasons                []string
	MaximumCascadeDuration time.Duration
	ConsumerContracts      map[string]StatusConsumerContract
}

StatusUnitOfWorkConfig declares immutable owner policy and the entire identity-lifecycle-consumers-v1 union before use. PolicyVersion is positive; change it for any policy, reason, deadline or consumer-contract change. Reasons has 1..32 distinct bounded non-whitespace codes. MaximumCascadeDuration is microsecond-exact, positive and at most 87,600 hours. ConsumerContracts must contain exactly the 12 suspend/ban consumers, including restore's nine. RetentionPolicyVersion has CreationUnitOfWorkConfig semantics. Configuration is trusted deployment metadata, never authentication or caller permission.

func (StatusUnitOfWorkConfig) Format

func (StatusUnitOfWorkConfig) Format(s fmt.State, _ rune)

Format hides private policy and consumer configuration.

func (StatusUnitOfWorkConfig) MarshalJSON

func (StatusUnitOfWorkConfig) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of private configuration.

type UserAuthorityAdmission

type UserAuthorityAdmission struct {
	UserAuthorityVersion, IdentifierAuthorityVersion, CredentialAuthorityVersion uint64
}

UserAuthorityAdmission freezes three independently owned user security epochs. All must be positive and authenticated as original command intent; none is the aggregate User.Version. This is not authentication or a proof.

func (UserAuthorityAdmission) Format

func (UserAuthorityAdmission) Format(s fmt.State, _ rune)

Format redacts correlated authority input from diagnostics.

func (UserAuthorityAdmission) MarshalJSON

func (UserAuthorityAdmission) MarshalJSON() ([]byte, error)

MarshalJSON rejects accidental export of correlated admission input.

type UserAuthorizationAdmission

type UserAuthorizationAdmission struct {
	Scope   authority.AuthorityScope
	Version uint64
}

UserAuthorizationAdmission binds one user-domain authorization lifecycle epoch. Scope.SubjectID must equal the immutable command's effective UserID when used with RequireActiveUserAuthorization, or its human ActorID with the explicitly actor-bound RequireActiveActorAuthorization. Workload identities are excluded. Scope.PolicyNamespace comes from trusted native composition and must own user-ID uniqueness. Version is a positive full-width counter, independent of policy revision. Native adapters must freeze every field into their keyed command before reservation and compare that intent at execution. This structural input is neither authentication proof nor an Allow decision.

func (UserAuthorizationAdmission) Format

Format redacts correlated admission input from diagnostics.

func (UserAuthorizationAdmission) MarshalJSON

func (UserAuthorizationAdmission) MarshalJSON() ([]byte, error)

MarshalJSON rejects accidental export of correlated admission input.

type UserListSnapshotConfig

type UserListSnapshotConfig struct {
	MaxUsers     uint32
	MaxSnapshots uint32
}

UserListSnapshotConfig bounds durable structural directory snapshots per tenant. Zero selects 10,000 users and 32 snapshots. Otherwise both fields must be positive: MaxUsers <= 100,000 and MaxSnapshots <= 32. Oversized results or exhausted quota fail without partial pages or storage. Lowered limits affect new snapshots, not existing retained continuations.

type UserUpdateUnitOfWork

type UserUpdateUnitOfWork struct {
	// contains filtered or unexported fields
}

UserUpdateUnitOfWork composes durable administrative typed-field updates behind identity.UserUpdateAdminService. It owns no policy, pool, goroutine or second transaction protocol. Immutable composition is safe for concurrent calls; each call uses the sole Coordinator's exact enlisted Repository and audit/lifecycle phases. Zero is invalid. Direct calls grant no authority.

func NewUserUpdateUnitOfWork

func NewUserUpdateUnitOfWork(c *Coordinator, r *Repository, config CreationUnitOfWorkConfig) (*UserUpdateUnitOfWork, error)

NewUserUpdateUnitOfWork validates existing typed composition without I/O. Schemas are selected by each command's exact registered ID/version; enabling the independent self-profile feature is unnecessary. Retention configuration has the creation owner's positive-version semantics. No callbacks are run.

func (*UserUpdateUnitOfWork) Execute

Execute atomically persists admitted field replacements, one aggregate successor, protected audit, lifecycle and original receipt. Replay precedes the locked version/status fence. Omitted fields and lifecycle status remain unchanged; deleted/anonymized users cannot be mutated or resurrected. SQL failures roll back all prefixes; ambiguous closure remains Unknown. Only administrative attribute commands are accepted; preserve IDs for recovery.

func (UserUpdateUnitOfWork) Format

func (UserUpdateUnitOfWork) Format(s fmt.State, _ rune)

Format prevents disclosure of runtime composition and dependencies.

func (UserUpdateUnitOfWork) MarshalJSON

func (UserUpdateUnitOfWork) MarshalJSON() ([]byte, error)

MarshalJSON rejects serialization of runtime composition.

func (*UserUpdateUnitOfWork) Recover

Recover observes the exact original administrative receipt, never reapplies fields or fabricates success from current state. The core service owns current authorization and redaction. Expired pending commands need every original frozen participant's negative evidence; missing evidence remains unresolved.

type UsernameQuery

type UsernameQuery struct {
	TenantID             identity.TenantID
	UserID               identity.UserID
	CanonicalValue       string
	NormalizationProfile string
	NormalizationVersion uint32
}

UsernameQuery discovers one exact canonical username and its stored comparison identity. CanonicalValue is already normalized by the workflow owner; this port never folds, trims or migrates it. UserID optionally restricts discovery. Username ownership is not email/phone verification or authentication.

func (UsernameQuery) Format

func (UsernameQuery) Format(s fmt.State, _ rune)

Format redacts the correlated lookup for every formatting verb.

func (UsernameQuery) MarshalJSON

func (UsernameQuery) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit export of correlated lookup data.

func (UsernameQuery) MarshalText

func (UsernameQuery) MarshalText() ([]byte, error)

MarshalText rejects implicit text and map-key export.

func (UsernameQuery) Validate

func (q UsernameQuery) Validate() error

Validate bounds the lookup and requires an explicit nonzero comparison pair. It does not apply syntax, reserved-name, custom enrollment or access policy.

type UsernameRecord

type UsernameRecord struct {
	Query                                                                        UsernameQuery
	Suppressed                                                                   bool
	User                                                                         identity.User
	Identifier                                                                   identity.Identifier
	Verification                                                                 identity.Verification
	UserAuthorityVersion, IdentifierAuthorityVersion, CredentialAuthorityVersion uint64
	ObservedAt                                                                   time.Time
}

UsernameRecord is an explicit primary snapshot, not authentication, channel verification or a renewable validity lease. Pending username state may be selected: a required verified-email login must separately admit its actual email recipient. Suppressed uniformly covers absent, inactive, revoked, wrong-subject and differently bound historical names without selected data. Copies own scalar values; retain the original and fence it with RequireUsername.

func (UsernameRecord) Format

func (UsernameRecord) Format(s fmt.State, _ rune)

Format redacts the correlated primary record for every formatting verb.

func (UsernameRecord) MarshalJSON

func (UsernameRecord) MarshalJSON() ([]byte, error)

MarshalJSON rejects implicit record export.

func (UsernameRecord) MarshalText

func (UsernameRecord) MarshalText() ([]byte, error)

MarshalText rejects implicit text and map-key export.

func (UsernameRecord) Validate

func (r UsernameRecord) Validate() error

Validate checks complete structure, not current ownership or permission.

type UsernameRegistrationMigrationSource

type UsernameRegistrationMigrationSource struct {
	Base    migrations.Source
	Version migrations.Version
}

UsernameRegistrationMigrationSource extends original registration and email verification custody without changing installed rows or migration checksums. Base must contain registration, acceptance and email-verification histories. If selected, install the historical magic-link suffix before this successor; this suffix retains that constraint arm even when it was not selected. No magic-link or username workflow is activated by storage installation alone. Normalization binding remains an independently selected prerequisite.

func (UsernameRegistrationMigrationSource) Load

Load returns copied forward-only history; it owns no database or runner.

type UsernameRenameContributor

type UsernameRenameContributor interface {
	FeatureCommitContributor
	UsernameRename(identity.Command) (UsernameRenameIntent, *UsernameRenameDomain, error)
}

UsernameRenameContributor supplies immutable original intent. Its native execution owns original password proof, session, current factors, policy and risk; only the kernel writes identifiers and keyed retirement history. Final checks must retain original epochs/expiry, not admit a new arbitrary snapshot.

type UsernameRenameDomain

type UsernameRenameDomain struct {
	// contains filtered or unexported fields
}

UsernameRenameDomain borrows the exact enlisted directory writer and freezes policy. It owns no transaction, pool, retry, callback, journal or goroutine.

func NewUsernameRenameDomain

func NewUsernameRenameDomain(r *Repository, c UsernameRenameDomainConfig) (*UsernameRenameDomain, error)

NewUsernameRenameDomain copies policy without IO. Install the identifier normalization and retirement histories before execution; this constructor neither authorizes renaming nor migrates unbound historical usernames.

func (UsernameRenameDomain) Format

func (UsernameRenameDomain) Format(s fmt.State, _ rune)

Format redacts borrowed native custody and retained keys.

func (UsernameRenameDomain) MarshalJSON

func (UsernameRenameDomain) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit export of borrowed native custody.

func (*UsernameRenameDomain) UsernameAvailable

func (d *UsernameRenameDomain) UsernameAvailable(ctx context.Context, q UsernameQuery) (bool, error)

UsernameAvailable observes canonical occupancy and live keyed cooldowns on the primary. It is advisory only: it takes no reservation/lock, and another signup or rename may win immediately. The workflow must enforce trusted tenant/network rate admission before exposing the result. This low-level reader grants no authentication, authorization or reusable validity lease.

UserID must be absent: availability cannot exclude a caller-selected owner. Existing names block regardless of user status or historical comparison binding, matching the canonical unique index. Missing retained keys, missing schema and cancellation deny rather than promise availability. The earlier caller deadline bounds the borrowed repository budget; no resource is retained.

type UsernameRenameDomainConfig

type UsernameRenameDomainConfig struct {
	NormalizationProfile        string
	NormalizationVersion        uint32
	CurrentIdentifierKeyVersion uint32
	RetainedIdentifierKeys      map[uint32][32]byte
	ReuseCooldown               time.Duration
}

UsernameRenameDomainConfig selects the unchanged stored comparison profile and identifier-reuse policy. Retained keys are copied. ReuseCooldown is an explicit microsecond-exact duration within 0..365 days; live retirement expiry is never recomputed when configuration changes. Missing historical keys deny.

func (UsernameRenameDomainConfig) Format

Format redacts retained key material and configuration.

func (UsernameRenameDomainConfig) MarshalJSON

func (UsernameRenameDomainConfig) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit export of retained keys.

type UsernameRenameIntent

type UsernameRenameIntent struct{ Change identity.IdentifierChange }

UsernameRenameIntent freezes a comparison-bound username and every directory predecessor. It neither normalizes values nor proves current authority.

func (UsernameRenameIntent) Format

func (UsernameRenameIntent) Format(s fmt.State, _ rune)

Format redacts correlated original identity/name intent.

func (UsernameRenameIntent) MarshalJSON

func (UsernameRenameIntent) MarshalJSON() ([]byte, error)

MarshalJSON denies implicit export of correlated original intent.

type VerifiedIdentifierAdmission

type VerifiedIdentifierAdmission struct {
	IdentifierID                           identity.IdentifierID
	Kind                                   identity.IdentifierKind
	IdentifierVersion, VerificationVersion uint64
	User                                   UserAuthorityAdmission
}

VerifiedIdentifierAdmission retains a passwordless session's original exact verified identifier and all three user security epochs. It is neither bearer authentication nor a substitute credential. Kind is email or phone; versions are positive. The command binds tenant/user and the caller freezes these values in its original intent before reservation. Diagnostic export denies.

func (VerifiedIdentifierAdmission) Format

Format redacts correlated identifier and security versions.

func (VerifiedIdentifierAdmission) MarshalJSON

func (VerifiedIdentifierAdmission) MarshalJSON() ([]byte, error)

MarshalJSON rejects accidental admission export.

func (VerifiedIdentifierAdmission) MarshalText

func (VerifiedIdentifierAdmission) MarshalText() ([]byte, error)

MarshalText rejects accidental admission export.

type Work

type Work struct {
	// contains filtered or unexported fields
}

Work is a generation-bound transaction capability for trusted enlisted adapters, never an application SQL gateway. Only the coordinator may create it; no public constructor or transaction/connection/closure API exists. Copies share lifetime and failure state. Methods and returned rows must be used serially and must not be retained beyond the contributor invocation. Any SQL, scan, budget or cancellation failure poisons subsequent execution. Zero is invalid. Coordinator.Begin issues Work for creation and field-update mutation; other domain profiles remain under development. Work alone is not complete command authority.

Example
package main

import (
	"context"
	"fmt"

	identitypostgres "github.com/faustbrian/go-identity/postgres"
)

// A separately owned enlisted adapter uses only the public restricted surface.
func currentWorkVersion(ctx context.Context, work identitypostgres.Work) (string, error) {
	scope, err := work.Scope()
	if err != nil {
		return "", err
	}
	rows, err := work.Query(ctx, `SELECT version::text FROM identity.users WHERE tenant_id=$1 AND user_id=$2`, string(scope.TenantID), string(scope.UserID))
	if err != nil {
		return "", err
	}
	defer rows.Close()
	if !rows.Next() {
		return "", rows.Err()
	}
	var version string
	if err := rows.Scan(&version); err != nil {
		return "", err
	}
	return version, nil
}

func main() {
	// Application code cannot create valid Work: its future Coordinator owns
	// issuance. This verifies the safe zero contract, not complete composition.
	_, err := currentWorkVersion(context.Background(), identitypostgres.Work{})
	fmt.Println(err != nil)
}
Output:
true

func (Work) AnonymousCreation

AnonymousCreation reads the actual provisional kernel effect during its exact current native invocation. Session effects must call this seam, not accept a caller-authored user as creation evidence. Copies are scalar-only; neither this read nor its output grants authentication or survives Work.

func (Work) AnonymousDisposal

func (w Work) AnonymousDisposal(p FeatureExecutionContributor) (identity.User, error)

AnonymousDisposal reads the actual provisional kernel disposal during this exact delete participant's Apply invocation. It cannot be supplied by a caller as permanent-user mutation or authentication evidence, and expires with Work.

func (Work) AnonymousExpiredDisposal

func (w Work) AnonymousExpiredDisposal(p FeatureExecutionContributor) (identity.User, error)

AnonymousExpiredDisposal projects only the actual provisional kernel change in this exact service-expiry Apply. It is not caller-supplied destruction, session revocation, authorization, or completed transaction evidence.

func (Work) AnonymousUpgradeConsumption

func (w Work) AnonymousUpgradeConsumption(owner AnonymousUpgradeContributor) (CapabilityReservationBinding, error)

AnonymousUpgradeConsumption returns owned original one-use custody only during the exact registered upgrade owner's Apply after provisional capability consumption. Preparation, final checks, recovery, foreign/returned handles and finalized Work deny. It performs no IO, carries no bearer, renews nothing and cannot prove commitment or authorize delivery of the permanent session.

func (Work) AnonymousUpgradeDisposal

func (w Work) AnonymousUpgradeDisposal(p AnonymousUpgradeContributor) (identity.User, error)

AnonymousUpgradeDisposal reads only the guest's actual provisional disposal during its exact typed upgrade Apply. It never represents a mutation of the permanent target, authentication evidence or a completed session transition.

func (Work) ApplyPasswordHashUpgrade

func (w Work) ApplyPasswordHashUpgrade(ctx context.Context, p FeatureExecutionContributor, command identity.Command) (PasswordHashUpgradeReceipt, error)

ApplyPasswordHashUpgrade advances only kernel-owned reference, aggregate and credential-authority versions in this Work after native material CAS succeeds. The caller must abort on any material error and must bind the successor into its signed signin record and session before returning. No password-change command, second transaction, journal, timestamp renewal or session is created. Repeated, substituted, unprepared or post-invocation use denies and poisons Work. Returned metadata is provisional; the coordinator alone may commit.

func (Work) CaptchaReplayOwnership

func (w Work) CaptchaReplayOwnership(p CaptchaReplayContributor) (CaptchaReplayOwnership, error)

CaptchaReplayOwnership exposes current-generation linkage only to the exact active native feature owner with an admitted CAPTCHA replay declaration. Returned/foreign/zero/expired Work denies without IO or callbacks. Copies cannot renew ownership, and this supplies no predecessor-transfer authority.

func (Work) CheckRemovedPasskeyCredential

func (w Work) CheckRemovedPasskeyCredential(ctx context.Context, owner FeatureExecutionContributor, command identity.Command, c identity.CredentialRef, a UserAuthorityAdmission) error

CheckRemovedPasskeyCredential checks the exact provisional disabled successor and unchanged user epochs in this same participant's final invocation. A current disabled row without this Work's successful original removal is not proof. It performs bounded primary reads only, owns no resources beyond its closed cursor and returns redacted errors that poison live Work on rejection.

func (Work) CreatePasskeyCredential

CreatePasskeyCredential inserts only the initial non-secret kernel reference during the exact registered native passkey enrollment Apply invocation. Bind PasskeyCredentialCreationFields unchanged in the original command and install CredentialMigrationSource first. The command's record is the new reference, its actor is that same existing user and its lifecycle is identity.passkey.create_credential at zero-to-one. Session-bound additional enrollment selects the exact .session-registration-v1 schema and event index zero. The previously supported passkey.registered.v1 name remains admitted only for existing .native-v1 composers. No other operation, owner, reconstructed command or reference replacement is admitted. Existing references, including disabled ones, conflict without resurrection; no existing user or credential epoch is incremented.

Current active user and all original user security epochs are locked through the sole coordinator Work. Every live rejection poisons Work. The native owner must separately verify WebAuthn, original session/fresh proof, factor, directory, policy and risk, stage mapping and required effects in this same Work, and repeat current reference/admission checks before commit. Success is provisional only; it grants no authentication, session, separate commit or recovery authority. This method owns no transaction, pool, callback, cache or goroutine.

func (Work) DatabaseTime

func (w Work) DatabaseTime(ctx context.Context) (time.Time, error)

DatabaseTime reads a fresh primary UTC clock instant inside this transaction. It does not renew the original Work lifetime or reservation lease.

func (Work) DeliveryScope

DeliveryScope returns an owned declaration only during this exact enlisted delivery instance's invocation. Descriptor equality does not confer custody. The returned binding is the original mutation, never a separate enqueue ID.

func (Work) EmailRemovalScope

func (w Work) EmailRemovalScope(ctx context.Context, owner FeatureExecutionContributor, command identity.Command) (identity.CommandBinding, error)

EmailRemovalScope returns exact command correlation only during the original native Apply invocation after the kernel has locked the complete directory partition and prepared a safe removal. Capability-owned target retirement uses this seam before directory writes. It performs no IO, consumes nothing and grants no SQL/transaction ownership. Foreign, reconstructed, unprepared, already-applied and returned handles deny; no caller callback is invoked.

func (Work) EmailVerificationMFAChallenge

func (w Work) EmailVerificationMFAChallenge(owner EmailVerificationMFAChallengeContributor) (MFAContinuationPlan, error)

EmailVerificationMFAChallenge lends the frozen child declaration only during its exact registered native owner's protected Apply. Foreign, retained, preparation, commit-check, closed and generation-mismatched handles deny. The owned copy is correlation, not proof of its committed parent, browser, factor or permission to issue a session. No IO, callbacks or renewal occurs.

func (Work) Exec

func (w Work) Exec(ctx context.Context, sql string, args ...any) (int64, error)

Exec runs one trusted compile-time SELECT/INSERT/UPDATE/DELETE/WITH statement using the extended protocol, including with zero parameters. It returns the affected-row count after all results are bounded and drained. SQL is at most 64 KiB; parameters use the closed scalar profile documented on Query. This denies transaction-control commands and driver options, not malicious SQL inside trusted adapters. Contributors must enforce owner/tenant scope and cannot invoke SQL functions that alter ownership, isolation or external state.

func (Work) FeatureCommandIdentity

func (w Work) FeatureCommandIdentity(p FeatureExecutionContributor) (identity.CommandBinding, [32]byte, uint64, error)

FeatureCommandIdentity returns the original frozen command binding, keyed fingerprint and reservation generation during this exact participant's Apply invocation. Admission-only, foreign, expired and returned handles deny without IO. The owned copies correlate native transactional effects; they are neither authentication proof nor a renewable validity lease. Do not log this tuple.

func (Work) FeaturePreparationOutput

func (w Work) FeaturePreparationOutput(p FeaturePreparationContributor) ([]byte, uint64, error)

FeaturePreparationOutput returns an owned copy of the original retained ciphertext and its original generation to the exact registered preparation owner during its synchronous final ApplyFeature invocation. This lets a stable native owner restore invocation-local custody without retaining shared request state or embedding ciphertext in smaller generic command fields.

Ordinary execution, pre-generation admission, recovery, foreign participants, returned invocations, and unusable Work cannot read it. Ciphertext is not bearer possession, current authority or renewed expiry; the native owner must authenticate its existing envelope and separately recheck current admission. No SQL, encryption, callbacks or goroutines run. Use Work serially and do not retain it. Invalid access returns no bytes or generation and a redacted error.

func (Work) FeatureScope

FeatureScope lets a native adapter verify that this exact comparable instance is the coordinator's currently invoked feature participant. It returns owned frozen scope/schema/version declarations, not policy or proof admission. Zero, foreign, closed, expired and post-invocation handles fail. Descriptor equality alone is insufficient. No contributor methods, IO or callbacks run. This guard does not authorize raw SQL, closure or retaining Work; trusted adapters remain responsible for their owned schema and complete validation.

func (Work) MFACompletionConsumption

MFACompletionConsumption exposes the original child consumption and frozen continuation only during the exact registered owner's protected Apply, after provisional one-use consumption in this transaction. Zero, foreign, returned, preparation, final-check, recovery and finalized handles deny. Owned scalar copies contain no factor or bearer and cannot authorize a session alone. This guard performs no IO, factor verification, expiry renewal or commit.

func (Work) MagicLinkConsumption

func (w Work) MagicLinkConsumption(owner FeatureExecutionContributor) (CapabilityReservationBinding, error)

MagicLinkConsumption exposes frozen original one-use input only during the exact registered owner's protected Apply invocation, after the capability participant has provisionally consumed it in this same transaction. Zero, metadata-only, admission/commit/recovery, returned and foreign handles deny. Returned scalars are owned copies, contain no bearer and cannot authorize delivery: session/pre-auth, audit and capability finalization may still fail. Calls are serial within the invocation and perform no IO or renewal.

func (Work) MagicLinkMFAChallenge

func (w Work) MagicLinkMFAChallenge(owner MagicLinkMFAChallengeContributor) (MFAContinuationPlan, error)

MagicLinkMFAChallenge exposes the frozen original scope only to its exact challenge owner during protected Apply, after provisional primary consumption. Metadata, preparation, final checks, recovery and retained/foreign handles deny. The projection is not completed MFA, fresh authority or a session grant. It performs no IO, consumes nothing and cannot renew the original expiry.

func (Work) OTPConsumption

func (w Work) OTPConsumption(owner FeatureExecutionContributor) (OTPReservationBinding, error)

OTPConsumption exposes the original checked consuming reservation only to the exact feature owner during its protected ApplyFeature invocation. This lets a session-owned effect bind its writes to OTP admission in the SAME transaction, without accepting a caller-created success flag or committing authentication separately. Non-consuming checks, unchecked reservations, recovery, foreign owners and returned/failed/closed handles fail closed.

The returned scalar copy contains no code or bearer and grants no independent authority. The OTP owner remains responsible for purpose, possession, current eligibility and finalization; the feature owner must bind its complete effect to the original command and reservation. Commit may still fail, so this is neither a completed authentication proof nor permission to deliver a token. Calls are serial within the callback; no IO, comparison or mutation occurs.

func (Work) OrganizationInvitationConsumption

func (w Work) OrganizationInvitationConsumption(owner OrganizationInvitationConsumptionContributor) (CapabilityReservationBinding, error)

OrganizationInvitationConsumption returns owned original reservation custody only during the exact invitation owner's protected Apply, after provisional one-use consumption. Preparation, commit checks, recovery, returned/foreign handles and finalized work deny. It performs no IO or renewal, contains no bearer and is not a committed membership or authorization grant.

func (Work) PasskeyMFAChallenge

func (w Work) PasskeyMFAChallenge(owner PasskeyMFAChallengeContributor) (MFAContinuationPlan, error)

PasskeyMFAChallenge lends the frozen declaration only during its exact registered native owner's protected Apply. Returned copies grant no proof, issuance permission or renewed expiry; retained, foreign and closed Work, preparation, recovery and commit-check invocation handles deny.

func (Work) PasskeyRegistrationUser

func (w Work) PasskeyRegistrationUser(ctx context.Context, p PasskeyRegistrationContributor, command identity.Command) (identity.User, error)

PasskeyRegistrationUser returns only this Work's actual created user to its exact native owner, during original Apply or final Check. It locks current active initial user/reference authority and original creation correlation; it cannot resolve a pre-existing account or grant session/proof authority. Changed commands, foreign invocations, premature access or changed authority poison live Work. The caller must not retain Work or use this as a new lease.

func (Work) PasswordHashUpgradeSuccessor

func (w Work) PasswordHashUpgradeSuccessor(p FeatureExecutionContributor) (RecipientRecord, CredentialAdmission, error)

PasswordHashUpgradeSuccessor returns scalar owner-derived successor admission during the exact native Apply invocation. Original observation time, user and identifier security epochs, verification and expiry are unchanged. This is not freshly read authority or a renewable lease. Session's owner must fence this exact successor before issuance; zero/unapplied/foreign Work denies.

func (Work) PasswordMFAChallenge

func (w Work) PasswordMFAChallenge(owner PasswordMFAChallengeContributor) (MFAContinuationPlan, error)

PasswordMFAChallenge lends the original complete challenge scope only during its exact registered native owner's protected Apply invocation. Foreign, retained, preparation, commit-check and closed handles deny. Password primary evidence is not a consumed capability, and no capability use is invented here. The owned copy grants no factor/session authority or delivery permission.

func (Work) PreparePasswordHashUpgrade

func (w Work) PreparePasswordHashUpgrade(ctx context.Context, p FeatureExecutionContributor, command identity.Command, recipient RecipientRecord) error

PreparePasswordHashUpgrade exclusively locks the original selected user and credential before identifier admission. Call after directory admission and before any shared user/credential admission, preventing lock-upgrade races. Only the exact registered native password owner's active Apply invocation and original paired command may use it. The frozen predecessors, recipient, status, expiry and independent epochs must agree. Anonymous scope stays intact. Denials poison Work. It neither writes material nor authenticates a password.

func (Work) Query

func (w Work) Query(ctx context.Context, sql string, args ...any) (*WorkRows, error)

Query executes one trusted compile-time statement and returns owned bounded rows with no raw driver/connection access. Exactly one result may be active; close it before another query. Callers must not concurrently mutate args. At most 64 parameters and 1 MiB aggregate scalar bytes are accepted: nil, bool, int/int16/int32/int64, uint32/uint64, finite float64, string, []byte and microsecond-exact time.Time in PostgreSQL UTC years 1..9999. Driver execution modes, query rewriters and custom marshalers are rejected without invocation. At most 256 rows, 64 columns and 1 MiB aggregate raw result bytes are returned; budget overflow poisons Work and requires coordinator abort. These limits bound delivered results, not a PostgreSQL statement's server-side work. The earlier caller or Work deadline wins; Work cancellation cancels reads.

func (Work) RecordOAuthConsent

func (w Work) RecordOAuthConsent(owner OAuthConsentContributor, mutation OAuthConsentMutation) error

RecordOAuthConsent retains one mutation only during the exact native owner's Apply invocation, matching every frozen consent field in the authenticated command. Call only after successful owner SQL; the kernel does not inspect foreign tables. Invalid, duplicate, wrong-phase or foreign recording poisons otherwise usable Work, so ignoring rejection cannot commit prior effects.

func (Work) RecordOrganizationInvitationMembership

func (w Work) RecordOrganizationInvitationMembership(owner OrganizationInvitationConsumptionContributor, mutation OrganizationInvitationMembership) error

RecordOrganizationInvitationMembership retains one exact native mutation after the owner has successfully written membership in this Work. It verifies the frozen original organization/member version and current protected consumption invocation; it does not independently inspect owner SQL. Invalid or repeated recording poisons Work so an ignored error cannot commit.

func (Work) RemovePasskeyCredential

RemovePasskeyCredential disables and advances only the exact original passkey reference during its registered native Apply invocation. The original command must bind PasskeyCredentialRemovalFields and the canonical removal lifecycle at index zero under the exact native-v1 or assertion-v1 schema; deletion options cannot remove a reference. Primary locks and current expiry are fenced through the sole coordinator Work; every live rejection poisons it. Disabled references remain reserved and cannot be removed twice or restored.

User-wide credential epochs are unchanged: removing one passkey must not revoke the independent password session needed for original-key recovery. The native owner must separately prove fresh authentication, usable recovery, current policy/factors/risk, atomic protocol/mapping removal and passkey authority advancement. It must call CheckRemovedPasskeyCredential before commit. No transaction, callback, cache or goroutine is created or retained.

func (Work) RequireActiveActorAuthorization

func (w Work) RequireActiveActorAuthorization(ctx context.Context, p FeatureExecutionContributor, expected UserAuthorizationAdmission) error

RequireActiveActorAuthorization compares the original human actor's exact authorization epoch, not the target user's epoch. Scope.SubjectID must equal immutable ActorID; the existing authorization owner retains its share lock within Work. Errors poison Work. This is not an Allow decision, proof or freshness renewal; the workflow still requires current target authorization.

func (Work) RequireActiveActorCredential

func (w Work) RequireActiveActorCredential(ctx context.Context, p FeatureExecutionContributor, expected CredentialAdmission) (time.Time, error)

RequireActiveActorCredential checks the immutable command's human actor, independently of its target UserID, through the existing primary credential owner. All original credential/user/identifier epochs must match. Locks and bounded database-time checks match RequireActiveCredential; neither method changes command scope or grants permission, authentication or proof use. A missing/foreign actor or invocation poisons live Work. The native owner must freeze expected input, acquire cross-subject locks in canonical order, check every other authority and consume fresh proof atomically.

func (Work) RequireActiveCredential

func (w Work) RequireActiveCredential(ctx context.Context, p FeatureExecutionContributor, expected CredentialAdmission) (time.Time, error)

RequireActiveCredential checks kernel-owned current eligibility only during this exact native participant's active invocation. It locks the primary user and credential rows until the coordinator ends Work, compares each expected epoch and reference, and samples primary time after acquiring both locks. Expiry is exclusive; blocked, disabled, absent, foreign and stale records deny uniformly with ForbiddenError and poison Work, preventing an ignored denial from committing. Malformed input or an unowned handle returns InvalidInput. Query/cancellation errors retain Work's redacted error semantics.

It never refreshes versions, modifies rows, issues a session, consumes proof or opens/closes a transaction. Its returned clock sample is not a renewable validity lease. Global/tenant/authorization/optional owner checks, private proof provenance and one-time finalization are separate mandatory phases; success here alone must never admit session issuance or authenticate a bearer.

func (Work) RequireActiveDirectoryAuthority

func (w Work) RequireActiveDirectoryAuthority(ctx context.Context, p FeatureExecutionContributor, expected DirectoryAuthorityAdmission) error

RequireActiveDirectoryAuthority checks only kernel-owned global and tenant authority during the exact native participant invocation. Primary share locks remain until the original coordinator terminalizes Work. Missing, disabled, stale or regressed authority returns Forbidden and poisons Work; malformed input returns InvalidInput. No row or default version is created, no epoch is refreshed, and the original deadline is never extended. This neither checks credential/authorization/optional authority nor consumes an authenticated proof: success alone must not enable session issuance or bearer acceptance.

func (Work) RequireActiveProviderAccount

func (w Work) RequireActiveProviderAccount(ctx context.Context, p FeatureExecutionContributor, expected ProviderAccountAdmission) (time.Time, error)

RequireActiveProviderAccount checks current identity-owned account and credential authority during the exact registered participant's invocation. It retains primary user, credential, link and association share locks until the existing coordinator closes Work. Missing, unlinked, moved, disabled, expired or stale authority denies and poisons Work, including ignored errors. AccountMigrationSource and credential authority history must be installed.

The clock sample follows all lock acquisition and a final credential expiry check; it neither renews original evidence nor constitutes a validity lease. Provider configuration/social-connection, cryptographic proof, current factor policy, authorization, risk and atomic one-use effects remain separate owning checks. This method never issues a session, mutates rows, starts a transaction, performs network I/O or retains a callback/handle. Success alone cannot authenticate a provider credential or admit a social callback.

func (Work) RequireActiveTargetUser

func (w Work) RequireActiveTargetUser(ctx context.Context, owner FeatureExecutionContributor, expected identity.User) error

RequireActiveTargetUser locks and checks the original command's exact target user, tenant, active status and aggregate record version. Call only during this owner's live feature invocation, before credential/authorization and feature-aggregate locks; the existing identity lifecycle writers share this user-row lock. SHARE locks for distinct actor/target users commute.

The native feature must bind expected.ID and Version into original command intent and recheck them on retries. Missing, inactive or stale rows deny uniformly; live errors poison Work. No epoch is derived from User.Version. This is target existence/state admission, not authentication, permission, credential admission, session validity or a replacement for security epochs. For operations such as membership removal that must support inactive targets, use the feature's existing membership authority rather than this active gate.

func (Work) RequireActiveUserAuthority

func (w Work) RequireActiveUserAuthority(ctx context.Context, p FeatureExecutionContributor, expected UserAuthorityAdmission) error

RequireActiveUserAuthority compares the command-bound user's active status and all three original security epochs without requiring a credential. Only the exact native feature participant's live invocation may call it. The primary share lock lasts until coordinator commit or abort; aggregate user version is deliberately not an authority epoch. Missing, inactive or stale state denies uniformly and every live failure poisons Work, even if ignored. A returned invocation cannot poison a later invocation sharing its Work. This does not decide policy, authenticate a bearer, renew original authority, or replace credential-specific admission when a credential is present.

func (Work) RequireActiveUserAuthorization

func (w Work) RequireActiveUserAuthorization(ctx context.Context, p FeatureExecutionContributor, expected UserAuthorizationAdmission) error

RequireActiveUserAuthorization compares a command-bound user's exact current authorization epoch during the exact native participant's active invocation. It borrows the original coordinator transaction through WorkRows and retains the owner's share lock until commit or abort. Earlier caller/Work deadlines win. Missing or unequal epochs deny uniformly; malformed scope or invocation is InvalidInput; storage failures are redacted Unavailable. Every failure on live Work poisons it, even if the participant ignores the error.

This explicitly user-only profile never substitutes actor/workload identity or claims organization authority. It does not bootstrap, advance an epoch, decide policy, refresh validity evidence, consume proof or issue a session. The native adapter still needs its policy decision and all other applicable authority and atomic proof phases. Work remains serial and cannot be retained after invocation.

func (Work) RequireActiveUserStatus

func (w Work) RequireActiveUserStatus(ctx context.Context, owner FeatureExecutionContributor, expected identity.UserStatusRecord) error

RequireActiveUserStatus locks and checks the command-bound user's active status and exact original user-security epoch during this feature owner's live invocation. Expected must come from the identity owner and be frozen in the native command's intent. It authenticates neither the feature's credential nor its actor and decides no permission. The user is the target/owner; an API-key actor must not be represented as that human.

The SHARE lock is the same user-row fence used by lifecycle writers and lasts until coordinator closure. Acquire it before feature aggregate/key locks. Aggregate User.Version is validated structurally but is not a security epoch: ordinary metadata, identifier and password changes must not silently become API-key-owner revocation. Use the existing stronger credential/user-authority guards when those additional dimensions actually authorize the operation. Missing, inactive or changed security denies uniformly. Live failures poison Work even if ignored; returned invocations cannot poison a later invocation. This check performs no write, freshness renewal or independent transaction.

func (Work) RequireAnonymousAuthority

func (w Work) RequireAnonymousAuthority(ctx context.Context, owner FeatureExecutionContributor, expected AnonymousAuthorityRecord) error

RequireAnonymousAuthority fences actual staged anonymous creation and its unchanged kernel epochs in the current native invocation's sole Work. It is not a credential check, risk decision or session/lifecycle admission. The exact creation owner/command must already have applied; final read-only commit checks may repeat it without renewing time. Any mismatch poisons Work.

func (Work) RequireEmailRemovalSubjects

func (w Work) RequireEmailRemovalSubjects(ctx context.Context, owner FeatureExecutionContributor, command identity.Command, expected EmailRemovalAdministration) error

RequireEmailRemovalSubjects fences the original global/tenant epochs, then acquires both administrative actor and target user rows in one canonical primary order before either owner's credential/factor/session checks. The exact email participant may call it only during original preparation or Apply. Kernel removal execution repeats the same fence before locking identifiers. This prevents reciprocal/cyclic cross-subject removal lock inversion.

The three expected values must match immutable command fields. No command scope, versions or state are changed, no missing account is created and no authentication/permission/proof admission is granted. Missing/foreign scope, returned invocation, deadline or storage failure poisons Work. The coordinator alone owns the transaction; locks remain until its commit or rollback.

func (Work) RequireFeatureCommand

func (w Work) RequireFeatureCommand(ctx context.Context, p FeatureExecutionContributor, command identity.Command) error

RequireFeatureCommand admits only the unchanged command supplied to this exact registered participant's synchronous Apply invocation. Ordinary copies retain custody; reconstructed commands do not, even with identical fields. This bounded local guard performs no IO, callback or fingerprint renewal. It does not authenticate credentials or authorize effects. Nil/cancelled contexts and foreign, admission-only or returned invocations deny. Rejection poisons usable Work so ignoring the error cannot commit earlier effects.

func (Work) RequireMFAPasskeyCredential

func (w Work) RequireMFAPasskeyCredential(ctx context.Context, owner MFACompletionContributor, expected CredentialAdmission) (time.Time, error)

RequireMFAPasskeyCredential checks the exact original primary credential for the subject frozen in this native anonymous TOTP completion plan. The child must already be provisionally consumed in this same Work. Apply and final checks retain the existing user/credential locks and current database-time expiry checks; every live failure poisons Work. It never changes the command's original anonymous scope or creates a recipient, proof, session or transaction. The native owner must independently authenticate original assertion/browser/ child custody and the factor, authorize the operation and fence RP mapping. This method supplies current credential eligibility, not authentication.

func (Work) RequireMFAPasskeyPreparationCredential

func (w Work) RequireMFAPasskeyPreparationCredential(ctx context.Context, owner MFACompletionContributor, command identity.Command, expected CredentialAdmission) (time.Time, error)

RequireMFAPasskeyPreparationCredential checks the original passkey's current eligibility only during the exact native owner's input-admission callback. command must retain the coordinator's original opaque custody and its frozen anonymous TOTP completion plan. The original subject is selected from that plan, never from a caller's user identifier. Primary user/credential locks, expiry checks and poisoned-error semantics match RequireMFAPasskeyCredential. This performs no consumption, generation, mutation or authentication and cannot replace the consumed-child check in Apply or final commit checks.

func (Work) RequireMagicLinkRecipient

func (w Work) RequireMagicLinkRecipient(ctx context.Context, p FeatureExecutionContributor, expected RecipientRecord) error

RequireMagicLinkRecipient fences the original verified email recipient only during the native anonymous magic-link request invocation. User, identifier, verification and independent security versions must remain unchanged; primary share locks persist until the sole coordinator ends Work. Missing, blocked, stale or unverified recipients deny and poison Work. It never changes the original anonymous command, signs a link, authenticates a user or issues a session. Risk, original-flow intent and current factor policy remain mandatory workflow checks. The handle is serial-use and must not escape its invocation.

func (Work) RequireOAuthContinuationHandoff

func (w Work) RequireOAuthContinuationHandoff(ctx context.Context, owner OAuthContinuationPreparationContributor, command identity.Command, previous identity.CommandID) error

RequireOAuthContinuationHandoff admits only the exact original command and predecessor during this owner's checked preparation-start callback. Ordinary admission, Apply, foreign, zero and returned handles deny and poison live Work. It performs no IO or authorization renewal and proves neither start COMMIT nor credential issuance. Advance must separately enforce its native pointer CAS.

func (Work) RequireOAuthDeviceGrantSource

func (w Work) RequireOAuthDeviceGrantSource(ctx context.Context, owner FeatureExecutionContributor, credential CredentialAdmission, policy UserAuthorizationAdmission) (time.Time, error)

RequireOAuthDeviceGrantSource locks and compares the approved human source's exact credential and authorization epochs without changing a device poll's client actor, anonymous flow, audit or recovery scope. Only the closed native device-token participant and its original preparation/apply/final command are admitted. Current source withdrawal poisons Work, including ignored denials.

The native owner must derive these expectations through the session owner's OriginalDeviceGrantAdmission, bind the complete original source into its keyed command and match its locked grant, client and consent. This fence is not authentication, authorization, consent, proof consumption or a validity lease. Directory/session checks and original temporal bounds remain separate. Locks, SQL, errors and transaction lifetime retain the existing credential and authorization owners; no transaction, cache or authority is created here.

func (Work) RequireOTPEmailChangeTarget

func (w Work) RequireOTPEmailChangeTarget(ctx context.Context, owner ManagedEmailVerificationContributor, command identity.Command) error

RequireOTPEmailChangeTarget locks and checks the exact original pending candidate and verified predecessor before any OTP comparison or debit. Only the registered change-specific input-admission owner may call it during the existing coordinator Work. It writes nothing, grants no reservation and cannot authorize verification-only mutation. Explicit initial-primary intents additionally require no primary and exactly one verified predecessor under the same partition lock. Lock lifetime and cancellation match RequireOTPEmailVerificationTarget.

func (Work) RequireOTPEmailVerificationTarget

func (w Work) RequireOTPEmailVerificationTarget(ctx context.Context, owner ManagedEmailVerificationContributor, command identity.Command) error

RequireOTPEmailVerificationTarget serializes the exact original pending-email partition before an OTP comparison/debit or protected application. Call after frozen directory admission and before credential/factor/session checks. The exact registered native input-admission owner must be active; this takes the user row exclusively before any shared credential lock to avoid lock-upgrade deadlocks. It checks pending target/CAS input but writes nothing, compares no code, grants no reservation and retains no handle beyond the existing Work.

func (Work) RequireOrganizationInvitationRecipient

func (w Work) RequireOrganizationInvitationRecipient(ctx context.Context, owner OrganizationInvitationIssuanceContributor, recipient RecipientRecord) error

RequireOrganizationInvitationRecipient fences the exact verified existing email recipient under primary authority/identifier share locks, then retains admission for this native invocation only. The same original identifier and version must already be frozen in the command. This does not authorize the sending owner, pending limit, signing or delivery; those remain native checks. Rejection poisons Work. Preparation admission cannot be reused by a later Work: Apply must perform this fence again before staging an issued grant.

func (Work) RequirePhoneChangeTarget

func (w Work) RequirePhoneChangeTarget(ctx context.Context, owner PhoneChangeContributor, command identity.Command) error

RequirePhoneChangeTarget locks the exact old verified target before OTP comparison or attempt debit, in the actual coordinator input-admission Work. Only this registered invocation can use it. It authenticates no proof or code and writes nothing; the native owner must repeat its other current fences.

func (Work) RequirePhoneEnrollmentCandidate

func (w Work) RequirePhoneEnrollmentCandidate(ctx context.Context, owner FeatureExecutionContributor, command identity.Command, expected PhoneEnrollmentIntent) error

RequirePhoneEnrollmentCandidate permits only the exact prepared candidate in this registered owner's synchronous Apply invocation, before kernel apply. It is the candidate counterpart of RequireRecipient: it does not fabricate an existing/verified recipient. Proof, current session, factor and risk checks remain the native owner's responsibility. No IO or callbacks run; mismatch poisons Work so ignored denial cannot commit a staged OTP or SMS delivery.

func (Work) RequirePhoneRemovalTarget

func (w Work) RequirePhoneRemovalTarget(ctx context.Context, owner PhoneRemovalContributor, command identity.Command) error

RequirePhoneRemovalTarget locks the exact original verified partition in the synchronous preparation admission, before credential/session/factor locks. It compares all original predecessors and poisons Work on mismatch. No OTP, removal, proof use, notice or new authority is created by this target check.

func (Work) RequirePhoneVerificationTarget

func (w Work) RequirePhoneVerificationTarget(ctx context.Context, owner PhoneVerificationContributor, command identity.Command) error

RequirePhoneVerificationTarget locks the exact original pending partition in the synchronous input-admission phase, before any code comparison/debit. Acquire this user lock before credential/session/factor locks, avoiding lock upgrades. No mutation, generation, external IO or proof renewal occurs. Foreign invocation, target or predecessor poisons the existing Work.

func (Work) RequireRecipient

func (w Work) RequireRecipient(ctx context.Context, p FeatureExecutionContributor, expected RecipientRecord) error

RequireRecipient fences a selected original record during the exact native feature invocation. It holds primary user then identifier share locks until the existing coordinator commits/aborts. Changed address, ownership, verification or security versions deny and poison Work even if ignored. Suppressed selection never becomes real delivery; callers must keep their original no-op branch. Anonymous discovery remains separate from UserID in the command binding. This does not authenticate the flow or decide risk.

func (Work) RequireRecipientCredential

func (w Work) RequireRecipientCredential(ctx context.Context, p FeatureExecutionContributor, recipient RecipientRecord, expected CredentialAdmission) (time.Time, error)

RequireRecipientCredential fences the exact original email/phone recipient and its credential during this participant's active invocation. The snapshots must agree on tenant, selected user and every security epoch. Primary user, identifier and credential share locks remain held until Work ends; expiry is checked after lock acquisition. It never rewrites anonymous command scope, rediscovers a recipient or refreshes expected versions. Denials poison Work, including when ignored. Malformed/unowned input returns InvalidInput; current ineligibility returns Forbidden with the existing redacted query semantics. Password comparison, proof provenance, authorization, one-time consumption and session issuance remain separate. The returned time is not a validity lease.

func (Work) RequireResetRecipientCredential

func (w Work) RequireResetRecipientCredential(ctx context.Context, p FeatureExecutionContributor, recipient RecipientRecord, expected CredentialAdmission, expectedEnabled bool) (time.Time, error)

RequireResetRecipientCredential admits the original enabled/disabled password predecessor only for the exact anonymous native reset-request profile. It preserves primary recipient, status, expiry and independent epoch fences and poisons Work on denial. expectedEnabled is original trusted intent, never client input. This grants no authentication, factor bypass or reset completion. Locks, clock, lifetime and original anonymous-scope semantics match RequireRecipientCredential, which still requires an enabled reference.

func (Work) RequireUsername

func (w Work) RequireUsername(ctx context.Context, owner FeatureExecutionContributor, expected UsernameRecord) error

RequireUsername fences the exact original primary username during the current native feature invocation. User then identifier share locks last until the existing coordinator commits or aborts. Any failure poisons live Work, including when ignored. It does not admit a password, verified address, policy or session.

func (Work) RequireVerifiedIdentifier

func (w Work) RequireVerifiedIdentifier(ctx context.Context, p FeatureExecutionContributor, expected VerifiedIdentifierAdmission) error

RequireVerifiedIdentifier fences the original command-bound user's security epochs and exact still-verified identifier in the sole protected transaction. Primary user then identifier share locks remain until commit/abort. Lookup is by original identifier ID, never a newly supplied address; removed, reassigned, reverified or stale state denies and poisons live Work even if ignored. The canonical address is read only inside its owner and never returned as a new authentication or renewable validity lease. No credential row is invented.

func (Work) Scope

func (w Work) Scope() (identity.CommandBinding, error)

Scope returns the exact immutable core command binding, not current policy or an authentication proof. Closed, failed or expired Work returns no scope.

func (Work) SelectResetRecipientCredential

func (w Work) SelectResetRecipientCredential(ctx context.Context, owner FeaturePreparationContributor, q RecipientQuery) (recipient RecipientRecord, credential CredentialAdmission, enabled bool, err error)

SelectResetRecipientCredential selects the original verified email/password snapshot only inside the exact native anonymous reset-request invocation. It contains no verifier and grants no factor/risk/issuance authority. Missing, blocked, unverified or password-free selections return a suppressed record. The caller must still invoke RequireResetRecipientCredential and the factor owner before generation, and repeat their fences at final application. Work owns SQL, cancellation, row closure and transaction lifetime; no pool, callback, mutation, missing-factor inference or reusable validity lease is created. Multiple password references and malformed primary state deny.

func (Work) StageAudit

func (w Work) StageAudit(index uint16, record audit.Record) error

StageAudit stages a canonical privacy-processed audit record at its exact declared index. It preserves Builder's opaque random ID, rejects duplicate IDs/indices, mismatched binding/schema/action and oversized or non-profile records, and poisons Work on admission failure. Work lifetime applies even though this method performs no I/O. It never calls user policy, a sink, or a transaction closer. The future registered audit contributor must persist these records through this same Work before terminalization; staging alone is not durable audit delivery or evidence that a command committed.

func (Work) StageCapabilityIssuanceFor

func (w Work) StageCapabilityIssuanceFor(p CapabilityIssuanceContributor, index uint16, grant capability.Grant) error

StageCapabilityIssuanceFor stages one authenticated, subject-bound grant for the exact declared issuer, not a caller-authored proof projection. Index is the frozen plan position. Grant identity, purpose, tenant, subject, exclusive expiry and single-use maximum must match. The issuer remains responsible for cryptographic envelope/replay provenance and workflow policy. A declared RegistrationUserID instead selects only this Work's successfully created anonymous-signup user for identifier verification; it never changes the original command binding or permits arbitrary subject selection. ResetRecipientUserID instead requires this invocation's successful primary recipient/credential fence and matching original reset scope. Neither target alone proves current factor eligibility or complete workflow authorization. MagicLinkRecipientUserID likewise requires the exact magic-link invocation's primary verified-email fence and signed original identifier/security scope. MFAContinuationUserID selects only the closed challenge owner's subject after provisional primary consumption, with exact signed continuation scope/time. No bearer is exposed or stored here; encrypted delivery must be staged by its registered owner. Failure poisons this command. Foreign owners are denied before staging. Work and aliases must remain serial-use.

func (Work) StageDelivery

func (w Work) StageDelivery(v DeliveryEnvelope) error

StageDelivery copies one predeclared ciphertext during the original mutation. Zero/failed/closed Work, undeclared/duplicate indices and unsupported bounds fail closed. Each envelope is 1..524288 bytes; aggregate custody is at most 1MiB. No SQL runs; this is provisional memory, not queued/provider success. Only trusted original-command composition has Work; this method does not authenticate a caller or prove that ciphertext contains an admissible intent.

func (Work) StageDeliveryFor

func (w Work) StageDeliveryFor(p DeliveryContributor, v DeliveryEnvelope) error

StageDeliveryFor stages ciphertext only for the exact delivery participant enlisted in this original Work's frozen plan. Equal descriptors or shared configuration do not confer staging ownership. A foreign owner is rejected before copying custody. Otherwise StageDelivery's bounds, lifetime and poison semantics apply. This is a trusted workflow seam, not recipient authorization; the owning workflow must abort on any failure. Work remains serial-use.

func (Work) StageLifecycle

func (w Work) StageLifecycle(index uint16, occurredAt time.Time) error

StageLifecycle materializes the predeclared event without accepting an arbitrary payload. OccurredAt must be the primary UTC instant obtained by the trusted adapter through Work.DatabaseTime, microsecond-exact and within PostgreSQL years 1..9999. It is not a caller clock/freshness proof. Work does not perform I/O or independently check its provenance during staging. Undeclared, duplicate or invalid staging poisons Work. Closed, expired or failed Work cannot stage. This does not persist or acknowledge delivery.

func (Work) StagePasskeyRegistrationSession

func (w Work) StagePasskeyRegistrationSession(ctx context.Context, owner PasskeyRegistrationContributor, command identity.Command, sessionID string) error

StagePasskeyRegistrationSession binds the actual session owner's provisional creation to the original native signup command during Apply. sessionID must equal its closed session.result.session.id field; the actual created user and original passkey reference are independently fenced. The native session owner must first persist and verify its complete session/family/issuance in this same Work. This method itself neither verifies those rows nor issues a credential. It creates no journal or event until normal successful audit/lifecycle staging. Duplicate/mismatched/foreign staging poisons Work even if the caller ignores the error. Existing account-only plans and encoded plan bytes stay unchanged.

func (Work) StagedAudits

func (w Work) StagedAudits() ([]StagedAudit, error)

StagedAudits returns an owned snapshot only after every declared index has passed staging. Changing the returned slice/plan cannot change Work. Record accessors retain audit's immutable-by-contract ownership. Zero, incomplete, poisoned, closed or expired Work returns no records and a redacted error. Only the declared audit contributor uses this snapshot for same-transaction persistence; this method performs no I/O or callbacks and conveys no closure or durable authority. Work's serial-use and bounded lifetime apply.

func (Work) StagedCredentialCompromise

func (w Work) StagedCredentialCompromise() (CredentialCompromiseReceipt, error)

StagedCredentialCompromise exposes the kernel-owned exact provisional successors only after its mutation and normal lifecycle staging. Outbox may persist them in the same Work; the value cannot grant current authority or acknowledge a cascade. Missing/closed/failed Work returns no metadata.

func (Work) StagedCredentialReplacement

func (w Work) StagedCredentialReplacement() (CredentialReplacementReceipt, error)

StagedCredentialReplacement returns independently owned provisional version successors after the kernel mutation and normal lifecycle staging. Missing, failed, expired or closed Work denies; success grants no authority or cascade acknowledgement. Persist through the existing registered outbox participant.

func (Work) StagedDelivery

func (w Work) StagedDelivery(p DeliveryContributor) ([]DeliveryEnvelope, error)

StagedDelivery returns copied ciphertext only to the currently invoked exact participant. It grants no post-invocation Work or sender authority. Every declared intent must be staged, in its declared deterministic order.

func (Work) StagedLifecycle

func (w Work) StagedLifecycle() ([]StagedLifecycle, error)

StagedLifecycle returns one owned record only after the declared event was staged and its successful audit agrees on the exact aggregate and versions. Conflicting audit evidence poisons Work. An authentication denial in the closed API-key verification profile may accompany its independent successful permission-reduction audit; only that actual update produces its lifecycle. Other denied/failed mutations cannot produce success notifications. Missing or invalid Work returns no records. The outbox contributor must persist it through this same Work before successful terminalization.

func (Work) StagedMagicLinkRegistrationLifecycle

func (w Work) StagedMagicLinkRegistrationLifecycle() (StagedLifecycle, error)

StagedMagicLinkRegistrationLifecycle returns account creation only after actual kernel creation and the command's successful audit/lifecycle staging. It contains no address/attributes/proof and is not a durable commit receipt.

func (Work) StagedOAuthConsent

func (w Work) StagedOAuthConsent() (StagedLifecycle, error)

StagedOAuthConsent returns an owned safe secondary record only after matching successful primary audit/lifecycle and actual native consent recording. Fixed index1 cannot collide with primary index0. Creation and reconfirmation use the independent consent's original version, ID and primary occurrence time; this never fabricates grant scope changes or a downstream acknowledgement.

func (Work) StagedOrganizationInvitationMembership

func (w Work) StagedOrganizationInvitationMembership() (StagedLifecycle, error)

StagedOrganizationInvitationMembership projects the actual retained member mutation only after matching successful primary invitation audit/lifecycle staging. Its fixed secondary index1 is part of the closed accept profile; primary index0 is reserved for invitation.accepted.v1. Both share command, tenant, recipient and primary occurrence time, never invitation versions. The safe projection grants no membership and is not an outbox/commit receipt.

func (Work) StagedPasskeyRegistrationLifecycle

func (w Work) StagedPasskeyRegistrationLifecycle() (StagedLifecycle, error)

StagedPasskeyRegistrationLifecycle returns account creation only after actual kernel creation and successful primary audit/lifecycle staging. It reveals no attributes or authenticator, and is not a durable commit or session receipt.

func (Work) StagedPasskeyRegistrationSessionLifecycle

func (w Work) StagedPasskeyRegistrationSessionLifecycle() (event StagedLifecycle, present bool, err error)

StagedPasskeyRegistrationSessionLifecycle returns only an explicitly staged original signup session after successful account/credential audit staging. Legacy account-only profiles return present=false without inventing an event. Its next unused index and effect ID use the existing immutable lifecycle derivation; it contains no bearer, CSRF or session payload. The outbox owner must persist it in this same Work, not independently acknowledge a commit.

func (Work) StagedPasswordHashUpgrade

func (w Work) StagedPasswordHashUpgrade() (PasswordHashUpgradeReceipt, error)

StagedPasswordHashUpgrade exposes provisional metadata to the registered lifecycle participant after feature application. It grants no authority and cannot reconstruct history from mutable rows. A missing upgrade, unusable Work or unstaged lifecycle denies; original journal remains outcome owner.

type WorkRows

type WorkRows struct {
	// contains filtered or unexported fields
}

WorkRows is a Work-owned serial result cursor with no driver escape hatch. Scan permits only pointers to the closed scalar types accepted by Query, plus **string/**int64/**time.Time for nullable columns and nil to skip a column. Custom scanners are rejected without invocation. Next must precede Scan. Close is idempotent; Err must be inspected after Next returns false. Rows become permanently unusable when their Work is invalidated; zero is invalid and safely rejects reads. On a Scan error, discard every destination: the driver may have populated an earlier column before rejecting a later one.

func (*WorkRows) Close

func (r *WorkRows) Close()

Close releases this cursor without committing or rolling back the Work.

func (*WorkRows) Err

func (r *WorkRows) Err() error

Err returns only redacted identity errors, never PostgreSQL diagnostics.

func (*WorkRows) Next

func (r *WorkRows) Next() bool

Next advances within the row/byte budgets; false means completion or failure.

func (*WorkRows) Scan

func (r *WorkRows) Scan(dest ...any) error

Scan decodes only closed typed destinations; it never invokes RowScanner.

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL