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: 32 Imported by: 0

README

Risk PostgreSQL adapter

Experimental, Go 1.27. This module is being built as the durable owner of risk evidence and decisions. It is not yet an executable durable risk service.

PrepareAccountLinkCommandCounters accepts a bare explicit self-user identity link command and trusted server-resolved network attribution. User and session must exactly match the canonical command; undeclared dimensions are rejected. The returned opaque variant preserves its signed proof and original primary preparation time. Existing counter restoration authenticates scope and retained key aliases. As with feature counters, the logical counter fingerprint excludes preparation time: the kernel's keyed command binds it, and the current-check phase compares the locked charge's exact original prepared_at. Stateless restoration alone grants neither allowance nor permission to renew freshness. It remains a preparatory contract: the protected native link owner must compose provider/session/policy checks, same-command reservation, required audit/effects and recovery. No independent counter transaction or generic feature-command conversion is introduced.

Implemented boundary

  • ValidateCounterOnlyOperation(action) checks this repository's configured protected operation before composing a workflow that has no provider-evidence admission. Only an exact velocity-only policy is supported by that workflow; mandatory status, CAPTCHA or other provider signals fail closed rather than disappear during counter preparation. The check is pure and gives no domain authorization or counter allowance. Workflows with actual provider admission keep the existing richer counter-policy support.

  • PreparePasskeySignupCommandCounters(command, subject, primaryTime) selects only the anonymous passkey owner's two canonical registration actions with their exact .signup-v1 schemas. It uses the original bound browser flow and trusted network/device, retaining CredentialMutation's five attempts per fifteen minutes, deny outcome and transaction-owned reservation. No account, session or identifier is fabricated. The native owner must authenticate the original private browser cookie and protocol result; scalar preparation does neither. Install PasskeySignupCounterMigrationSource{Schema, Version} after the selected counter histories. It extends the actual validated constraints, preserving all installed optional profiles and populated counter evidence. Counter-only coordinator tests cover options charge/replay/denial; genuine verification/account/session effects require the native passkey owner.

  • PrepareMFALoginSendCommandCounters selects only anonymous identity.mfa.otp-send with the exact original browser cookie, required factor ID and resolved account. Journal UserID remains empty. The browser dimension spans newly issued children/commands; no authenticated session is invented. Native reservation and current checks obtain the account/browser only from the registered MFALoginSendCounterContributor, whose protected source checks still own signed child, primary, factor, recipient and current policy. Scalar preparation is not authentication or allowance. Install MFALoginSendCounterMigrationSource after protected, verification and selected MFA completion histories. The forward migration preserves original windows, aliases, charges and snapshots and permits browser windows only for OTP send. The public login sender itself remains composition work.

  • PrepareMFACompletionCommandCounters(command, subject, child, completion, primaryTime) selects anonymous native TOTP, OTP or recovery-code completion. Supply authenticated original continuation subject/child and trusted network; no session or authenticated command user is invented. Opaque code/browser custody survives mapping. Reservation and current admission compare subject and child to the exact sealed coordinator completion plan. Use the same native counted transaction for denied factor and risk attempts, not a success-only charge. Correct-code probing rolls its provisional charge back before retained generation. Install MFACompletionCounterMigrationSource after protected and registration counter histories. Select MFARecoveryCounterMigrationSource for recovery codes, then MFALoginSendCounterMigrationSource for OTP sending and MFAOTPCompletionCounterMigrationSource for OTP completion at separate permanently allocated successor versions. Populated evidence is unchanged; completion uses the original child dimension, never the sending-only browser dimension. This adapter path is not public MFA login; provider admission and workflow/ transport composition must still be completed and tested.

  • PrepareVerificationCommandCounters(command, subject, originalGrantID, primaryTime) selects only sessionless identity.email.verification-confirm. The native email owner must authenticate the original signed grant/subject, preserve callback and intent, and match the grant ID to its consumption plan. Supply only trusted user/network dimensions, not a session. The core derives distinct capability keys while tenant/subject limits continue across links. Existing reservation, takeover, current checks and recovery preserve original preparation and charge snapshots; unavailable or expired authority denies. Install VerificationCounterMigrationSource{Schema, Version} after selected protected-counter history. It atomically extends only the owned dimension constraints, leaving populated windows, aliases and charges unchanged. Neither preparation nor counter success authenticates a proof or verifies email; composed transactional confirmation remains separate implementation.

  • MapCaptchaUse(use, protectedSpec) preserves the protected feature schema, binding and all domain target/version fields, appending closed token-free consuming custody. The verified actor, command, tenant, subject/anonymous flow and action must match the original precheck. Feature owners reserve the captcha field namespace and include the returned CaptchaEvidencePlan in their shared coordinator plan. Risk and authorization policy versions remain separate. Repository.ValidateCaptchaUseCommand authenticates that exact declaration under selected current verifier configuration without callbacks or IO. These pure boundaries grant no durable use or mutation permission; feature owners must independently enforce domain-time current authorization; reservation alone is not usable login or protected-use permission.

  • Repository.ReserveCaptchaEvidence and RebindCaptchaEvidence implement the coordinator's sealed native consuming-reservation contract. Install CaptchaUseMigrationSource before choosing consuming plans. The owner locks the exact keyed evidence from committed original issuance, compares signed native facts and checks primary expiry after exclusion. First reservation binds one command/fingerprint/generation; takeover conserves the original interval and transfers only its exact predecessor, atomically with the command and every declared participant. Missing, terminal, foreign and divergent ownership deny; no provider callbacks, private transaction or time-based release run.

  • Repository.CheckCaptchaEvidence and FinalizeCaptchaEvidence implement the sealed coordinator consuming phases. They authenticate complete admitted signed input under the selected current profile, lock exact committed-original and reserved consumer custody, compare original facts and recheck primary-time expiry. Finalization CASes the current generation in the same transaction as protected effects, audit, lifecycle and result. Native feature owners still enforce their own target/user/session/factor authority. No provider runs here. ReleaseCaptchaEvidence terminally releases only coordinator-proven rollback or unanimous primary noncommit, preserving original validity and reserved time. Historical cleanup works after expiry or current verifier/policy removal; missing, terminal, corrupt or divergent custody remains unknown. A shared native risk owner also proves every selected counter/phone role before release. These phases are not a complete password/login service or provider interop.

  • CaptchaUseMigrationSource{Schema, Version} adds consuming-command custody after the existing CAPTCHA journal, with a permanently allocated forward migration version. It preserves original issuance, aliases, expiry and encrypted responses. Consuming states require complete same-tenant journal linkage, distinct command identity, full-width positive generation, signed binding, and original exclusive expiry. Unknown legacy consuming states fail the atomic upgrade rather than being reset or assigned invented ownership. Erasing a terminal response does not erase consuming custody. These storage constraints do not grant permission, prove noncommit or enforce transitions; select the native coordinator phases above to enforce those transitions.

  • NewCaptchaExecutor(CaptchaExecutorConfig{Executor: composition, Flow: flow}) supplies the real risk.CaptchaEvidenceExecutor. Compose immutable CaptchaEvidenceCustody first, select it in Config.CaptchaCustody, construct the repository and executor, then supply the executor to risk.NewCaptchaEvidenceIssuer. No dummy callback or consumer-written store is necessary. Caller and flow come from verified server composition, never decoded client metadata. The executor binds the exact tenant/target namespace and administrative actor and freezes all challenge, session, pre-auth and request dimensions. Changing any dimension requires a new correctly verified composition. Current admission/recovery policies receive trusted identity.captcha.{flow-kind,operation,pre-auth,session,actor,challenge,request} attributes and must enforce current authority; historical permission is not enough. The separately configured policies cannot be omitted. Unknown commit discloses no candidate; recovery returns only the authenticated original encrypted response without provider verification or expiry renewal. This is issuance, not protected-use authority. Production-effect composition, complete cleanup/retirement, protected workflow composition and release gates remain unfinished for CAPTCHA.

  • Config.CaptchaCustody selects bounded immutable core verifier profiles with the exact risk policy and retained evidence-key set. Empty preserves existing setup. The native participant authenticates signed input against a selected profile before reservation, claims all token aliases in the coordinator's reservation transaction and transfers only the exact predecessor generation. Domain work rechecks sealed current ownership and every alias, samples primary time after locks, then inserts encrypted evidence in the same Work as command, audit and lifecycle commitment. Participant recovery classifies only exact primary custody; missing owners or corrupt response encryption remain unknown. Public issuer execution/recovery is supplied by NewCaptchaExecutor above. Complete rotation/key-retirement safeguards, protected workflow composition and the canonical risk service are still unfinished.

  • CaptchaScopeMigrationSource{Schema, Version, Custody} must follow the CAPTCHA custody migration before selected native reservation. Its forward upgrade backfills exact provider-scope key retention without rewriting prior history. First claims lock that scope before checking at most seventeen indexed key rows; omission or secret replacement of any referenced version denies. For populated histories, supply the original reviewed retained core custody for every installed scope; token-free old aliases cannot infer their original secrets. Missing or conflicting custody fails the upgrade atomically. Freeze those migration inputs permanently along with the allocated history version. Historical owner takeover can use a newer complete retained profile without expanding its original aliases or expiry. No retirement API is supplied yet.

  • CaptchaMigrationSource{Schema, Version} independently installs replay winners, scoped aliases, referenced key versions and native evidence storage after the kernel and existing risk namespace. Allocate its permanent version after the composition's installed history; phone/counter/lockout upgrades are not bootstrap dependencies. It preserves existing tables and adds no private transaction owner. Alias uniqueness excludes key version so rotation or reuse of a key secret cannot create a second winner. Evidence payload deletion does not delete the independent replay tombstones or their key-retirement linkage. This schema does not select runtime CAPTCHA execution or implement cleanup or key retirement; select runtime custody separately.

  • MapCaptchaIssue maps signed core issuance custody without a raw provider token. CaptchaIssueOperation selects distinct user and anonymous-flow native schemas. Supply the separately verified command actor; administrator flows must match their signed actor. Mapping neither verifies a provider nor commits evidence. Strict native restoration retains original aliases, configuration commitment and exclusive validity without creating new authority. Original response encryption uses a separate CAPTCHA profile and authenticates exact command scope and retained record metadata. Mapping alone does not enable durable execution; explicitly selected native custody is separate from these preparation contracts. NewCaptchaExecutor supplies public issuance and recovery; protected-use phases use the consuming contracts above.

  • Config.EnforceLockouts selects current durable restriction enforcement for protected command counters. Install LockoutMigrationSource after counter history. Admission reads restrictions on the original logical keyed roots under the owning domain transaction; retained-key rotation and window resets cannot erase an active restriction. Counter locks fence a concurrent new row through its immediate foreign key; existing restriction rows are share-locked until domain commit/abort. Primary time is sampled after all locks. Expiry is exclusive, future-start or unavailable authority denies, and older policy versions do not reset a restriction. No retry-after or account-existence metadata is returned. Missing migration fails closed when selected. False retains the earlier counter-only development profile. Selection requires native command counters; it does not enable ephemeral or authentication-only evaluation. This read boundary never creates, extends, deletes or caches state, infers a trigger/duration from velocity, or permits identifier-only attempts to lock an account. Native start/end/CAS is separately selected through LockoutMutations, described below, with the owned LockoutExecutor workflow. Consumers must not supply their own lockout mutations or SQL. Full canonical Service remains unfinished; this profile is not production risk-service permission.

  • VelocityJournal records an authenticated pending ephemeral attempt and every exact keyed target/alias in one primary transaction, before external work. Select a caller-owned go-postgres.Pool, exact coordinator policy/key custody, stable deployment namespace and separately retained HMAC journal key. Replacing that key is unsupported; retain it for all unresolved attempts. Install VelocityIntentMigrationSource after velocity history: it backfills existing targets and separates pending intent from post-mutation snapshots without rewriting prior migration SQL. Receipt issuance proves only an intent commit, never dispatch permission, allowance or counter/epoch health. Matching pending replay is unavailable; changed intent conflicts without overwriting history. Ambiguous journal commits return no receipt and do not authorize redispatch. RecordResult retains an explicit complete adapter declaration atomically; terminal outcomes, including unknown, are immutable. Exact replay is idempotent. ReadResult validates the complete stored binding, dimensions and retained ordered aliases, preserving original uint64 values and observation/window times. Pending or corrupt history is unavailable; unknown never becomes noncommit. Exact full windows and microsecond-representable snapshots are required; no freshness is rounded forward. These methods do not authenticate external results or authorize effects. External-result reconciliation, fenced replay and Valkey execution remain pending.

  • NewVelocityRecovery(VelocityRecoveryConfig{Journal: journal, MaximumWindow: time.Hour, LeaseDuration: leaseBound}) owns scoped primary recovery leases. Acquire accepts the trusted projection's nonzero random 128-bit boot epoch, not request data. Independent processes have one live owner per tenant/namespace. Database time is sampled after locking; authoritative expiry alone allows monotonic takeover. New boots retire prior epochs, which cannot resurrect. Renew returns a superseding opaque receipt; old receipts and old generations fail CheckLease. Checks prove point-in-time ownership, not effect permission. Missing/ambiguous acknowledgements return no receipt. Restart(ctx, lease) lets the exact live replay owner abandon lost projection progress. It advances generation and replaces ownership without extending the original expiry or moving the history origin. Applied progress, closure and publication are cleared together; journal lifetime and attempt outcomes remain unchanged. Install the applied and publication migrations first. Matching retries of the original receipt reconcile the same live successor, including a lost successful commit response, without clearing successor progress. Renewal or later generations invalidate that reconciliation. Restart neither performs native IO nor publishes healthy state: the owned bridge must fence the successor and traverse history from zero before any subsequent coverage/publication/activation checks. The supported maximum window is one hour; explicit leases are positive, microsecond-representable and at most one minute. Initialization records zero replay progress and never publishes healthy state. Journal scan completeness, external-effect reconciliation, Valkey fencing and health publication remain unfinished; ownership acquisition alone cannot enable authentication. Writer transactions take a shared tenant/namespace lock before allocating insertion time/sequence or locking a result row. Acquisition takes that same lock exclusively and cannot cross an unresolved writer commit. Lock waits remain inside the journal timeout and cancellation budget. Historical reads remain independent; later pending/unknown or terminal declarations are not discarded. They remain replay-owner work, so acquisition alone is not cursor completeness, replay closure or effect admission. All participating writers must run the shared-lock implementation before relying on this drain guarantee. Earlier experimental journal binaries did not take that lock; stop or upgrade them first. Mixed-version writer operation is not certified by this development checkpoint.

  • VelocityMigrationSource{Base: counterHistory, Version: laterAllocation} adds the PostgreSQL recovery journal for the separate ephemeral Valkey lane. It stores scoped keyed attempt digests, original per-dimension snapshots and up to four retained aliases, without a protected-command foreign key or raw request facts. Boot epochs start unavailable; installation inserts no rows. Covered interval and lease constraints are storage invariants, not proof of replay or publication. Sequence positions are not commit-order evidence. Native journaling, fenced reconciliation, full snapshot validation and atomic Valkey healthy publication are not implemented by this migration. There is no pruning or operator-bypass API. Valkey remains ephemeral mutation authority; PostgreSQL is the durable recovery journal, not a second counter engine.

  • Install VelocityIntegrityMigrationSource{Base: intentHistory, Version: laterAllocation} before running current journal writers. Each native insertion and declaration atomically seals the complete persisted record with domain-separated HMAC-SHA-256 under the retained journal key. The seal covers scoped identity, sequence, fingerprint, original preparation/recording times, outcome, every ordered target/alias, and full snapshots. Readback and terminal replay reject missing or altered authentication without re-sealing history. PostgreSQL timezone and text formatting cannot renew or change sealed times. The forward migration preserves earlier experimental records unchanged and unsealed; they are retained for investigation, not accepted as authenticated readback/replay. Do not replace the journal key or run old writers alongside the current profile. Attributable legacy recovery remains unfinished; there is no automatic backfill, pruning or fail-open migration fallback. Record integrity is not external-result truth, rollback-resistant storage, replay completeness, Valkey effect authority or healthy publication.

  • Install VelocityReplayMigrationSource{Base: integrityHistory, Version: laterAllocation} before current writers. Native insertion and first terminal declaration atomically assign an indexed, separately authenticated change position. Terminal idempotent replay creates no new position. All original signed facts remain unchanged; valid pre-position history receives bounded native bookkeeping only after its original seal verifies. Migration does not sign old records; unverifiable legacy history remains unavailable. recovery.ReadPage(ctx, lease, cursor, batch) accepts batches 1..1000 (reference 100), starts at zero cursor, and returns copied immutable records plus page.Next(). Pages drain overlapping writers and validate exact live custody before and after the bounded read in the same primary transaction. Renewal accepts the continuation with the new lease; superseded leases and foreign/takeover cursors deny. Reads include all retained history, not a storage-time cutoff, and preserve expired snapshots without renewing windows. Use the returned cursor to observe insertions or declarations after an empty page. Original tenant, namespace digest, attempt digest and fingerprint are copied from authenticated retained facts. Attempt identity uses the core VelocityReplayIdentity profile, preserving existing journal bytes; the sequence-derived record ID remains separate. No raw attempt is stored, and projection does not mint a new command. Both native adapters must select the same stable namespace/key independently of rotating dimension aliases. Records are redacted/nonserializable owned-adapter projections, never CounterCommand, dispatch, effect application, or positive validity proof. Initialization can persist traversal bookkeeping but does not rewrite original history or epoch progress. Failures and ambiguous acknowledgements return no page/cursor. Current pagination is not applied replay closure, external-result reconciliation, Valkey fencing or healthy publication; those remain unfinished.

  • Owned replay additionally requires paired JournalIssuer and NativeVerifier from risk.NewVelocityRecoveryAuthorities. Trusted composition retains journal issuance only in this adapter and native issuance only in the concrete projection; application-facing stores expose neither. Crossed or partial ownership is rejected at construction. Omitting both preserves lease/page operations but disables owned replay.

    OwnedClosure(ctx, originalLease, ownedLease, coveredClosure) exports only a previously acknowledged PrepareCoveredClosure result. An ordinary stable cut is ineligible. The configured graph and every original lease field must match; core custody binds the exact supplied owned-lease instance. The stable keyed cut identity includes original scope, lease expiry, applied position, replay bounds, continuous journal start and maximum window. Matching exports preserve it, and every read reauthenticates the retained original covered cut and lease on primary storage. Export does not prepare a new cut, backdate provenance, renew expiry, publish native state or mark health. Native fenced publication, paired primary confirmation and healthy admission remain pending. OwnedLease checks exact current primary custody. OwnedHistory rereads the authenticated original record under a bounded writer-fenced transaction, preserving original identity, aliases, counts and timestamps, then closes SQL before native IO. Pending/unknown remain unresolved, not retry permission. Install VelocityAppliedMigrationSource{Base: replaySource, Version: laterAllocation} for RecordApplied. Only the configured native owner's acknowledgement of the exact lease and original terminal history advances scoped change-order progress. Duplicates are idempotent; gaps, foreign graphs, stale leases and corrupt sealed checkpoints deny. The forward migration starts populated epochs with no applied authority. Progress never publishes health; native restore and stable writer-fenced healthy activation remain unfinished. ResumeApplied(ctx, lease) returns a bounded primary-authenticated cursor for ReadPage, skipping only durable acknowledged effects rather than scanned pages. Same-owner renewal preserves progress; takeover or a new epoch replays retained history from zero. Current-generation seal and original terminal anchor must authenticate; corruption, stale ownership or ambiguous commit returns no cursor. Unresolved suffix history remains visible. This cursor is traversal custody, not proof of complete replay or permission to publish health. PrepareClosure(ctx, lease) establishes a stable primary journal cut after every retained change is applied. Pending, unknown, unpositioned or unapplied history denies. The existing epoch's replay_through > replay_from fences new same-scope journal writes until renewal or expiry; unchanged terminal replay remains idempotent. Locks end before the method returns. Matching retry recovers the same cut after a lost commit acknowledgement. CheckClosure verifies exact retained custody under primary time. Neither method proves historical temporal coverage, performs native IO or publishes health. Native publication, primary confirmation and admission must still agree before a concrete store can enable traffic. Do not treat a captured interval, empty page or successful closure as healthy readiness. Install VelocityCoverageMigrationSource{Base: appliedSource, Version: laterAllocation} to opt into PrepareCoveredClosure and CheckCoveredClosure. The existing epoch stores the primary journal start; fresh scopes start at insertion, migrated unknown scopes start at their first covered preparation. Neither is backdated. One full maximum-window warmup is required before initial eligibility; renewal, takeover and a new native boot retain established continuity. Exact-boundary coverage qualifies, shorter coverage denies. Every native effect must follow a committed journal intent; mixed/unparticipating writers or incomplete restored history are unsupported and must never adopt this metadata as proof. Covered closure remains primary custody, not native publication or healthy admission. The original lease/page APIs remain usable on schemas without this optional migration.

  • Optional Config.UseIssuer installs use preparation only after matching the issuer's exact current policy and entire retained signing/linkage key set. PrepareEvidenceUse accepts a core precheck, original trusted request and native phone initiation feature spec. It freezes the exact phone, pre-auth, attempt and subject dimensions inside the opaque in-memory command; the returned signed plan and durable journal contain no raw scope or bearer. Caller-selected risk.intent/risk.use.* fields deny. Non-risk fields remain the phone owner's responsibility, including equality with its domain target. ValidateRiskEvidenceCommand reconstructs the original intent under installed provider configuration without callbacks or IO. It uses the signed historical check time, rounded upward to microseconds, without rewriting that time or expiry; it does not establish current validity. Nil preserves existing setup. PreparePhoneResetCompletionEvidenceUse instead accepts an existing sealed phone-reset input or generated command. It preserves the original password or verifier, canonical reset capability, SMS, independent TOTP and actual browser cookie without exposing a generic feature or single-code variant. Completion requires its own independently issued phone-password-reset-complete evidence; initiation cannot substitute. The pinned public coordinator currently enables initiation execution only. Completion mapping/restoration is preparatory and requires the jointly consuming coordinator before a phone-reset workflow can execute.

    Select Config.UseCounters with the exact DurableCounterStore used by issuance to enable current execution. Install its independent DurableCounterMigrationSource and the existing evidence reservation history first. Reuse the same policy value and complete retained counter keys as the core issuer, not a newly constructed equivalent policy. Nil counter custody retains preparation/reservation compatibility but denies domain use.

    CheckRiskEvidence and FinalizeRiskEvidence implement the existing sealed coordinator execution phases. They lock the original issued row and exact reserved command/fingerprint/generation, authenticate current policy/provider configuration, require the original sealed durable counter attempt and read complete retained keys plus current unchanged windows. Missing, corrupt, expired, foreign or over-limit authority denies. A shared native counter-scope lock fences the durable owner's charges and key registration through commit; these checks never charge, reset a window, call a provider or open another transaction. The signed check instant and original expiry never renew. Finalization repeats current checks and CASes the same reserved generation with exclusive database-time expiry in the protected mutation transaction. Unknown retains reserved custody; only existing coordinator-proven noncommit can terminally release either phase. The phone owner still supplies current target/browser/factor authority and the real OTP/capability/password/session effects; adapter execution is not proof of that complete recovery journey.

  • OwnedConfirmation exports an already recorded exact publication through the configured core VelocityConfirmation contract. It does not implicitly confirm, reconcile by writing, or perform native IO. A single outer journal timeout bounds export; retained checks authenticate original lease, coverage and persisted confirmation on every use. Export and copying cannot refresh original confirmation time or expiry. Primary renewal/takeover/corruption invalidate the custody. Concrete native confirmation and continuity remain necessary before any healthy admission.

  • VelocityPublicationMigrationSource{Base: coverageSource, Version: nextAllocation} adds native publication confirmation to the existing epoch row. Existing rows remain unconfirmed. ConfirmPublication requires the original primary lease, owned lease, covered cut, its exact exported custody and the configured native owner's publication acknowledgement. It rechecks applied progress and coverage under the existing writer fence before commit. CheckPublication rereads that same record without changing its time. A lost commit acknowledgement returns unavailable; retry only the same custody to reconcile the original primary record, not native IO. Renewal/takeover clear obsolete confirmation without requiring the migration for lease/page-only use. Both methods keep the epoch replaying and traffic fenced: primary confirmation does not prove current native marker/counter continuity, write a confirmed native marker or expose a public counter store. Paired admission and reference activation remain unfinished. No SQL lock spans native IO.

  • VelocityActivationMigrationSource{Base: publicationSource, Version: nextAllocation} adds actual activated_at to the existing epoch authority. healthy_at remains the original covered snapshot watermark; neither cut nor lease expiry is rewritten to pretend it was observed at activation time. Existing healthy rows lack the required native activation provenance and become unavailable while retaining windows, lockouts, history and lease expiry. Replay rows and confirmations are not promoted. Coordinate all participants before relying on joint admission; old experimental binaries that bypass current primary eligibility are not a supported mixed profile.

  • Activate requires the original lease/covered cut and exact configured primary/publication/native-confirmation custody. It drains journal writers, reauthenticates primary progress/history/coverage and recorded confirmation, records eligibility and then reopens writers. Its opaque VelocityHealthy is not cached permission: CheckHealthy rereads exact current primary state and original expiry. Replay-only lease/closure/publication checks still deny after activation. Matching healthy retries reconcile the original timestamp; overlapping attempts may return unavailable and require explicit retry. Unknown commits expose no receipt, never native resend permission.

  • InvalidateHealthy makes only the unchanged activation unavailable. Retained metadata permits exact idempotent reconciliation without resurrecting health, clearing counters/lockouts or shortening custody. The current owner can invalidate after expiry; stale owners cannot affect successors. New recovery still waits for authoritative lease expiry. Primary eligibility does not establish present native continuity or public traffic admission: the owned store must enforce the exact native marker, continuity and durable intent/ result conservation at each effect boundary. That composition remains pending.

  • OwnedEligibility exports an acknowledged VelocityHealthy through the configured exact original lease/native-confirmed cut, using only this adapter's concrete CheckHealthy. It accepts no application health callback. Every core eligibility read rechecks current primary state and original expiry with bounded context; export/repetition do not write or renew timestamps. Primary corruption, invalidation, expiry, takeover or unavailability denies copied custody. Export does not establish native continuity or execute a counter effect; the owned native/store composition remains required.

  • OwnedJournal binds the same original activation to this owner's concrete primary journal. Pass its opaque output to the owned native factory; callers cannot name the internal connection type or supply journal/effect callbacks. Every use checks current primary eligibility and exact configured tenant, policy and keys. An acknowledged intent retains its original receipt through terminal recording; replay reads immutable primary history without retry permission. Primary transactions finish before native work, and copied connections cannot cache allowance or renew expiry. The native public factory and complete live PostgreSQL/Valkey crossing remain unfinished. Initial activation and successful-commit reconciliation retain the original native-confirmed chain internally. Export derives current eligibility from this same primary owner, under one outer timeout, and binds its own journal reader; callers cannot select a separate chain or primary connection.

  • MapIssue accepts only an opaque successful core evaluation and matching trusted identity binding. IssueOperation fixes its closed native schema.

  • The native decoder verifies every signed field and current configured policy. Its record target is the canonical opaque command ID; the private retained intent digest never becomes audit/lifecycle aggregate metadata. A committed response resolver must compare that digest separately after authorization.

  • The internal response codec uses the existing secret-envelope AES-256-GCM implementation and a concrete copied local keyring. Original times and exact scope are authenticated; rotation preserves retained responses without renewing freshness. It cannot invoke network key providers inside Work.

  • MigrationSource{Schema: "identity_risk", Version: allocation} provides a dedicated, forward-only issued-evidence schema. Allocate its version in the composition's single history after the identity kernel. Never renumber an applied version or adopt unmanaged objects.

  • IssuanceIDMigrationSource{Base: originalSource, Version: laterAllocation} appends the opaque command-ID profile without changing the original history or retained legacy ciphertext/AAD. Install this complete history for new native issuance. Legacy digest-target rows remain retained, not silently rewritten.

  • ReservationMigrationSource{Base: issuanceHistory, Version: laterAllocation} adds nullable, all-or-none command/fingerprint/generation ownership and the six one-use journal states. It preserves installed migration bytes, legacy and opaque record IDs, original expiry and encrypted response custody. Its composite command foreign key binds ownership to the same tenant and exact recovery phase. Allocate a new version after the issuance-ID migration; the source returns the complete history and is safe to apply again. Schema availability is not reservation or terminal-transition authority. Existing issuance binaries may continue inserting ownerless issued rows; consuming compositions require the replay-compatible executor and native participant.

  • NewRepository(Config{...}) supplies the native issuance contributor. Enlist that exact instance with the identity repository, audit and lifecycle adapters in one coordinator registry. It inserts through the coordinator's active Work, materializes at database time and returns only a provisional structural receipt. The coordinator commits evidence, protected identity.risk.decide audit, risk.evidence_issued.v1 lifecycle and command result together.

  • Recovery examines native linkage only during the locked coordinator invocation. Positive or inconsistent evidence keeps the command unresolved; native absence can contribute to unanimous negative evidence because this initial journal never prunes rows. Neither expiry nor a private pool lookup permits release.

  • NewExecutor(ExecutorConfig{...}) implements the core EvidenceExecutor contract through the real primary coordinator, with the exact native repository internally enlisted alongside kernel, audit and lifecycle participants. It authorizes before provider admission and before execution, and privately compares retained intent before decrypting an original committed response.

  • The repository implements RiskReservationContributor for native phone-reset initiation. It authenticates every signed core use field under retained key pairs, matches current risk policy and consuming command scope, locks the exact already-issued row, and samples primary time after any lock wait. The original issuance command must be committed; retained positive linkage from a foundation or unresolved history cannot confer new ownership. Missing, terminal, expired and mismatched evidence returns one redacted conflict. Command and evidence ownership commit in the same coordinator reservation transaction. Takeover CAS requires the same command/fingerprint and exact prior generation, preserving the original expiry and reservation time. There are no private transactions, provider callbacks or bearer reads. The immutable precheck binds omitted raw recovery scope and provider evidence; reservation does not re-evaluate providers or authoritative counters. Apply must recheck these before any protected mutation. The current coordinator deliberately denies domain execution for this profile until complete apply/finalize phases exist. Completion also requires purpose-bound OTP and capability participants and remains unsupported.

  • RiskReleaseContributor implements consuming recovery and terminal release for initiation. The exact-instance RecoveryWork.RiskBinding authenticates historical signed custody and matches the committed original issuance, all immutable row linkage and the reserved command/fingerprint/prior generation. Missing, terminal, corrupt or foreign rows remain unknown, never noncommit proof. No current-expiry check or policy change can invent reuse authority. The coordinator excludes old writers and requires independent noncommit from the phone, kernel, audit and lifecycle participants before invoking release. Its bounded release handle CASes only reserved to terminal released, with the recovery generation, in the same transaction as failure audit and aborted command receipt. Original expiry, reserved time and response custody persist. Unknown phone/domain outcomes and audit/SQL failures retain the reservation; retries and cleanup do not reactivate it. No raw recovery/provider scope is reconstructed and no domain authority is enabled by this recovery profile.

Adoption and security

The official executor owns plan construction, authorized primary resolution and exact original-response replay. Application code must not supply a private transaction, journal or workflow substitute. Mapping and encrypted bytes establish neither durability nor protected recovery authority. No bearer may be exposed until the sole coordinator proves commit. Expiry, missing metadata or a failed read never establish rollback.

Trust actor kind, policy and correlation from server composition, not transport input. Record IDs, digests, native commands and encrypted response material are internal custody data, never operation results or log fields. Retain wrapping keys for every retained encrypted result. Go cannot guarantee memory erasure.

Issuance composition

Migrate the kernel followed by the complete IssuanceIDMigrationSource history. Construct the native repository with the issuer's retained evidence keys and retained local wrapping keys. Supply the caller-owned primary pool and owned audit/lifecycle adapters to ExecutorConfig; both effect adapters must support the coordinator's typed recovery phase. Supply a verified Caller decision context for the exact actor, tenant, identity.risk.evaluate action and identity.user resource. It is copied, not derived from request Actor text. Both opt-in coordinator policies must use the caller's current revision.

The owned audit contributor uses audit/postgres, identity.security_audit, v1. The original explicit identity.audit v1 composition identity remains accepted for compatibility; other contracts, owners and versions are rejected. The owned outbox contributor uses outbox/postgres, identity.lifecycle, v1. Install all audit migrations with their fresh-install preflight and generic plus identity outbox migrations before use.

Pass the executor to risk.NewPhoneEvidenceIssuer. Missing is returned only after authorized global claim absence. Prior pending, failed, foreign and corrupt commands never enable provider reevaluation. Committed replay preserves the original reference and timestamps, even after expiry and retained-key rotation. Independent evaluations racing under one command ID may observe Unknown while the winner is pending; Recover converges to the original committed response without providers. A commit error initially discloses no reference. No result grants one-use consumption authority. Pools/adapters remain caller-owned; no background goroutine or Close method is introduced.

Original committed issuance remains replayable in all six legitimate later journal states while retained ciphertext is available. This preserves the same reference and interval, not reuse authority: native reservation independently rejects terminal evidence or another owner's reservation. No replay evaluates providers, repairs missing ciphertext or renews the original expiry.

The PostgreSQL integration suite withholds an actual successful domain COMMIT acknowledgement at the socket boundary for both phone-reset purposes. The initial result stays reference-free Unknown; a new primary executor recovers the original reference and timestamps without provider work or duplicate effects.

Remaining work

Domain apply/finalization and completion's additional participants; durable lockouts/overrides, counter retirement and pruning; CAPTCHA participants; investigation, retention and anonymization; complete public examples/API baseline and package/release verification remain pending. There is no supported login or phone recovery workflow from this module yet.

Protected command counters

Set Config.CommandCounters to an explicit core CommandCounterPolicyConfig with the same risk policy version and 1..4 newest-first retained digest keys. Nil retains issuance-only setup. Install CounterMigrationSource after the evidence reservation history; prior migration bytes and evidence remain intact. The coordinator and risk dependencies must include the committed protected-counter contracts pinned by this module. No private transaction or consumer-written counter store is required or supported.

The native feature owner passes its opaque command, trusted canonical subject and primary preparation time to PrepareCommandCounters, then declares the returned CommandCounterPlan in the coordinator plan. The native owner validates its own fields plus the reserved counter.* fields. The exact registered risk instance reconstructs tenant/operation/attempt, bound subject or actor/resource, session/network dimensions, policy bounds and original retained-key projection before SQL. Raw network/session inputs stay in the in-memory opaque command; only bounded keyed projections and structural command linkage persist.

Authenticated password-change commands retain their exact original hash, session bearer and reauthentication proof while counter fields are appended. The adapter explicitly preserves that disjoint command variant; generic and hash-only borrowers remain closed to it. Counter preparation grants no proof verification or password-change authority. The native password owner must verify and consume the proof in its protected transaction. Hash-only commands remain unsupported.

ReserveCommandCounters is invoked only under coordinator ownership. A fixed window begins at primary time, resets at exclusive expiry, and never wraps its uint64 count. All retained digest aliases share one logical window. Durable tenant/operation key history rejects omitted or changed unretired versions; adding a strictly newer key preserves active counts. This initial history is append-only: retiring keys or pruning windows/snapshots is not yet supported. An active incompatible window configuration fails closed instead of resetting allowance. No lockout duration or policy is inferred from these attempt limits.

Every charge retains its original four dimension snapshots and observation time. Allowed SQL is provisional until the coordinator commits pending ownership; denied charges commit with failure audit and aborted receipt. Exact replay does not call the mutation phase. Takeover transfers only the exact predecessor and reuses its original allowed decision, never a new count or fresh observation. Historical recovery checks the retained predecessor charge without treating it as domain commitment; only unanimous independent noncommit evidence can abort the owning command. Recovery never refunds a charged attempt.

Native PostgreSQL tests exercise threshold denial, hot-key contention, replay, takeover, rotation, missing retained keys, preparation expiry, window expiry, saturation, failed snapshot rollback and charged noncommit reconciliation. The feature owner in these tests is a seam; no password mutation or login journey is claimed. Native current fixed-counter admission now implements the coordinator's opt-in CommandCounterAdmissionContributor. It locks the original current- generation charge, validates all original snapshots and retained key history, then locks each current logical window. Only afterward does it sample primary time and validate the original preparation and earliest window expiry. Both pre-mutation and pre-commit checks use the same domain Work; no counts, aliases, key history, observation times or expiry are changed by a current check. Missing original aliases, divergent roots, changed windows or excess current counts deny. New retained keys may coexist with the original aliases without recharging a takeover. A delayed domain operation that outlives its original evidence rolls back all provisional domain effects but retains its charged attempt and classified failure receipt.

This is current fixed-counter allowance, not a complete risk verdict or domain authorization. The native feature owner must check its current user, credential, factor and organization authority. No lockout/override policy is supported by this configuration; those remain required implementation work. RiskEvidence consumption/apply/finalize, real password/session workflows and release gates remain pending. Tests use a SQL effect seam, not a production password adapter.

Forward lockout transition storage

LockoutStateMigrationSource appends one atomic migration after LockoutMigrationSource, preserving every installed checksum and every populated restriction's version, original interval and keyed root. Allocate its version permanently and separately from any selected velocity history. New nullable custody fields deliberately remain empty for legacy rows; the upgrade does not invent administrative permission, a command, an event or an ended restriction.

The storage represents an explicit end without deleting CAS history or shortening the original expiry. Complete native linkage needs a canonical opaque record ID, binding digest and existing same-tenant command with the exact start/end operation; inconsistent or partial linkage is rejected. These fields are latest domain-state linkage, not a second command/replay journal.

Existing interval-only admission deliberately remains unchanged and must not be treated as honoring an administrative end. Direct SQL in the populated upgrade test is a schema fixture, not a production mutation API.

Selected native lockout transitions

Config.LockoutMutations adds the native start/end operations to the same registered risk contributor. Install LockoutTransitionMigrationSource after the state migration and the existing authorization owner's authority schema before selecting it. Unselected profiles acquire no new schema dependency.

PrepareLockoutCommand checks the configured current authorization revision outside Work and seals the full trusted request at its original primary UTC microsecond read instant. Its administrative operation is distinct from the credential-change operation being restricted. It does not restrict password signin, password recovery or factor-recovery routes. Preparation and a provisional feature receipt are not commitment; effects run only through the sole identity coordinator. Applications must not implement this orchestration themselves; use the owned LockoutExecutor below.

Native apply locks the existing authorization owner's actor epoch through commit, resolves the retained keyed subject root without charging an attempt, checks primary-time expiry after lock acquisition, then performs exact-version CAS. Starting an active restriction is a conflict, not implicit extension. Ending preserves the original interval and aggregate version history. Canonical protected audit and lifecycle effects share that transaction; failure rolls back the domain transition. Closed command fields and original decision freshness cannot be changed on replay.

The selected admission profile honors an explicit end only when current state matches its exact immutable same-command domain version. Missing selected history or malformed custody fails closed. Historical domain versions retain original effects for the existing coordinator's recovery participant even after subsequent transitions. They own no command leases, retry state or second replay journal; no pruning is exposed. This native contributor is not the complete canonical risk service or release-gate completion.

NewLockoutExecutor composes the caller-owned primary pool, selected repository, real audit/lifecycle adapters and the current authenticated actor/tenant/user scope. Choose a separate immutable executor scope for each selected start/end operation. Admission and historical disclosure policies are separately required; neither successful history nor an actor epoch is mutation permission.

Pass an unchanged LockoutExecutionRequest to Execute. The executor reads the existing authorization owner's current actor epoch, samples original primary time, checks mutation policy outside Work, prepares the canonical effects and executes exactly once through the existing coordinator. Applications provide configuration and verified scope, not SQL, epoch lookup or transaction glue.

Only a successful authorized primary resolution exposes Snapshot, the exact original committed post-state. Recover checks the current disclosure policy and reads the original immutable domain version, even after later starts/ends. Retain original intent and all referenced signing keys. Changed intent denies; retained-key rotation neither changes original state nor renews its validity. Unknown results expose no snapshot and require same-request recovery, not an unproved replacement command. Existing issuance workflows remain separate.

Production effect composition

Use audit/postgres.NewIdentityContributor and transactional-outbox/v2/postgres/identity.NewContributor for ExecutorConfig Audit and Lifecycle. Install their owned migrations (including command/effect bindings) before use; audit fresh-install preflight must precede audit migrations. They write through the same coordinator Work, without owning another transaction. Do not replace these phases with application SQL stores or treat a successful phase callback as commitment.

The real PostgreSQL public CAPTCHA integration composes both adapters across pre-auth subject/anonymous, authenticated and administrator flow variants. Lost commit acknowledgement reveals no candidate and recovers the exact original without another provider verification. Effect failures after actual writes roll back evidence and success effects. Recorded audit/outbox payloads exclude the provider token and opaque evidence bearer. Remote provider interoperability and complete protected login journeys remain separate, unfinished acceptance work.

Documentation

Overview

Package postgres owns the durable risk journal. Native issuance uses the identity coordinator's sole Work; no provisional reference is a credential or proof of commit. Reservation, consumption and retention remain separate required implementation work.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CaptchaIssueOperation

func CaptchaIssueOperation(subject identity.FeatureSubjectRequirement) identity.FeatureOperation

CaptchaIssueOperation selects a trusted native issuance schema. User and anonymous targets have distinct registered schemas; zero retains user scope. Unknown requirements return an invalid descriptor. This grants no admission, provider verification, commitment, or protected-use authority.

func IssueOperation

func IssueOperation() identity.FeatureOperation

IssueOperation is the closed native evidence-issuance schema. RecordID is the command's opaque canonical ID, never a keyed intent digest. Authorized native response resolution must additionally compare the retained private intent. Prior pending/failed commands never permit fresh evaluation. This descriptor conveys no authorization, durability or one-use consumption authority.

func LockoutOperation

func LockoutOperation(mode risk.LockoutMode) identity.FeatureOperation

LockoutOperation returns a closed native schema, not mutation authority. Native operation IDs use hyphens; canonical audit actions use underscores. Neither ID is an alias accepted by risk evaluation. Unknown mode returns zero.

func MapCaptchaIssue

MapCaptchaIssue freezes token-free signed core custody for the sole shared coordinator. The trusted binding supplies the separately verified actor, policy ID and correlation, never an invented user for an anonymous flow. Administrator actors must match the signed administrative context. RecordID is derived from the original command, not caller-selected. Construction is pure and grants neither current authority nor evidence commitment.

func MapCaptchaUse

MapCaptchaUse appends token-free signed CAPTCHA custody to the protected feature's complete native fields without replacing its binding or schema. The consumer command, verified actor, tenant, subject/anonymous flow and operation must match the precheck exactly. The captcha namespace is reserved. Risk policy remains separate from authorization policy. Construction copies fields, performs no callbacks/IO and grants no durable use or permission. The returned plan must be enlisted with the native risk owner in the sole coordinator; reservation and all domain-time phases remain mandatory. Inputs must not be concurrently mutated. Zero/invalid input returns a redacted ErrInvalidEvidenceExecution and zero outputs.

func MapIssue

MapIssue maps an opaque core-owned successful evaluation into an immutable coordinator command. Binding must match the signed tenant, subject, actor, command and current policy; trusted composition supplies actor kind, policy ID and correlation. RecordID must be empty and is derived here, not selected by callers. Every signed field is frozen. Zero/foreign input fails redacted; construction performs no IO, authorization, issuance or fresh observation.

Types

type CaptchaExecutor

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

CaptchaExecutor owns CAPTCHA issuance and original encrypted-response recovery through the sole identity coordinator. It is safe for concurrent calls, retains immutable composition and starts no goroutines or private mutation transactions. Zero is invalid. No provider verification, replacement issuance or protected consumption occurs here. Original response disclosure requires current recovery authorization even immediately after commit. Unknown outcomes reveal nothing.

func NewCaptchaExecutor

func NewCaptchaExecutor(c CaptchaExecutorConfig) (*CaptchaExecutor, error)

NewCaptchaExecutor freezes one exact flow and verified caller using the owned kernel/risk/audit/lifecycle registry. Caller operation, tenant and target must match; administrator actor must be the separately verified caller. Missing, malformed or mismatched composition returns redacted ErrInvalidPolicy. Copies of caller attributes are owned, and caller mutation cannot change admission.

func (*CaptchaExecutor) Execute

Execute reserves original aliases, applies native evidence and commits its audit/lifecycle/receipt in the same coordinator Work. Proven rollback never exposes a candidate; ambiguity retains replay ownership for primary recovery. It neither retries provider work nor manufactures a successor bearer.

func (CaptchaExecutor) Format

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

Format redacts trusted flow and runtime composition.

func (CaptchaExecutor) MarshalJSON

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

MarshalJSON rejects trusted runtime export.

func (CaptchaExecutor) MarshalText

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

MarshalText rejects trusted runtime export.

func (*CaptchaExecutor) Resolve

Resolve performs bounded current admission and primary history observation. Only an actual missing claim permits provider verification. Historical rows need independent current recovery authorization and exact intent/AAD matching; elapsed time never renews or releases custody. Unknown/denied returns no bearer.

type CaptchaExecutorConfig

type CaptchaExecutorConfig struct {
	Executor ExecutorConfig
	Flow     risk.FlowContextInput
}

CaptchaExecutorConfig selects exact trusted server-resolved flow context and verified caller composition. Flow is not client input or authentication proof; the server must authenticate its session/actor/pre-auth context. Admission and recovery policies must check current authority and receive the immutable flow as identity.captcha.* request attributes on every uncached primary lookup. Executor owns only composition, not caller pool/effect lifetimes. Empty is invalid; selected Repository.CaptchaCustody is required. Construction does no IO.

func (CaptchaExecutorConfig) Format

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

Format redacts trusted flow and runtime composition.

func (CaptchaExecutorConfig) MarshalJSON

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

MarshalJSON rejects trusted runtime export.

func (CaptchaExecutorConfig) MarshalText

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

MarshalText rejects trusted runtime export.

type CaptchaMigrationSource

type CaptchaMigrationSource struct {
	Schema  string
	Version migrations.Version
}

CaptchaMigrationSource installs native CAPTCHA custody in the already-owned risk namespace. Install kernel and MigrationSource first; allocate Version permanently after every installed migration in the composition's one history. This independently selected upgrade requires no phone/counter/lockout tables and never rewrites their history. Existing unmanaged objects fail closed. Replay winners and aliases have no expiry-based deletion. Evidence payload erasure must preserve these independent tombstones and referenced versions. Zero is invalid; Load is pure, cancellation-aware and concurrent-safe.

func (CaptchaMigrationSource) Load

Load returns one independently owned forward-only atomic migration. This creates no issuance or protected-use authority and enables no runtime feature. Invalid allocation returns redacted invalid input; cancellation is preserved.

type CaptchaScopeMigrationSource

type CaptchaScopeMigrationSource struct {
	Schema  string
	Version migrations.Version
	// Custody supplies the original reviewed retained key configuration for
	// every populated provider scope. Keys cannot be inferred from token-free
	// history. Missing or conflicting versions fail the upgrade atomically;
	// empty is allowed only for an empty CAPTCHA history. Do not mutate this
	// slice concurrently with Load. The migration stores only commitments.
	Custody []risk.CaptchaEvidenceCustody
}

CaptchaScopeMigrationSource adds serialized replay-key retention to an installed CaptchaMigrationSource. Allocate Version after that history; existing winner, alias and response bytes are preserved. This forward-only migration backfills referenced versions and prevents their removal while aliases still refer to them. It enables no runtime feature. Load is pure, cancellation-aware and concurrent-safe; zero is invalid.

func (CaptchaScopeMigrationSource) Load

Load returns one atomic forward upgrade without modifying earlier migrations. Invalid allocation returns redacted invalid input; cancellation is preserved.

type CaptchaUseMigrationSource

type CaptchaUseMigrationSource struct {
	Schema  string
	Version migrations.Version
}

CaptchaUseMigrationSource adds consuming-command custody to the existing CAPTCHA evidence journal without changing issuance, aliases or envelopes. Install CaptchaMigrationSource first and permanently allocate Version after installed history. Previously reserved/finalized/released rows without owned linkage fail the atomic upgrade: their authority cannot be guessed or reset. This schema grants no reservation, release or protected execution authority; those operations must use the sole coordinator and native participant CAS. Load is pure, cancellation-aware and concurrent-safe; zero is invalid.

func (CaptchaUseMigrationSource) Load

Load returns an independently owned forward-only atomic migration. Existing unmanaged objects and unsupported history fail execution rather than being silently adopted. Invalid configuration is redacted; cancellation is retained.

type Config

type Config struct {
	Schema             string
	PolicyVersion      uint64
	EvidenceKeys       []risk.EvidenceKey
	EnvelopeKeys       map[string][]byte
	CurrentEnvelopeKey string
	// CommandCounters optionally enables only native protected command counters.
	// Nil preserves issuance-only setup. All retained keys are copied; removal
	// requires durable retirement, which this initial profile does not yet expose.
	CommandCounters *risk.CommandCounterPolicyConfig
	// EnforceLockouts selects current durable lockout admission for protected
	// command counters. Install LockoutMigrationSource first. False preserves the
	// earlier counter-only development profile, not complete risk enforcement.
	// It cannot start/end a lockout, select a duration or bypass safe recovery.
	EnforceLockouts bool
	// LockoutMutations enables native authorized start/end. Install
	// LockoutStateMigrationSource, LockoutTransitionMigrationSource and the
	// authorization owner's authority schema before selection. Nil preserves
	// the interval-only development profile.
	LockoutMutations *LockoutMutationConfig
	// UseIssuer optionally installs pure original-scope authentication for native
	// use preparation. It must match PolicyVersion and every retained EvidenceKey.
	// The issuer value is copied; nil preserves reservation-only setup. Current
	// execution additionally requires UseCounters and the original durable rows.
	UseIssuer *risk.PhoneEvidenceIssuer
	// UseCounters selects the same durable counter owner used by phone evidence
	// issuance. Install DurableCounterMigrationSource first. Current use reads
	// its existing scope, original authenticated attempt and current windows
	// through the sole Risk Work, never its pool or a second transaction. The
	// store's immutable custody is borrowed; its pool remains caller-owned.
	// Nil preserves pure preparation/reservation, but domain use fails closed.
	UseCounters *DurableCounterStore
	// CaptchaCustody selects 1..32 immutable current verifier profiles for native
	// CAPTCHA issuance and current consuming phases. Nil preserves existing setup.
	// Every profile must match
	// PolicyVersion and the complete retained EvidenceKeys. Install the separately
	// allocated CaptchaMigrationSource and CaptchaScopeMigrationSource before
	// issuance; also install CaptchaUseMigrationSource for consuming reservation.
	// No provider callbacks
	// are retained or invoked by this durable owner.
	CaptchaCustody []risk.CaptchaEvidenceCustody
}

Config selects the dedicated migrated namespace, current risk policy and retained core signing/digest keys. EvidenceKeys must be the issuer's exact retained key set. Envelope keys are nonzero local AES-256 keys, indexed by stable references; retain every reference needed by historical responses. Construction copies all keys. Zero and unsupported configuration fail closed.

func (Config) Format

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

Format redacts copied and caller-owned key material in all diagnostics.

func (Config) MarshalJSON

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

MarshalJSON rejects secret-bearing startup configuration serialization.

func (Config) MarshalText

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

MarshalText rejects secret-bearing startup configuration serialization.

type CounterMigrationSource

type CounterMigrationSource struct {
	Base    ReservationMigrationSource
	Version migrations.Version
}

CounterMigrationSource appends protected fixed-window counters and immutable command-linked snapshots after the existing evidence history. Allocate Version permanently after Base.Version. Existing evidence SQL is unchanged; Load is pure/concurrent-safe and returns owned forward-only atomic history. Key history is append-only: this profile does not yet authorize key retirement or pruning.

func (CounterMigrationSource) Load

Load returns owned complete forward history; invalid allocation is redacted and cancellation is preserved before any SQL construction.

type DurableCounterConfig

type DurableCounterConfig struct {
	Pool              *database.Pool
	Schema, Namespace string
	Policy            risk.Policy
	Keys              []risk.CounterDigestKey
	ReplayKey         []byte
	Tenants           []string
	MaximumRecords    int64
	Timeout           time.Duration
}

DurableCounterConfig selects one durable PostgreSQL admission authority. Namespace and ReplayKey are stable deployment custody, not rotation knobs. Keys are complete newest-first dimension-key history; Tenants is an explicit allowlist of 1..128 scopes. MaximumRecords is 1..1000000 retained attempts per tenant: reaching capacity denies, never evicts replay history or resets quotas. Timeout is 1ms..1min. Install DurableCounterMigrationSource before use.

func (DurableCounterConfig) Format

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

func (DurableCounterConfig) MarshalJSON

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

func (DurableCounterConfig) MarshalText

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

type DurableCounterMigrationSource

type DurableCounterMigrationSource struct {
	Schema  string
	Version migrations.Version
}

DurableCounterMigrationSource installs the PostgreSQL-only admission lane. It does not alter protected command counters or Valkey recovery history. Allocate Version once in the owning migration ledger. An existing selected risk schema may be shared; the five owned table names must not preexist.

func (DurableCounterMigrationSource) Load

Load is pure and cancellation-aware; all tables are created atomically by the native runner. There is no implicit historical counter reset or adoption.

type DurableCounterStore

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

DurableCounterStore implements the core CounterStore with database-owned fixed windows and atomic retained outcomes. This durable lane is disjoint from the optional ephemeral Valkey lane and protected-command participants. It performs no external callback, starts no goroutines and borrows its pool. Copies are concurrent-safe. Cancellation/SQL/commit ambiguity denies with no positive result; matching retry reads the original committed timestamps and never charges twice. Expiry does not delete original replay history.

func NewDurableCounterStore

func NewDurableCounterStore(c DurableCounterConfig) (DurableCounterStore, error)

NewDurableCounterStore validates/copies custody without IO or admission. A changed stable key fails against durable scope identity on first use.

func (DurableCounterStore) Check

func (s DurableCounterStore) Check(ctx context.Context, tenant string) error

Check observes the selected scope's current stable custody and capacity without debiting a counter or extending evidence. Missing fresh scope is eligible only after the native tables exist. Changed keys, corruption, capacity exhaustion and unavailable primary authority fail closed.

func (DurableCounterStore) Format

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

func (DurableCounterStore) MarshalJSON

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

func (DurableCounterStore) MarshalText

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

func (DurableCounterStore) Mutate

Mutate charges every target once in one PostgreSQL transaction, including denied attempts. Conflicting replay, missing/changed retained keys, corrupt history, exhausted capacity and unavailable authority return no allowance. Original results remain historical facts; core admission enforces freshness.

type EmailChangeCounterMigrationSource

type EmailChangeCounterMigrationSource struct {
	Schema  string
	Version migrations.Version
}

EmailChangeCounterMigrationSource appends the closed change-confirm grant dimension to already installed protected counters. Allocate Version after selected histories; populated windows and their time/charges are unchanged. Existing check expression is retained exactly, including selected MFA/browser lanes. Missing/unvalidated owned checks fail, not silently rebuild storage. This forward transactional migration owns no runtime resources or authority.

func (EmailChangeCounterMigrationSource) Load

Load returns the bounded pure migration; cancellation and invalid input deny.

type Executor

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

Executor owns issuance and authorized original-response recovery through the sole identity Coordinator. It starts no goroutines, opens no private mutation transactions and never closes the caller's pool or effect adapters. Immutable composition supports concurrent calls; each Work is used serially. Zero is invalid. Pending/failed history never permits provider reevaluation. This issuance profile does not grant reservation or protected consumption authority.

func NewExecutor

func NewExecutor(c ExecutorConfig) (*Executor, error)

NewExecutor validates bounded trusted composition and constructs the exact four-participant registry. Invalid or incomplete composition fails redacted. The caller context is copied; services/adapters must retain their immutable policy revision and support concurrent calls for the executor's lifetime.

func (*Executor) Execute

Execute authorizes before reservation, freezes the signed native command and performs one same-Work mutation with protected audit/lifecycle/receipt. The encrypted original is disclosed only after independently authorized primary commitment resolution. Conflict, pending, failed and commit uncertainty never materialize a replacement reference or rerun providers.

func (Executor) Format

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

Format hides trusted caller and custody dependencies.

func (Executor) MarshalJSON

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

MarshalJSON rejects runtime composition serialization.

func (Executor) MarshalText

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

MarshalText rejects runtime composition serialization.

func (*Executor) Resolve

Resolve authorizes one uncached primary admission observation before provider work. Only actual global claim absence returns Missing. Committed responses require a private exact-intent row read and historical-AAD decryption; expired originals are preserved without renewal. Pending reconciliation invokes only frozen contributors through the coordinator. Unknown never carries a bearer.

type ExecutorConfig

type ExecutorConfig struct {
	Pool                   *database.Pool
	Repository             *Repository
	Audit                  identitypostgres.AuditContributor
	Lifecycle              identitypostgres.LifecycleContributor
	Coordinator            identitypostgres.CoordinatorConfig
	Caller                 authorization.DecisionContext
	PolicyID               string
	RetentionPolicyVersion uint64
}

ExecutorConfig composes one authenticated caller's immutable authorization context with the caller-owned primary pool and durable effect adapters. Caller must come from verified server composition, never client-decoded Actor input. Its tenant/resource identify the exact user scope; use another executor for another verified scope. Coordinator requires both QueryPolicy and separately opt-in AdmissionPolicy at Caller's current policy revision. Repository is the exact instance registered internally, with copied retained custody keys. Effect adapters must implement RecoveryContributor as well as their typed persistence phase. Construction does no IO and transfers no resource ownership.

func (ExecutorConfig) Format

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

Format hides verified caller attributes, pool settings and fingerprint keys.

func (ExecutorConfig) MarshalJSON

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

MarshalJSON rejects serialization of trusted runtime composition.

func (ExecutorConfig) MarshalText

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

MarshalText rejects serialization of trusted runtime composition.

type IssuanceIDMigrationSource

type IssuanceIDMigrationSource struct {
	Base    MigrationSource
	Version migrations.Version
}

IssuanceIDMigrationSource appends the opaque command-identity profile without rewriting the original install or changing retained encrypted response AAD. Base is the original permanent allocation; Version must be a later permanent allocation within MaxInt64. Existing digest-target rows remain readable and unchanged, but new issuance uses only opaque command IDs. Load is pure and concurrent-safe; zero is invalid. There is no destructive down migration.

func (IssuanceIDMigrationSource) Load

Load returns an owned complete forward history, preserving Base's exact SQL. Invalid allocation is redacted; context cancellation is preserved.

type LockoutCommandRequest

type LockoutCommandRequest struct {
	Binding          identity.CommandBinding
	Scope            authorization.DecisionContext
	Request          risk.LockoutRequest
	AuthorityVersion uint64
}

LockoutCommandRequest is trusted server-resolved input, never transport JSON. Binding identifies the administrative command, Request.Scope.Operation the independently restricted operation. First start uses RecordID=CommandID; later transitions retain the same opaque record ID and exact expected version. AuthorityVersion is the current actor epoch, not a policy decision. Scope is authenticated policy context; no caller-supplied risk bypass is accepted.

func (LockoutCommandRequest) Format

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

func (LockoutCommandRequest) MarshalJSON

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

func (LockoutCommandRequest) MarshalText

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

type LockoutExecution

type LockoutExecution struct {
	Command  identity.CommandResult
	Snapshot *LockoutSnapshot
}

LockoutExecution retains the existing coordinator's classified outcome. Snapshot is present only after current-policy-authorized primary commitment resolution and exact original-intent matching. Unknown or failed execution never exposes a provisional snapshot; a committed result is historical only.

type LockoutExecutionRequest

type LockoutExecutionRequest struct {
	CommandID identity.CommandID
	RecordID  string
	Request   risk.LockoutRequest
}

LockoutExecutionRequest identifies one original command and exact mutation intent. Request must match the configured authenticated caller and operation. A first start may omit RecordID (CommandID is used); subsequent transitions must retain the original record ID and exact version. The executor reads the existing authorization owner's actor epoch; callers supply no authority row. Retain this unchanged for Execute retries or Recover; changing intent cannot replay an original success or cause a new effect under the same command ID.

func (LockoutExecutionRequest) Format

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

Format redacts correlated actor, subject and transient network facts.

func (LockoutExecutionRequest) MarshalJSON

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

MarshalJSON forbids exporting trusted internal workflow input.

func (LockoutExecutionRequest) MarshalText

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

MarshalText forbids exporting trusted internal workflow input.

type LockoutExecutor

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

LockoutExecutor owns preparation, same-Work mutation, audit/lifecycle and authorized original-result recovery through the sole coordinator. It opens no private mutation transaction, never retries an unknown effect, and does not renew an original decision or recreate a snapshot from latest state. Zero is invalid; immutable instances support concurrent independent calls.

func NewLockoutExecutor

func NewLockoutExecutor(c LockoutExecutorConfig) (*LockoutExecutor, error)

NewLockoutExecutor validates and copies one bounded scope without callbacks, network activity or resource ownership transfer. Unsupported/incomplete composition returns ErrInvalidPolicy; selected schemas fail closed at runtime.

func (*LockoutExecutor) Execute

Execute performs at most one new mutation. Authorized existing history is reconciled instead of preparing a new command or refreshing its freshness. Unknown remains bound to this request and must be resolved with Recover; earlier caller deadlines win and all policy callbacks run outside Work.

func (LockoutExecutor) Format

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

Format hides caller context and retained runtime custody.

func (LockoutExecutor) MarshalJSON

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

MarshalJSON forbids exporting runtime workflow custody.

func (LockoutExecutor) MarshalText

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

MarshalText forbids exporting runtime workflow custody.

func (*LockoutExecutor) Recover

Recover authorizes historical disclosure through the configured current QueryPolicy, reconciles the original command, and reads its immutable domain version. It performs no new start/end, intent signing, provider work or retry. Missing, denied, malformed and unknown history never returns a snapshot.

type LockoutExecutorConfig

type LockoutExecutorConfig ExecutorConfig

LockoutExecutorConfig selects one verified administrative actor, tenant, target user and native start/end operation. Caller is trusted authenticated composition, not request JSON. Both separately selected admission and historical disclosure policies are required at the caller's current revision. Effect adapters must support the existing coordinator recovery contract. Pool and callback ownership remains with the caller; construction performs no IO. Repository must explicitly select LockoutMutations and its migrations.

func (LockoutExecutorConfig) Format

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

Format hides trusted caller and runtime dependency custody.

func (LockoutExecutorConfig) MarshalJSON

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

MarshalJSON forbids serialization of authenticated runtime configuration.

func (LockoutExecutorConfig) MarshalText

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

MarshalText forbids serialization of authenticated runtime configuration.

type LockoutMigrationSource

type LockoutMigrationSource struct {
	Base    CounterMigrationSource
	Version migrations.Version
}

LockoutMigrationSource appends durable restriction storage to the immutable protected-counter history. Restrictions name the same logical keyed root as retained counter aliases; neither rotation nor window reset creates a new restriction identity. Version is a permanent forward-only allocation after Base.Version. Installation creates no restriction and selects no trigger, duration or override. Production mutation commands remain separate work.

func (LockoutMigrationSource) Load

Load returns owned complete atomic history, preserving prior migration bytes. Invalid allocation rejects before construction; cancellation is propagated.

type LockoutMutationConfig

type LockoutMutationConfig struct {
	Authorization            authorization.Service
	PolicyID                 string
	PolicyRevision           uint64
	AuthorityNamespace       string
	MaximumLockoutDuration   time.Duration
	AdmissionTTL             time.Duration
	MaximumDuration          time.Duration
	SigningKeys              map[uint32][32]byte
	CurrentSigningKeyVersion uint32
}

LockoutMutationConfig enables one native transition owner. Authorization is the existing concurrency-safe, revision-fenced policy service; it runs only outside Work and must honor cancellation. AuthorityNamespace identifies the existing authorization owner's actor epochs and must uniquely identify the selected principal kinds. Role changes must atomically advance that epoch. AdmissionTTL is explicit, microsecond-exact and at most twenty seconds; MaximumDuration bounds preparation callbacks to at most five seconds. There is no inferred trigger or duration. Retain signing keys for pending commands. SigningKeys are copied nonzero HMAC-SHA256 keys, separate from bearer keys.

func (LockoutMutationConfig) Format

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

func (LockoutMutationConfig) MarshalJSON

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

func (LockoutMutationConfig) MarshalText

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

type LockoutSnapshot

type LockoutSnapshot struct {
	RecordID      string
	Operation     risk.Action
	Version       uint64
	PolicyVersion uint64
	StartedAt     time.Time
	ExpiresAt     time.Time
	EndedAt       *time.Time
}

LockoutSnapshot is the exact original committed post-mutation state, not the current restriction or a permission. End preserves StartedAt/ExpiresAt and records EndedAt separately. Returned pointers are independently owned; no digest, policy permit, counter root or raw network/session input is exposed.

type LockoutStateMigrationSource

type LockoutStateMigrationSource struct {
	Base    LockoutMigrationSource
	Version migrations.Version
}

LockoutStateMigrationSource appends attributable transition storage without rewriting any installed interval or counter history. Allocate Version permanently after Base.Version. Existing restrictions retain their original versions, intervals and keyed roots; no command, authorization, transition or audit record is fabricated for them. Native start/end execution is separate from installing this schema, and interval-only admission remains unchanged.

func (LockoutStateMigrationSource) Load

Load returns owned complete forward-only atomic history. Nil/cancelled context and invalid version allocation fail before producing history. Concurrent calls are independent; there is no IO, backfill, reset or destructive down SQL.

type LockoutTransitionMigrationSource

type LockoutTransitionMigrationSource struct {
	Base    LockoutStateMigrationSource
	Version migrations.Version
}

LockoutTransitionMigrationSource appends immutable domain-version evidence after LockoutStateMigrationSource. Version is a permanent unique forward allocation. Original intervals, history and legacy custody are untouched; no successful transition is backfilled. Historical command outcomes remain coordinator-owned. Domain versions must be retained while referenced by any unresolved or retained command; this profile does not expose pruning.

func (LockoutTransitionMigrationSource) Load

Load returns independent atomic forward-only history without IO or down SQL.

type MFACompletionCounterMigrationSource

type MFACompletionCounterMigrationSource struct {
	Schema  string
	Version migrations.Version
}

MFACompletionCounterMigrationSource adds the original child capability dimension for anonymous native TOTP completion after protected and registration verification counter histories. Allocate Version once after every selected predecessor. Existing windows, charges, aliases, snapshots and key/timing evidence remain unchanged. The atomic forward migration grants no allowance or proof authority and admits no other new capability-scoped operation.

func (MFACompletionCounterMigrationSource) Load

Load is pure, bounded and concurrent-safe, returning one owned forward migration. Invalid inputs/cancellation fail without SQL; execution requires the owned predecessor tables and constraints rather than rebuilding them.

type MFALoginSendCounterMigrationSource

type MFALoginSendCounterMigrationSource struct {
	Schema  string
	Version migrations.Version
}

MFALoginSendCounterMigrationSource adds the original browser-flow dimension after the selected protected, registration and MFA completion histories. Allocate Version permanently after those predecessors. Populated windows, aliases, charges, key history and original snapshot times remain unchanged. The forward-only atomic migration enables storage, not source authentication or allowance; native registered MFA/counter owners remain mandatory.

func (MFALoginSendCounterMigrationSource) Load

Load returns one owned forward migration without IO. Invalid schema/version, nil context and cancellation fail before SQL construction. Concurrent calls are safe; missing predecessor constraints fail execution without rebuilding tables or silently adopting another storage profile.

type MFAOTPCompletionCounterMigrationSource

type MFAOTPCompletionCounterMigrationSource struct {
	Schema  string
	Version migrations.Version
}

MFAOTPCompletionCounterMigrationSource selects original-child OTP completion after protected, verification, MFA completion/recovery and login-send counter histories. Allocate Version once after every selected predecessor. Existing windows, aliases, charges, snapshots, keys and evidence deadlines are unchanged. Storage support grants no allowance: both actual MFA and OTP owners remain mandatory, and browser-flow scope stays exclusive to OTP sending.

func (MFAOTPCompletionCounterMigrationSource) Load

Load returns one owned forward migration without IO. Missing predecessor constraints fail execution; nil context, cancellation and invalid schema or version fail before SQL construction. Concurrent calls are safe.

type MFARecoveryCounterMigrationSource

type MFARecoveryCounterMigrationSource struct {
	Schema  string
	Version migrations.Version
}

MFARecoveryCounterMigrationSource extends the existing completion-counter history with recovery-code completion. Allocate Version after that history. Existing windows, charges and their original timing remain unchanged; this migration grants neither allowance nor authentication authority.

func (MFARecoveryCounterMigrationSource) Load

Load returns one forward migration without IO. Cancellation and invalid schema/version fail before SQL construction. Concurrent calls are safe.

type MigrationSource

type MigrationSource struct {
	Schema  string
	Version migrations.Version
}

MigrationSource owns the forward-only issued-evidence install in a dedicated namespace. Version is a permanent 1..MaxInt64 allocation in the composition's single migration history; never renumber applied versions. Kernel migrations must precede this source. Existing unmanaged objects fail instead of being adopted. Zero is invalid; Load is pure and concurrent-safe. This initial history does not implement reservations, counters, CAPTCHA or erasure.

func (MigrationSource) Load

Load returns independently owned atomic installation SQL without a destructive down migration. Invalid input is redacted; context cancellation is preserved.

type PasskeySignupCounterMigrationSource

type PasskeySignupCounterMigrationSource struct {
	Schema  string
	Version migrations.Version
}

PasskeySignupCounterMigrationSource adds only the two canonical registration actions' browser-flow/device dimensions. Allocate Version after all selected histories. Installed validated expressions are preserved, including optional MFA, email and verification profiles; no window, charge or snapshot is reset. Missing or unvalidated owned checks fail atomically. This selects storage, not browser authentication, risk allowance or native registration authority.

func (PasskeySignupCounterMigrationSource) Load

Load returns one pure forward transactional migration. Invalid schema/version, nil context and cancellation fail before SQL construction. Calls are safe concurrently and own no runtime resources.

type Repository

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

Repository owns issued-evidence SQL through the sole identity coordinator. It has no transaction, connection or bearer-read API. It is immutable and safe for concurrent independent invocations; Work remains serial-use only. Zero is invalid. Initiation reservation/rebind use the sole coordinator; consuming recovery and terminal release use that coordinator as well. Protected counters, authorized native lockout transitions and native CAPTCHA issuance and consuming custody are opt-in. CAPTCHA check/finalize and proven terminal release run through the same coordinator. Phone use additionally needs exact issuer/durable-counter custody; the phone workflow still owns domain/factor authority. Counter retirement and pruning remain unsupported. Selection is not a complete consumer workflow service.

func NewRepository

func NewRepository(c Config) (*Repository, error)

NewRepository validates and copies local custody configuration without IO. The returned instance must be enlisted in the same coordinator registry used by execution and recovery; matching descriptor names do not confer authority.

func (*Repository) ApplyFeature

ApplyFeature runs only during this exact instance's active invocation. It materializes once at authoritative Work database time, preserving the original exclusive expiry, then inserts encrypted response custody and minimal scoped keyed linkage. The receipt is provisional and contains no bearer. Coordinator commit must persist the required audit, lifecycle and command result together; every error requires Abort. No private transaction or external callback runs.

func (*Repository) CheckCaptchaEvidence

func (r *Repository) CheckCaptchaEvidence(ctx context.Context, w identitypostgres.CaptchaApplyWork) error

CheckCaptchaEvidence authenticates admitted native custody and current selected policy, locks the exact reserved primary row and checks its original facts and exclusive expiry after exclusion. It grants no independent domain authority. The invocation and rows are not retained; no provider, callback or private transaction runs. Concurrent invocations use independent handles.

func (*Repository) CheckCommandCounters

CheckCommandCounters rechecks native fixed-counter custody and current allowance only during the exact coordinator domain invocation. It locks the retained original charge, validates all original snapshots and current key history, and locks each current logical window before sampling primary time. Original preparation, observation and window expiry never renew; expired or incomplete evidence requires a new command, not an allowance reset. No counter, journal, alias or key-history mutation occurs here. Success grants no domain authorization or full risk verdict; the feature owner checks its own current authority. Selected durable lockouts are read under these same locks; their original intervals survive counter-window resets and retained-key rotation. Lockout mutation and overrides remain separate implementation work. Zero/disabled/foreign Work fails redacted.

func (*Repository) CheckRiskEvidence

func (r *Repository) CheckRiskEvidence(ctx context.Context, w identitypostgres.RiskApplyWork) error

CheckRiskEvidence authenticates original phase-specific phone scope under current policy/provider custody and locks the exact reserved issued row. It requires the actual original durable counter attempt and current allowance inside the same sole coordinator transaction. Original check/issuance/expiry never renew. Missing, terminal, foreign, stale or unavailable authority denies. Native phone/factor/current-user authorization remains the feature owner's responsibility. No callback, provider, private transaction or handle retention occurs; independent invocations are concurrent-safe, each Work is serial-use.

func (*Repository) Descriptor

Descriptor identifies the native store, not current registration or authority.

func (*Repository) FeatureOperations

func (r *Repository) FeatureOperations() []identity.FeatureOperation

FeatureOperations returns owned issuance and explicitly selected lockout declarations. It does not grant caller authority or register global state.

func (*Repository) FinalizeCaptchaEvidence

func (r *Repository) FinalizeCaptchaEvidence(ctx context.Context, w identitypostgres.CaptchaFinalizeWork) error

FinalizeCaptchaEvidence repeats current-use validation and terminally CASes the exact reserved generation in the protected domain transaction. Original issuance, expiry and reservation time never change. Failure requires the coordinator to roll back all provisional effects; it is not release proof.

func (*Repository) FinalizeRiskEvidence

func (r *Repository) FinalizeRiskEvidence(ctx context.Context, w identitypostgres.RiskFinalizeWork) error

FinalizeRiskEvidence repeats the current original-row/counter checks and CASes the exact reserved command/fingerprint/generation to finalized in the protected mutation transaction, with exclusive database-time expiry. Zero affected rows requires rollback of every provisional effect, not release. It never issues, renews, retries, opens a private transaction or invokes a provider/caller callback. Unknown outcomes retain reserved custody and use existing coordinator recovery; expiry alone grants no release or reuse.

func (Repository) Format

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

Format hides runtime custody configuration and retained key material.

func (Repository) MarshalJSON

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

MarshalJSON rejects serialization of runtime custody state.

func (Repository) MarshalText

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

MarshalText rejects serialization of runtime custody state.

func (*Repository) PrepareAccountLinkCommandCounters

func (r *Repository) PrepareAccountLinkCommandCounters(command identity.Command, subject risk.Subject, primaryTime time.Time) (identity.Command, kernel.CommandCounterPlan, error)

PrepareAccountLinkCommandCounters prepares the existing protected counter policy for a canonical explicit self-user link without converting it into a generic feature command. Trusted server-resolved subject User and Session must equal the original command; only Network may supply another dimension. All other subject fields must be empty. Network validation/key derivation belongs to the existing risk policy. PrimaryTime is original primary UTC microsecond time, not a new lifetime or caller-selected observation.

This pure operation performs no IO, callbacks, authentication or reservation. Its opaque result retains the exact signed grant and original command scope; native fingerprinting, provider/policy/session checks, current allowance, atomic charge/effects and recovery remain mandatory. Zero/disabled/wrong-mode, repeated preparation and mismatched dimensions return redacted errors and no command/plan. Immutable repository configuration supports concurrent calls.

func (*Repository) PrepareCommandCounters

func (r *Repository) PrepareCommandCounters(c identity.Command, subject risk.Subject, primaryTime time.Time) (identity.Command, identitypostgres.CommandCounterPlan, error)

PrepareCommandCounters adds a closed native counter projection to an existing protected feature command. Subject is trusted server-resolved input, not an HTTP request: subject/actor/resource must equal the command's canonical binding. PrimaryTime is supplied primary UTC microsecond time; reservation rechecks it without renewal. Raw network/session values stay only in the opaque command, not persisted columns or the frozen plan. This pure method grants no allowance, authorization or commitment. The feature owner must validate its own schema including these reserved fields. Zero/disabled repository fails redacted.

func (*Repository) PrepareEmailChangeCommandCounters

func (r *Repository) PrepareEmailChangeCommandCounters(c identity.Command, subject risk.Subject, capabilityID string, primaryTime time.Time) (identity.Command, identitypostgres.CommandCounterPlan, error)

PrepareEmailChangeCommandCounters selects only the managed-v1 change-confirm profile. Signed original user/grant and trusted network must be conserved. Install EmailChangeCounterMigrationSource; no live session is inferred. This is pure preparation, not allowance, proof authentication or consumption.

func (*Repository) PrepareEvidenceUse

PrepareEvidenceUse maps an opaque core precheck and its exact trusted original scope into a consuming native phone-reset initiation command and signed plan. UseIssuer must be configured. The supplied feature spec must use the closed native phone schema and must not already contain risk.intent or risk.use.*. Other feature fields are preserved and remain the phone owner's responsibility. Raw phone, pre-auth, attempt and subject dimensions live only in the opaque in-memory command; neither the plan nor journal gains those values or a bearer. Inputs are copied, must not be concurrently mutated, and must never be logged. This pure bounded preparation samples no time and performs no callbacks/IO. It grants no current-counter, journal, reservation or domain authority; every failure returns zero outputs and redacted ErrInvalidEvidenceExecution.

func (*Repository) PrepareLockoutCommand

func (r *Repository) PrepareLockoutCommand(ctx context.Context, q LockoutCommandRequest, primaryTime time.Time) (command identity.Command, err error)

PrepareLockoutCommand checks current policy outside any transaction and seals the complete immutable request. PrimaryTime must be the original primary read instant obtained before policy evaluation; never use a request/process clock, rewrite it on retry or add network delay to it. Native apply rechecks primary expiry and current actor epoch under lock. Preparation grants no commitment. This adapter mapping is for trusted owned workflows, not application glue; retain the returned command unchanged for replay/ambiguous outcome recovery.

func (*Repository) PrepareMFACompletionCommandCounters

PrepareMFACompletionCommandCounters selects only anonymous native TOTP/OTP/recovery login completion. It binds the signed continuation subject and child plan without inventing an authenticated session or changing command user ownership. Preserve opaque code/cookie custody. The actual reservation/current checks compare this projection to sealed coordinator-owned completion scope; pure preparation alone grants no factor, proof, allowance or mutation authority.

func (*Repository) PrepareMFALoginSendCommandCounters

func (r *Repository) PrepareMFALoginSendCommandCounters(c identity.Command, subject risk.Subject, at time.Time) (identity.Command, identitypostgres.CommandCounterPlan, error)

PrepareMFALoginSendCommandCounters selects the closed anonymous OTP-send lane. The registered native MFA owner must authenticate the resolved user, original signed child, confirmed factor and consumed-primary browser before charging. Reservation and current checks compare this projection to that exact owner's source; pure preparation is not authentication or allowance. The browser dimension uses the immutable original AnonymousFlowID, never a new child or a fabricated session. Original cookie custody is retained and journal UserID remains empty. Cancellation/IO and mutation belong to execution.

func (*Repository) PreparePasskeySignupCommandCounters

func (r *Repository) PreparePasskeySignupCommandCounters(c identity.Command, subject risk.Subject, at time.Time) (identity.Command, identitypostgres.CommandCounterPlan, error)

PreparePasskeySignupCommandCounters selects only the two anonymous native passkey signup schemas. The browser target comes from the original binding, never a caller-selected counter field. Subject contains only trusted Network and Device. Canonical CredentialMutation limits, denial and reservation phase are unchanged. The native passkey owner must authenticate original browser custody and protocol facts before reservation and commit account/credential/ session effects atomically. Pure preparation grants none of that authority. Install PasskeySignupCounterMigrationSource before reserving this profile.

func (*Repository) PreparePhoneResetCompletionEvidenceUse

func (r *Repository) PreparePhoneResetCompletionEvidenceUse(command identity.Command, original risk.PhoneEvidenceRequest, use risk.EvidenceUse) (identity.Command, identitypostgres.RiskEvidencePlan, error)

PreparePhoneResetCompletionEvidenceUse adds authenticated completion-only risk scope to an exact sealed input or generated phone-reset command. The original password or verifier, canonical capability, SMS, independent TOTP and bound browser cookie retain their original owners; no partial Feature or OneTimeCode command is produced. UseIssuer must match current configuration. The precheck must consume an independently issued PhoneResetCompletion row. Raw scope stays only in encrypted command custody, never the returned plan. This bounded pure preparation performs no IO, callbacks or time observation and grants no current allowance, proof authentication or mutation authority. Failure returns zero outputs and a redacted error. Inputs must not be mutated concurrently; destroy/discard borrowed secret owners after bounded use.

func (*Repository) PrepareVerificationCommandCounters

func (r *Repository) PrepareVerificationCommandCounters(c identity.Command, subject risk.Subject, capabilityID string, primaryTime time.Time) (identity.Command, identitypostgres.CommandCounterPlan, error)

PrepareVerificationCommandCounters selects only the core's sessionless registration-link lane. The native email owner must authenticate capabilityID and subject.User from the original signed grant, preserve its exact command and callback intent, and match this ID to its capability consumption plan. Only identity.email.verification-confirm accepts this profile; no session is fabricated. Network is trusted transport input. Install the separately allocated VerificationCounterMigrationSource before reservation. This pure preparation performs no IO, grants no proof validation/allowance and returns zero on error. Existing PrepareCommandCounters retains session semantics.

func (*Repository) RebindCaptchaEvidence

func (r *Repository) RebindCaptchaEvidence(ctx context.Context, w identitypostgres.CaptchaUseReservationWork) error

RebindCaptchaEvidence transfers only the exact reserved predecessor to its positive successor under the same command/fingerprint and signed original. The coordinator transfers every declared participant atomically. Original expiry/reservation time and terminal ownership are never renewed or released. It has the same callback/transaction/lifetime constraints as first reservation.

func (*Repository) RebindCaptchaReplay

func (r *Repository) RebindCaptchaReplay(ctx context.Context, w identitypostgres.CaptchaReservationWork) error

RebindCaptchaReplay conserves the original winner and all aliases while CAS transferring exactly the predecessor generation to the coordinator's new owner. It never releases unresolved ownership, replaces signed input, extends evidence validity or grants domain/protected-use authority.

func (*Repository) RebindRiskEvidence

func (r *Repository) RebindRiskEvidence(ctx context.Context, w identitypostgres.RiskReservationWork) error

RebindRiskEvidence transfers only the same command/fingerprint's exact prior generation in the coordinator's atomic owner takeover. Original reservation time, issuance custody and expiry remain unchanged. Terminal, expired, missing or partial ownership fails closed; lease expiry never releases evidence.

func (*Repository) RecoverParticipant

RecoverParticipant supplies only this native participant's historical effect evidence under the coordinator's locked recovery invocation. An exact row is positive evidence, never a reconstructed successful receipt. Absence is negative only here: issuance is same-Work atomic and this profile never prunes rows. Corrupt or foreign linkage is unknown. Expiry is not rollback proof. For phone consumption, only exact reserved historical custody supplies noncommit evidence for this participant; every other participant must supply its own evidence before the coordinator grants terminal release authority.

func (*Repository) ReleaseCaptchaEvidence

func (r *Repository) ReleaseCaptchaEvidence(ctx context.Context, w identitypostgres.CaptchaReleaseWork) error

ReleaseCaptchaEvidence records terminal release only through the exact coordinator-owned rollback or unanimous primary noncommit invocation. Current verifier removal and historical expiry do not obstruct cleanup and never grant proof or reusability. Exact predecessor custody is CASed to the supplied generation without renewing the original interval. Handles are serial-use, bounded and not retained; no private transaction or callbacks run.

func (*Repository) ReleaseRiskEvidence

func (r *Repository) ReleaseRiskEvidence(ctx context.Context, w identitypostgres.RiskReleaseWork) error

ReleaseRiskEvidence terminally releases exact reserved initiation custody only through the sole coordinator's unanimous-noncommit release invocation. It preserves original issuance, expiry and reservation time, recording only the recovery generation. No expiry check grants rollback proof or reusability. Foreign, missing, terminal or mismatched custody fails closed. No callbacks, bearer reads, new evidence or private transaction are permitted.

func (*Repository) ReserveCaptchaEvidence

func (r *Repository) ReserveCaptchaEvidence(ctx context.Context, w identitypostgres.CaptchaUseReservationWork) error

ReserveCaptchaEvidence locks an already committed original CAPTCHA row and binds its one consuming command/fingerprint/generation in the coordinator's existing reservation transaction. Complete signed native input and selected current configuration are authenticated; primary expiry is checked after locking and again at CAS. No provider, caller callback or private transaction runs. Failure requires coordinator rollback. The serial-use handle and rows are not retained. This reserves ownership only, not protected-use permission. Install CaptchaUseMigrationSource before selecting consuming plans.

func (*Repository) ReserveCaptchaReplay

func (r *Repository) ReserveCaptchaReplay(ctx context.Context, w identitypostgres.CaptchaReservationWork) error

ReserveCaptchaReplay claims every retained provider-token alias under one original command, in the coordinator's reservation transaction. It authenticates exact selected configuration before SQL, reveals no reference and runs no provider, clock callback or private transaction. Alias ownership survives domain rollback/expiry; a different command always conflicts. Errors require coordinator rollback. Handles are serial-use and not retained.

func (*Repository) ReserveCommandCounters

ReserveCommandCounters charges exactly one protected attempt inside the sole coordinator reservation transaction. Fixed windows start at primary time and reset at their exclusive expiry; values saturate rather than wrap. Every retained digest alias names the same window. New-key registration preserves all known versions and key identities; removing/changing known keys fails closed. Denied is a provisional disposition, not an error, so its charge, snapshot, failure audit and aborted receipt can commit atomically. Takeover transfers exact predecessor linkage and returns the original decision without recounting, refunding or refreshing observation time. It performs no provider call, private transaction or domain mutation. Any error requires rollback; SQL success alone never establishes CounterCommitted or domain commitment.

func (*Repository) ReserveRiskEvidence

func (r *Repository) ReserveRiskEvidence(ctx context.Context, w identitypostgres.RiskReservationWork) error

ReserveRiskEvidence authenticates the frozen phase-specific use and locks its existing primary issued row through the sole coordinator's reservation Work. Exactly one command obtains ownership. No bearer, response or domain authority is returned. Missing, expired, terminal or mismatched evidence yields the same redacted conflict. It never inserts evidence, renews expiry, runs callbacks or opens a private transaction. The reservation migration must already be applied.

func (*Repository) ValidateCaptchaUseCommand

func (r *Repository) ValidateCaptchaUseCommand(command identity.Command, plan identitypostgres.CaptchaEvidencePlan) error

ValidateCaptchaUseCommand authenticates the complete closed consuming custody and exact scalar plan under the selected immutable current verifier profiles. It runs no clocks, callbacks or SQL and grants no journal/freshness/permission authority. Reservation and domain-time expiry/current-authority checks remain required. A retained signature from an unselected profile is insufficient.

func (*Repository) ValidateCommandCounters

func (r *Repository) ValidateCommandCounters(c identity.Command, p identitypostgres.CommandCounterPlan) error

ValidateCommandCounters reconstructs exact native scope and its original retained-key projection without IO. Historical key subsets remain decodable during rotation, but only current complete history admits a new charge.

func (*Repository) ValidateCounterOnlyOperation

func (r *Repository) ValidateCounterOnlyOperation(operation risk.Action) error

ValidateCounterOnlyOperation checks that this repository's actual immutable counter policy requires only the velocity signal for the selected protected operation. A workflow without provider-evidence admission must call this at composition so configured status/CAPTCHA facts cannot be silently omitted. It grants no allowance, authentication or mutation permission and performs no IO. Nil, disabled, unlisted, non-protected or richer configurations return risk.ErrInvalidPolicy. Concurrent calls are safe under the repository's immutable configuration contract; the supplied operation is not retained.

func (*Repository) ValidateFeatureCommand

func (r *Repository) ValidateFeatureCommand(c identity.Command, p identitypostgres.CommandPlan) error

ValidateFeatureCommand authenticates the complete signed core projection and checks exact protected audit/lifecycle declarations before reservation. It is pure, bounded and does not authorize the caller or establish commitment.

func (*Repository) ValidateRiskEvidenceCommand

func (r *Repository) ValidateRiskEvidenceCommand(command identity.Command, plan identitypostgres.RiskEvidencePlan) error

ValidateRiskEvidenceCommand authenticates the complete native original intent and signed consuming plan under configured current policy/provider versions. Initiation and sealed conjunctive completion are supported. Non-risk fields are checked separately by the phone owner, including its exact domain target. Validation uses the original signed check instant rounded up to microseconds; it is not admission at current time. It performs no IO, clock or callbacks and cannot replace current authoritative row/counter/expiry checks or finalization. Zero, disabled, malformed or mismatched input returns one redacted error. Validation alone grants no domain execution or current-counter authority.

type ReservationMigrationSource

type ReservationMigrationSource struct {
	Base    IssuanceIDMigrationSource
	Version migrations.Version
}

ReservationMigrationSource appends one-use journal ownership to the complete issuance history. Allocate Version permanently after Base.Version in the composition's single history. Existing rows retain their original identity, expiry and encrypted response; no owner is invented. The schema permits the six journal states but does not authorize their transitions. Only the native participant inside the sole coordinator may mutate them. Load is pure and concurrent-safe; zero is invalid. No destructive down migration is provided.

func (ReservationMigrationSource) Load

Load returns independently owned complete forward history without rewriting installed SQL. Invalid allocation is redacted and cancellation is preserved.

type VelocityActivationMigrationSource

type VelocityActivationMigrationSource struct {
	Base    VelocityPublicationMigrationSource
	Version migrations.Version
}

VelocityActivationMigrationSource adds actual activation time separately from the immutable covered snapshot watermark in the existing epoch owner. Legacy healthy rows lack authenticated native activation provenance: they become unavailable, retaining all windows, journal facts and lockouts. No replaying row or confirmation is promoted. Allocate Version after Base.Version.

func (VelocityActivationMigrationSource) Load

Load appends independently owned forward-only SQL without IO or rewriting installed history. Invalid allocation/context returns no migration history.

type VelocityAppliedMigrationSource

type VelocityAppliedMigrationSource struct {
	Base    VelocityReplayMigrationSource
	Version migrations.Version
}

VelocityAppliedMigrationSource adds generation-bound acknowledged recovery progress to the existing epoch owner. Installation grants no applied progress or healthy state, and preserves every installed migration and journal fact.

func (VelocityAppliedMigrationSource) Load

Load returns independent forward-only history without IO. Version must be allocated after Base.Version. Invalid input and cancellation return no SQL.

type VelocityAttempt

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

VelocityAttempt is a private journal receipt for one confirmed intent commit. It is not dispatch, allowance, retry, epoch-health or counter-commit authority. Unknown commits return no receipt. It cannot be exported or caller-constructed.

func (VelocityAttempt) Format

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

func (VelocityAttempt) MarshalJSON

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

func (VelocityAttempt) MarshalText

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

type VelocityCoverageMigrationSource

type VelocityCoverageMigrationSource struct {
	Base    VelocityAppliedMigrationSource
	Version migrations.Version
}

VelocityCoverageMigrationSource adds primary journal lifetime metadata to the existing epoch owner. Existing epochs remain unknown; new epochs start at insertion time, never one window in the past. No health is installed.

func (VelocityCoverageMigrationSource) Load

Load appends independent forward-only history. Allocate Version permanently after Base.Version; cancellation and invalid input return no SQL.

type VelocityHealthy

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

VelocityHealthy retains exact-instance custody of one acknowledged primary activation, not a cached health assertion or permission for external effects. CheckHealthy must recheck current primary state before use; the concrete native owner must separately verify its exact marker and continuity at every effect boundary. Original expiry is never renewed. Zero is invalid; copies are immutable/concurrent-safe, redacted and nonserializable.

func (VelocityHealthy) Format

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

func (VelocityHealthy) MarshalJSON

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

func (VelocityHealthy) MarshalText

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

type VelocityIntegrityMigrationSource

type VelocityIntegrityMigrationSource struct {
	Base    VelocityIntentMigrationSource
	Version migrations.Version
}

VelocityIntegrityMigrationSource adds full-record replay authentication after Base. Installed history is unchanged. Existing records remain unsealed: SQL cannot authenticate their original facts and must never invent that proof. They remain available for investigation, but cannot grant native readback or autonomous replay until an attributable recovery proves their original facts.

func (VelocityIntegrityMigrationSource) Load

Load returns independently owned forward-only history without IO. Invalid allocation is redacted; base context/schema validation remains unchanged.

type VelocityIntentMigrationSource

type VelocityIntentMigrationSource struct {
	Base    VelocityMigrationSource
	Version migrations.Version
}

VelocityIntentMigrationSource separates immutable attempt targets from post-mutation snapshots, so pending/unknown intent never fabricates counters. Version must permanently follow Base.Version. Existing history and snapshots are retained. Load is pure/concurrent-safe; installation grants no authority.

func (VelocityIntentMigrationSource) Load

Load returns independently owned forward-only atomic history. Invalid input is redacted and base validation preserves cancellation and nil-context errors.

type VelocityJournal

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

VelocityJournal owns durable ephemeral intent, not Valkey mutation, lockouts, healthy epochs or protected identity transactions. It starts no goroutines and never closes the caller's pool. Immutable configuration permits concurrent calls; zero is invalid. Completion retains explicit declarations; external reconciliation and fenced replay remain separate authorities.

func NewVelocityJournal

func NewVelocityJournal(c VelocityJournalConfig) (VelocityJournal, error)

NewVelocityJournal validates copied local custody without pool access. The schema must include VelocityReplayMigrationSource. No store is enabled by successful construction; mismatches fail with redacted ErrInvalidPolicy.

func (VelocityJournal) Format

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

func (VelocityJournal) MarshalJSON

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

func (VelocityJournal) MarshalText

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

func (VelocityJournal) ReadResult

ReadResult reconstructs an exact authenticated historical terminal result from primary authority. It preserves original timestamps and classification, not current positive validity; the core consumes freshness separately. Pending/missing/corrupt/unsealed history is unavailable. Explicit unknown remains unknown, never noncommit or retry permission. The transaction is bounded, read-only and repeatable; no callbacks, effects or epoch mutations occur.

func (VelocityJournal) RecordAttempt

RecordAttempt durably inserts one authenticated pending attempt and all exact target aliases in a short transaction before external work. It writes no snapshot or epoch and never invokes another store. Raw attempt/subject facts are not persisted. PreparedAt is rounded upward to PostgreSQL microseconds, and future preparation or sub-microsecond windows deny before insertion. Existing matching pending attempts remain unavailable; changed fingerprints fail with ErrInvalidCounterCommand. Neither expiry nor replay permits another dispatch. Every database/commit failure returns a redacted UnavailableError without a receipt, including commit ambiguity; callers must not retry effects. A shared scoped transaction lock precedes time/sequence allocation and lasts through commit, so recovery acquisition cannot pass an unresolved insertion. Journal recording remains evidence only, including while an epoch is replaying. A live prepared closure denies new evidence until renewal or expiry.

func (VelocityJournal) RecordResult

func (j VelocityJournal) RecordResult(ctx context.Context, a VelocityAttempt, outcome risk.CounterOutcome, snapshot []risk.Counter) error

RecordResult atomically retains a configured ephemeral adapter's explicit declaration and original snapshots. The exact confirmed attempt receipt is required; journal durability does not establish truth of an external result. Pending may become committed, not-committed or unknown. Every terminal state is immutable, including unknown; identical declarations are idempotent. Snapshots must use exact full windows and microsecond-representable times; values/freshness are never rounded or renewed. No Valkey dispatch, retry, health publication or recovery proof is granted. Database/commit ambiguity returns UnavailableError and must not be interpreted as external noncommit. Its shared scope lock precedes attempt-row locks and remains until transaction resolution. Recovery acquisition drains overlapping declarations but does not discard later evidence or turn an explicit declaration into external truth. A live prepared closure denies a new declaration but preserves identical terminal replay. Renewal or expiry reopens evidence admission, not health.

type VelocityJournalConfig

type VelocityJournalConfig struct {
	Pool              *database.Pool
	Schema, Namespace string
	JournalKey        []byte
	Policy            risk.Policy
	Keys              []risk.CounterDigestKey
	Timeout           time.Duration
}

VelocityJournalConfig selects a caller-owned primary pool and migrated risk schema with VelocityReplayMigrationSource. Namespace identifies a stable deployment/projection, not a request. JournalKey is a separately retained 32..128-byte HMAC key; replacing it would lose replay identity and is not supported. Policy and complete newest-first Keys must be the exact values used by the ephemeral coordinator. Timeout is positive and at most one minute. Construction copies keys without IO.

func (VelocityJournalConfig) Format

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

func (VelocityJournalConfig) MarshalJSON

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

func (VelocityJournalConfig) MarshalText

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

type VelocityMigrationSource

type VelocityMigrationSource struct {
	Base    CounterMigrationSource
	Version migrations.Version
}

VelocityMigrationSource appends the PostgreSQL recovery journal and boot-epoch storage for ephemeral Valkey counters. It does not grant counter mutation, replay, pruning, or healthy-publication authority. Allocate Version permanently after Base.Version. Load is pure/concurrent-safe and preserves installed SQL. No epoch or healthy state is manufactured by installation.

func (VelocityMigrationSource) Load

Load returns owned forward-only atomic history. Invalid allocations fail redacted; base validation preserves nil-context and cancellation semantics.

type VelocityPublicationMigrationSource

type VelocityPublicationMigrationSource struct {
	Base    VelocityCoverageMigrationSource
	Version migrations.Version
}

VelocityPublicationMigrationSource records native cut confirmation in the existing epoch authority. Existing rows remain unconfirmed; installation grants neither health nor admission. Allocate Version after Base.Version.

func (VelocityPublicationMigrationSource) Load

Load appends independent forward-only history without IO. Invalid allocations, nil context and cancellation return no SQL and preserve base history.

type VelocityRecovery

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

VelocityRecovery owns PostgreSQL recovery leases, not counter mutation or replay/publication truth. Immutable local configuration is concurrent-safe; zero is invalid. It owns no goroutine and never closes the caller's pool. Acquire/Renew use primary database time after locks. Unknown acknowledgements expose no receipt; takeover requires authoritative expiry, never local time.

func NewVelocityRecovery

func NewVelocityRecovery(c VelocityRecoveryConfig) (VelocityRecovery, error)

NewVelocityRecovery validates configuration without IO. Journal must already use VelocityReplayMigrationSource. Unsupported windows and lease bounds fail redacted with ErrInvalidPolicy; construction grants no external authority.

func (VelocityRecovery) Acquire

func (r VelocityRecovery) Acquire(ctx context.Context, tenant string, epoch [16]byte) (VelocityRecoveryLease, error)

Acquire obtains one scoped replaying lease for a trusted projection boot epoch. The epoch must be its nonzero random 128-bit boot marker, not request input. Only authoritative expiry permits replacing a live replay owner. Same-epoch takeover advances generation; a new epoch atomically retires the old one. Retired epochs cannot resurrect, including when their marker returns. Initial cursor has zero covered progress, and no path publishes healthy state. Concurrent losers, exhausted generations, corrupt state and commit ambiguity return UnavailableError with no receipt. No journal outcome is modified. Acquisition drains all overlapping journal writer transactions. Later writes remain evidence and must be accounted for by the still-unimplemented replay owner; successful acquisition is not a complete scan or stable final cursor.

func (VelocityRecovery) Activate

Activate atomically records primary eligibility for the exact covered, durably confirmed and native-confirmed cut, then reopens journal writers. Install VelocityActivationMigrationSource. It drains writers and independently authenticates original lease, applied progress, complete history, coverage and persisted confirmation under primary locks. No SQL lock spans native IO. The native acknowledgement is historical, not a substitute for those checks. Healthy retries reconcile the original activation without replay callbacks, writes or refreshed times; expired/superseded/invalidated state denies. Ambiguous commits return no receipt. Retry the same custody to reconcile. Cancellation is preserved; authority/IO failures are redacted unavailable. Success records primary state only: public traffic additionally needs current native continuity, exact-marker enforcement and owned intent/result execution.

func (VelocityRecovery) CheckClosure

func (r VelocityRecovery) CheckClosure(ctx context.Context, closure VelocityRecoveryClosure) error

CheckClosure verifies the exact retained cut and original lease against primary time. It is a point-in-time check, not native effect permission. Superseded, expired, foreign, altered or ambiguous custody fails closed.

func (VelocityRecovery) CheckCoveredClosure

func (r VelocityRecovery) CheckCoveredClosure(ctx context.Context, closure VelocityRecoveryClosure) error

CheckCoveredClosure checks the retained coverage and exact closed lease.

func (VelocityRecovery) CheckHealthy

func (r VelocityRecovery) CheckHealthy(ctx context.Context, healthy VelocityHealthy) error

CheckHealthy rechecks exact generation/owner, original cut, sealed applied progress, recorded confirmation/activation and exclusive expiry by primary time. It never invokes replaying-only callbacks, renews metadata, inspects native state or treats subsequent journal history as restored replay progress. Unavailable primary/expired or altered state denies; no stale fallback exists.

func (VelocityRecovery) CheckLease

func (r VelocityRecovery) CheckLease(ctx context.Context, lease VelocityRecoveryLease) error

CheckLease compares exact current generation, owner, epoch and original lease expiry against primary database time. Success is a point-in-time ownership check only, not a durable effect permit or permission to publish health later. Expired, superseded, retired, foreign or ambiguous state is unavailable.

func (VelocityRecovery) CheckPublication

CheckPublication rechecks the same recorded confirmation and original live custody without writing, renewing time or reopening journal admission. A missing, foreign, altered, expired or superseded confirmation denies. This is primary confirmation only, not evidence that the native projection is intact.

func (VelocityRecovery) ConfirmPublication

ConfirmPublication durably records the configured native owner's exact publication in the existing primary epoch. Install VelocityPublicationMigrationSource. Original lease, cut, coverage and expiry remain unchanged; matching retries retain the original confirmation time. Unknown commit acknowledgement returns unavailable, never success or native resend permission. Retry the same custody to reconcile primary truth. This keeps the replay writer fence closed and does not publish healthy state, confirm present native continuity or authorize traffic. SQL locks never span native IO. Cancellation is preserved; other failures are redacted.

func (VelocityRecovery) Format

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

func (VelocityRecovery) InvalidateHealthy

func (r VelocityRecovery) InvalidateHealthy(ctx context.Context, healthy VelocityHealthy) error

InvalidateHealthy makes the exact activation unavailable without clearing counters, history, lockouts or original lease expiry. Retained metadata permits idempotent reconciliation of an ambiguous invalidation. Only the unchanged original generation/owner may invalidate, even after expiry; superseded custody cannot affect a successor. New recovery still requires authoritative lease expiry. This denial operation performs no native IO and cannot resurrect health.

func (VelocityRecovery) MarshalJSON

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

func (VelocityRecovery) MarshalText

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

func (VelocityRecovery) OwnedClosure

OwnedClosure exports only acknowledged covered primary custody into the configured graph. The exact original PostgreSQL lease and full owned lease binding must match. The cut identity is a stable domain-separated keyed digest of that lease and original cut, never a newly sampled time or application ID. The retained checker reauthenticates the original covered cut on every use; renewal, expiry, coverage loss or applied-state corruption deny. Transactions end before native IO. Export performs no preparation, renewal, native effect or health mutation. Invalid custody returns InvalidInputError; failed primary checks return no custody and their redacted error, preserving cancellation.

func (VelocityRecovery) OwnedConfirmation

OwnedConfirmation exports only an already recorded primary confirmation into the configured recovery graph. It does not call ConfirmPublication or write any record. The exact original lease, covered cut and native publication must remain current; a retained checker reauthenticates the recorded confirmation on every native use. Renewal, expiry, takeover or corrupt primary state denies. One journal-timeout budget bounds the entire export, including nested checks. Transactions end before native IO. Export neither renews timestamps nor proves native continuity, changes health or grants traffic admission. Invalid owner custody returns InvalidInputError; authority failures return redacted UnavailableError, preserving cancellation and deadlines. Failure returns zero.

func (VelocityRecovery) OwnedEligibility

OwnedEligibility exports acknowledged primary activation into the configured custody graph using this adapter's concrete CheckHealthy on every use. It accepts no caller-supplied checker, time, generation or health assertion. The original lease and native-confirmed cut must match the activated receipt. One journal timeout bounds the export; retained checks independently bound later reads without refreshing original expiry, cut or activation time. Export performs no native IO or writes, and all primary transactions end before native work. Native continuity, exact-marker enforcement and journaled intent/result execution remain separate requirements. Invalid custody returns InvalidInputError; primary failures return redacted UnavailableError, with cancellation/deadlines preserved. Failure exposes no eligibility.

func (VelocityRecovery) OwnedHistory

OwnedHistory rereads the original authenticated record and change position under the exact live lease. Only immutable records returned by this recovery owner are eligible; structural projections cannot become native authority. The primary transaction is closed before any native effect can begin. Pending/unknown are retained facts, never noncommit or permission to retry.

func (VelocityRecovery) OwnedJournal

func (r VelocityRecovery) OwnedJournal(ctx context.Context, healthy VelocityHealthy) (velocity.Journal, error)

OwnedJournal binds this recovery owner's concrete journal to one original activated primary receipt. The opaque output is passed to the owned native adapter factory; it exposes no effect methods or caller-supplied callbacks. Construction and every later admission recheck current primary eligibility. Tenant, policy and complete key custody are checked before journal IO. An acknowledged intent retains its exact receipt through terminal recording; retries read authenticated original history and never authorize redispatch. All primary transactions finish before native work. Configuration is immutable and concurrent-safe; the caller retains pool ownership. Invalid custody returns InvalidInputError; primary failures are redacted, and cancellation is preserved. This connection neither publishes native health nor renews original expiry. It retains the original native-confirmed activation chain internally, with eligibility issued from this same primary owner. Callers cannot substitute a separately selected chain or journal. One outer journal timeout bounds export.

func (VelocityRecovery) OwnedLease

OwnedLease supplies cross-adapter custody after checking the exact acknowledged primary lease. Only configured issuance can mint this custody; reading requires its separately retained verifier. Construction grants neither dispatch nor health; native effects still require their own fence.

func (VelocityRecovery) PrepareClosure

PrepareClosure drains overlapping writers and durably closes new journal admission for the exact live lease, using the existing epoch's replay cut. Every retained change must have attributable current-generation applied progress; pending, unknown and unpositioned history deny. Matching retries retain the original cut. Renewal reopens admission and invalidates the cut; expiry also ends its writer fence. No SQL lock spans external IO. This proves a stable journal cut only, not historical coverage or two-store health. Ambiguous commit returns no custody; retry reads the same primary cut.

func (VelocityRecovery) PrepareCoveredClosure

func (r VelocityRecovery) PrepareCoveredClosure(ctx context.Context, lease VelocityRecoveryLease) (VelocityRecoveryClosure, error)

PrepareCoveredClosure requires a complete maximum-window journal lifetime in addition to the applied stable cut. Install VelocityCoverageMigrationSource. Missing historical provenance starts at current primary time and returns unavailable; callers cannot backdate it. Initial adoption needs a full-window warmup. Ordinary renewal/takeover/boot preserves continuity. All native effects must use this journal before dispatch; mixed writers and incomplete restores are unsupported. This remains primary custody, not native publication/health.

func (VelocityRecovery) ReadPage

ReadPage drains overlapping native writers and reads changes AFTER the opaque cursor under the exact live primary lease. Batches are 1..1000 (reference100). It reads all retained history, including expired original snapshots: storage time cannot exclude unknown/pending work or refresh original counter windows. Each insertion/first declaration receives a new authenticated change position; identical terminal replay does not. An empty page is never stable closure. Pre-positioned authenticated history is initialized in bounded native batches, without changing original facts/times. Unsealed/corrupt history fails closed. Scoped locks remain inside Timeout, never span callbacks or external effects. A failed/cancelled/expired/ambiguous transaction returns no records or cursor.

func (VelocityRecovery) RecordApplied

RecordApplied durably acknowledges one original terminal recovery effect in journal change order. The native acknowledgement must belong to the exact live owned lease. Duplicate acknowledged positions are idempotent; gaps, unresolved or unauthenticated history, stale ownership and commit ambiguity fail closed. Applied progress never publishes health or authorizes a debit. Install VelocityAppliedMigrationSource before calling this method. All SQL locks are scoped to bounded primary work and never span native IO.

func (VelocityRecovery) Renew

Renew extends only the exact live lease under primary locks and returns its superseding receipt after acknowledged commit. Concurrent renewal has one winner. Expired leases cannot renew or use local time to regain ownership. No cursor, history, generation, external result or epoch health is changed. A prepared closure is invalidated and journal evidence admission reopens.

func (VelocityRecovery) Restart

Restart abandons projection progress under the exact live replay lease. It returns a successor generation with a new owner and the original expiry; it neither extends custody nor grants healthy/native effect authority. The original history origin and journal lifetime remain unchanged. Applied progress, closure and publication are invalidated atomically. The applied and publication migrations must be installed; earlier schemas fail closed. A matching retry of the original receipt reconciles the same live successor without resetting its progress. Renewal, expiry or later generations deny that retry. Unknown commit acknowledgement returns no receipt; retrying the original receipt performs no external effect and reconciles on the primary.

func (VelocityRecovery) ResumeApplied

ResumeApplied reads authenticated durable applied progress under the exact live primary lease. Renewal preserves progress; takeover starts at zero. The returned cursor skips only acknowledged original terminal history, not merely scanned history. It grants neither health nor native effect authority. Missing or corrupt current-generation history and ambiguous commit deny a cursor. Install VelocityAppliedMigrationSource before calling this method.

type VelocityRecoveryClosure

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

VelocityRecoveryClosure is opaque custody of a stable primary journal cut. It is not native publication, temporal coverage or healthy admission authority.

func (VelocityRecoveryClosure) Format

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

func (VelocityRecoveryClosure) MarshalJSON

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

func (VelocityRecoveryClosure) MarshalText

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

type VelocityRecoveryConfig

type VelocityRecoveryConfig struct {
	Journal                      VelocityJournal
	MaximumWindow, LeaseDuration time.Duration
	// JournalIssuer and NativeVerifier opt into owned cross-adapter recovery.
	// Both must belong to one private composition graph. Omit both to preserve
	// the lease/page-only API; partial or crossed ownership is rejected.
	JournalIssuer  risk.VelocityJournalIssuer
	NativeVerifier risk.VelocityNativeVerifier
}

VelocityRecoveryConfig selects a confirmed journal and explicit lease bound. The supported reference recovery interval is exactly one hour. LeaseDuration is microsecond-representable, positive and at most one minute. There is no healthy default, operator bypass, effect callback or private counter store.

func (VelocityRecoveryConfig) Format

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

func (VelocityRecoveryConfig) MarshalJSON

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

func (VelocityRecoveryConfig) MarshalText

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

type VelocityRecoveryLease

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

VelocityRecoveryLease is exact-instance custody of one acknowledged lease. It is not allowance, replay completeness, dispatch or publication authority. Renewal supersedes the prior receipt; takeover fences its generation. It is not constructible or serializable, and carries no exportable owner secret.

func (VelocityRecoveryLease) Format

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

func (VelocityRecoveryLease) MarshalJSON

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

func (VelocityRecoveryLease) MarshalText

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

type VelocityReplayCursor

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

VelocityReplayCursor is exact recovery-instance/scope/epoch/generation custody of a change position. Zero starts the retained history. Renewal within the same generation accepts the cursor with the NEW lease; old leases still deny. Takeover or another recovery instance cannot reuse it. It proves no effects.

func (VelocityReplayCursor) Format

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

func (VelocityReplayCursor) MarshalJSON

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

func (VelocityReplayCursor) MarshalText

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

type VelocityReplayMigrationSource

type VelocityReplayMigrationSource struct {
	Base    VelocityIntegrityMigrationSource
	Version migrations.Version
}

VelocityReplayMigrationSource adds native change ordering after integrity history. Installation never signs existing rows or grants replay progress. Valid original seals are required for bounded native initialization at read.

func (VelocityReplayMigrationSource) Load

Load returns independent forward-only history without IO. Installed SQL is unchanged; invalid allocations, nil context and cancellation fail redacted.

type VelocityReplayOutcome

type VelocityReplayOutcome uint8

VelocityReplayOutcome preserves journal classification, not external truth. Pending and Unknown never mean noncommit or retry permission. Zero is invalid.

const (
	VelocityReplayPending VelocityReplayOutcome = iota + 1
	VelocityReplayCommitted
	VelocityReplayNotCommitted
	VelocityReplayUnknown
)

type VelocityReplayPage

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

VelocityReplayPage contains at most the requested batch. Empty is only an observation: later insertions/declarations remain discoverable with Next. No method publishes health, advances applied progress or dispatches effects.

func (VelocityReplayPage) Format

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

func (VelocityReplayPage) MarshalJSON

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

func (VelocityReplayPage) MarshalText

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

func (VelocityReplayPage) Next

Next returns opaque continuation custody; zero page has no usable successor.

func (VelocityReplayPage) Records

Records returns an independent slice of immutable records. Zero returns nil.

type VelocityReplayProjection

type VelocityReplayProjection struct {
	ID                       string
	Tenant                   string
	Namespace, AttemptDigest [32]byte
	Fingerprint              string
	Operation                risk.Action
	Phase                    risk.Phase
	PolicyVersion            uint64
	PreparedAt, RecordedAt   time.Time
	Window                   time.Duration
	Limit                    uint64
	Outcome                  VelocityReplayOutcome
	Targets                  []risk.CounterTarget
	Snapshot                 []risk.Counter
}

VelocityReplayProjection is a copied owned-adapter view, never HTTP data or CounterCommand authority. ID is a stable keyed opaque logical-record identity; it is separate from AttemptDigest, the original keyed attempt lookup identity. Tenant, Namespace, AttemptDigest and Fingerprint retain authenticated stored binding for owned recovery composition, never raw attempt or subject facts. They grant no dispatch, retry or healthy-epoch permission. Targets retain all original ordered aliases; Snapshot retains original values and windows.

func (VelocityReplayProjection) Format

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

func (VelocityReplayProjection) MarshalJSON

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

func (VelocityReplayProjection) MarshalText

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

type VelocityReplayRecord

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

VelocityReplayRecord is immutable authenticated history from one acknowledged page. It cannot be constructed or serialized, and is not effect permission.

func (VelocityReplayRecord) Format

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

func (VelocityReplayRecord) MarshalJSON

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

func (VelocityReplayRecord) MarshalText

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

func (VelocityReplayRecord) Projection

Projection returns independent target/key/snapshot slices; zero is invalid.

type VerificationCounterMigrationSource

type VerificationCounterMigrationSource struct {
	Schema  string
	Version migrations.Version
}

VerificationCounterMigrationSource adds the distinct original-grant counter dimension to already installed protected counter history. Permanently allocate Version after every selected migration. Original migration bytes, populated windows, snapshots, aliases, charges and their times remain unchanged. This forward-only atomic migration neither resets allowance nor grants proof or transaction authority. Load is pure, bounded and concurrent-safe.

func (VerificationCounterMigrationSource) Load

Load returns one owned forward migration; zero/invalid configuration denies, cancellation is preserved and missing/foreign installed constraints fail execution rather than silently adopting or rebuilding existing storage.

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL