FireMUD Delivery Status

PR data refreshed

PR #3134 review history

Account source-currentness storage and exact writer fencing

Unit 1A · identity, Account and public JOIN

Review rounds

Three-number pills mean: found (raw) / accepted here (useful) / routed

Hosted CodeRabbit3 completed
14/13/05/5/04/4/0
CLI CodeRabbit6 completed
8/6/04/4/03/2/06/5/04/3/0

Recorded review history

Reviews and findings

  1. Hosted Review 1 CompletedRuntime 13m 30s
    Found: 14 Accepted: 5/6/2 Routed: 0
    1. Allow Account-local fences to differ from Account-scope generations.Major

      AccountAuthorityGenerationRepository.advanceInternal advances the shared Account issuance fence for both Account and membership scopes, but it advances only the selected scope's generation. A membership advance can therefore produce Account generation/source 2/2 with fence 4/3. The password-reset test constructs and accepts exactly this state.

      requireRetainedEvent passes those receipt fence values to RetainedEventEvidence, which then throws because of the equality checks. Remove only those checks.

      -          || issuanceFence != accountAuthorityGeneration
      -          || issuanceFenceSourceVersion != sourceVersion
                 || accountSecurityCutoff == null
      
      • Accepted Accepted independent positive issuance fence/source coordinates rather than artificial Account generation equality; retain exact receipt and cutoff binding. Implemented7a with unit divergent4/3 vs2/2 proof; genuine membership-fence production closure is not claimed.
    2. Handle non-ACTIVE fresh Accounts before enrolling platform birth sources.Major

      AccountRepository.save accepts every AccountLifecycleState, but fresh source initialization rejects any state other than active. The transaction then rolls back. AccountRepositoryIntegrationTest creates fresh Accounts with every enum value, so its non-ACTIVE cases fail.

      If non-ACTIVE fresh Accounts are unsupported, reject them before the insert with a clear error. If they are supported, skip only platform-restriction birth enrollment for those rows while retaining Account authority baseline initialization. Keep the V81 guard for any birth row.

      • Accepted Accepted clear non-ACTIVE fresh insertion rejection before mutation. Do not skip restriction birth guards or invent authority; retained non-ACTIVE ordinary update proof remains.
    3. Update the AA-1.3 capability row to match the new reset prose.Minor

      Line 35 states that password-reset token consumption is now implemented atomically. The AA-1.3 row at Line 51 still says "Recovery token consumption and reset-driven revocation remain incomplete." The same row also omits the new production anchors and the focused proof anchor:

      • Production anchors to add: AccountPasswordResetOperationRepository.java, AccountPasswordResetDraftSourceChangeRepository.java, AccountAuthoritySourceEventReadback.java, V77__account_password_reset_operation_receipts.sql, V89__account_password_reset_pending_draft_source_changes.sql.
      • Proof anchor to add: PasswordResetAuthorityProducerPostgresIntegrationTest.java.

      Update the gap text so it says token consumption is implemented and only reset-driven revocation and PostgreSQL execution proof remain pending. Keep the Verification value unchanged, because the PostgreSQL cases were skipped.

      As per coding guidelines: "Keep its status, implementation record, validation, gaps, decisions, and service-map sections aligned when a domain boundary changes" and "implemented and partial rows name concrete production anchors."

      • Accepted Accepted tracker anchors/gap correction, shared with CLI#4. Keep partial status and passing physical proof, revocation and remaining recovery gaps explicit.
    4. Describe the pending-intent path as a retryable denial, not a wait.Minor

      Both documents say the reset "waits" for the owner-fence outcome. AccountServiceImpl.completePasswordReset does not wait. It commits the WAITING intent, throws SourceEvidenceUnavailableException (retryable AUTH_UNAVAILABLE), and depends on a same-token retry to settle.

      • design/architecture/microservices/account-service/runtime-and-data.md#L11-L11: replace "the request waits for its owner-fence outcome before mutating the token or password" with "the request records its exact intent without token/password mutation and returns retryable AUTH_UNAVAILABLE until a same-token retry observes the settled owner-fence outcome".
      • design/project-management/implementation-tracking/player-access-and-session.md#L33-L33: replace "token/password mutation waits for its owner-fence outcome" with the same retryable-denial wording.

      As per path instructions: "Review docs for canonical-current-state consistency."

      📍 Affects 2 files

      • design/architecture/microservices/account-service/runtime-and-data.md#L11-L11 (this comment)
      • design/project-management/implementation-tracking/player-access-and-session.md#L33-L33
      • Accepted Accepted exact retryable AUTH_UNAVAILABLE wording; WAITING persists original intent without token/password mutation, never blocks the request waiting for owners.
    5. Return a token denial for a SOURCE_ABORTED intent instead of an internal error.Minor

      A DEFINITIVE_ABORT (Lines 2507-2523) marks the journal row SOURCE_ABORTED and leaves the password_reset_token row in place. On any retry with the same token:

      1. findAccountIdByTokenHash finds the row, so resolvedToken stays empty.
      2. pending holds the aborted Intent, so originalIntent != null.
      3. The flow reads authority and calls participate.
      4. participate throws IllegalStateException("Terminal password-reset source intent has no receipt") at Lines 100-102 of AccountPasswordResetDraftSourceChangeRepository.

      token_hash is the V89 primary key, so no new intent can ever be created for that token. The token stays readable but can never be used, and every retry returns an internal error rather than "Invalid token". This is reachable when a capture mismatch occurs while the intent waits.

      Check the terminal status before reading authority or calling participate. Map it to the original denial.

      🐛 Proposed fix

           Intent originalIntent = pending.orElse(null);
           if (originalIntent != null
               && (originalIntent.accountId() != account.getId()
                   || !originalIntent.accountUuid().equals(account.getAccountUuid()))) {
             throw new IllegalStateException("Password-reset Draft intent Account binding changed");
           }
      +    if (originalIntent != null && "SOURCE_ABORTED".equals(originalIntent.status())) {
      +      return PasswordResetAttempt.aborted(
      +          originalIntent.tokenExpiresAt().isAfter(LocalDateTime.now())
      +              ? "Invalid token"
      +              : "Token expired");
      +    }
      

      Also delete or expire the token row in the same transaction as markSourceAborted. Then the user is prompted to request a new reset link.

      • Accepted Accepted terminal aborted intent client denial with exact owner/request binding. Same-transaction token invalidation must preserve receipt/FK and rollback guarantees; no terminal intent server error.
    6. Preserve password-reset and logout-all branches in both V80 guards.Major

      V80 replaces both shared guards but accepts only ACCOUNT_AUTHORITY_CHANGED and ACCOUNT_SECURITY_STATE_CHANGED.

      Password-reset completion updates the locked Account password hash, advances Account authority, and appends a PASSWORD_RESET_COMMITTED event. The Account update guard then cannot use its security-state branch and falls through to the legacy branch, which requires ACCOUNT_AUTHORITY_CHANGED and mutationKinds. The deferred Account trigger can therefore reject the reset transaction.

      Logout-all advances the Account source state and appends a LOGOUT_ALL_COMMITTED event as the latest source event. The source-record guard rejects that event with Unsupported Account source event type.

      Add explicit password-reset and logout-all branches to both guards. Bind each branch to its matching immutable operation receipt, Account identity, event identity and payload, authority counters, and issuance-fence values. The Account update branches must also validate the permitted Account state changes.

      V79’s acceptance of these schemas as prior checkpoints does not make them valid current events for the V80 guards.

      • Accepted Accepted exact reset/logout receipt branches in both V80 source/Account mutation guards; retain legacy/security and immutable payload, identity, counter, fence and permitted-state checks.
    7. Use Propagation.MANDATORY for findByIdForUpdate.Minor

      findByIdForUpdate uses @Transactional, which means REQUIRED propagation. If a caller has no surrounding transaction, the method opens its own transaction. The method returns after the row lock is already released, and the caller receives no serialization. The sibling methods findByAccountUuidForUpdate and updatePasswordHashForLockedAccount require a writable owner transaction. Apply the same contract here.

      Proposed fix

      --- "a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java"
      +++ "b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java"
      @@ -55,11 +55,12 @@
         }
       
         /** Locks one exact persisted Account row before an owner-local authority mutation. */
      -  @Transactional
      +  @Transactional(propagation = Propagation.MANDATORY)
         public Optional<Account> findByIdForUpdate(Long id) {
           if (id == null || id <= 0L) {
             throw new IllegalArgumentException("A positive persisted Account ID is required");
           }
      +    requireWritableOwnerTransaction();
           return Optional.ofNullable(
               dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).forUpdate().fetchOne(this::toEntity));
         }
      
      • Accepted Accepted mandatory writable owner transaction for findByIdForUpdate; prove outside/read-only transaction denies before locking.
    8. Keep generic Account updates readable by LOGIN source reads.Major

      AccountRepository.save records generic source events for changes to passwordHash, emailVerified, loginAuthModes, and role. readCurrentIssuerAccountSources now validates every retained event through requireRetainedEvent, while verifyEvent accepts only password-reset, logout-all, and security-state schemas. A generic Account event is therefore rejected with SourceEvidenceUnavailableException. Later closed events cannot repair the stream because the generic event remains in retained history.

      Accept and project validated legacy AccountEvent heads, or stop generic saves from changing fields that this reader must support.

      • Rejected Reject promotion of generic Account events to closed currentness: they lack operation-specific receipt/readback evidence, intentionally denied by current source contract. Keep exact retained history; typed AUTH_UNAVAILABLE and truthful gaps handled by4233551592.
    9. Use the configured jOOQ ignore terminator.Minor

      The repository uses jOOQ DDLDatabase defaults, where the closing token is [jooq ignore stop]. [jooq ignore end] is not configured, so it does not close the ignore region at line 90. Replace it with:

      --- [jooq ignore end]
      +-- [jooq ignore stop]
      
      • Accepted Accepted configured jOOQ stop terminator; shared with CLI#5. Regenerate jOOQ and retain protected baseline SQL.
    10. Account source reads now replay the full retained history on every call.Trivial

      readCurrentSource previously verified only the head event, and the comment at Lines 677-679 still describes that design. For ScopeKind.ACCOUNT, it now calls verifyEventHistory. That method loads and verifies every event from sequence 1 to the head. For each closed event, it also builds a new AccountAuthoritySourceEventReadback and runs its receipt queries. readCurrentSource also runs a count(*) query on the event table.

      This path runs on every recordAccountUpdate, readCurrentIssuerAccountSources, prepareClosedAccountAdvance, and advanceClosedAccountHead. advanceClosedAccountHead runs it twice. The cost is O(n) queries per call, and n grows with each reset, logout-all, or security update. These calls also hold FOR SHARE/FOR UPDATE locks.

      Possible fixes:

      • Persist a verified-through checkpoint and verify only the events appended after it.
      • Make the DB guards enforce the receipt invariant, as V38/V40 do for contiguity.

      Also update the stale comment in verifyLatestEvent.

      • Accepted Partially accepted stale comment correction, shared with CLI#3. Reject unproved latest-only/marker shortcut: closed-prefix and mixed history validation must remain. No performance optimization is claimed.
    11. Map legacy Account event readback failures to AUTH_UNAVAILABLE.Major

      When emailVerified changes from false to true, verifyEmail calls AccountRepository.save, which appends an account-auth-authority-source-event/v1 event. requireCurrentLatest later sends that event to verifyEvent, which supports only password-reset, logout-all, and security-state schemas. The generic event reaches IllegalStateException("Account source event schema is unsupported").

      This can prevent later password resets before token processing. The gRPC handler then returns INVALID_ARGUMENT instead of the intended AUTH_UNAVAILABLE. Account source reads can fail in the same way.

      Map the unsupported generic schema to SourceEvidenceUnavailableException. Keep the fail-closed behavior, and update the integration expectation and tracker text to state that Accounts with retained generic history cannot complete a reset until the history has a closed operation-specific readback contract.

      -        default -> throw new IllegalStateException("Account source event schema is unsupported");
      +        default ->
      +            throw new AccountAuthoritySourceEvidenceRepository
      +                .SourceEvidenceUnavailableException();
      
      • Accepted Accepted unsupported generic history maps typed SourceEvidenceUnavailableException/AUTH_UNAVAILABLE, preserving closed-receipt-only currentness and exact retained evidence.
    12. Create the missing disclosure and settlement objects before using these checks.Major

      DraftAuthorizationFenceRepository queries the disclosure tables and the publication/Game Logic settlement tables and functions, but no migration through V89 defines them. Calls that reach these checks can fail before enforcing the fence. Add the required Flyway DDL, and update the stale V99 Javadoc reference. Do not remove the checks.

      • Accepted Accepted complete nonactivating disclosure/publication/GameLogic storage closure and exact settlement checks; retain checks, no empty stubs or missing-dependency approval. Final forward map coordinated with Document.
    13. Enforce the settled Draft source change for environment binding updates.Trivial

      V86 requires source_change_binding for predecessor updates, but it does not require the matching Draft source change to be SOURCE_COMMITTED or to contain the exact environment-binding scope. A committed publication can therefore advance the binding head while its Draft source change remains WAITING.

      Add the deferred fence used by V85:

      ♻️ Suggested deferred fence trigger

      +CREATE FUNCTION account_hosted_terms_environment_binding_fence_complete_guard()
      +RETURNS TRIGGER LANGUAGE plpgsql AS $$
      +DECLARE predecessor UUID;
      +BEGIN
      +    IF NEW.status = 'COMMITTED' THEN
      +        SELECT predecessor_binding_id INTO predecessor
      +            FROM account_hosted_terms_environment_bindings
      +            WHERE environment_boundary = NEW.environment_boundary
      +              AND binding_id = NEW.candidate_binding_id;
      +        IF predecessor IS NOT NULL AND (NEW.source_change_binding IS NULL OR NOT EXISTS (
      +            SELECT 1 FROM account_draft_authorization_source_changes change
      +            JOIN account_draft_authorization_changed_scopes changed USING (change_id)
      +            WHERE change.change_id = NEW.request_id
      +              AND change.binding = NEW.source_change_binding
      +              AND change.status = 'SOURCE_COMMITTED'
      +              AND changed.source_key =
      +                  'HOSTED_TERMS:environment-boundary/' || NEW.environment_boundary)) THEN
      +            RAISE EXCEPTION 'Updated environment binding requires fully settled exact Draft source change';
      +        END IF;
      +    END IF;
      +    RETURN NULL;
      +END;
      +$$;
      +CREATE CONSTRAINT TRIGGER account_hosted_terms_environment_binding_fence_complete
      +    AFTER INSERT OR UPDATE ON account_hosted_terms_environment_binding_publications
      +    DEFERRABLE INITIALLY DEFERRED
      +    FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_fence_complete_guard();
      
      • Accepted Accepted deferred exact committed predecessor environment-source fence and exact changed-scope check; prove WAITING/wrong scope rejected, initial binding unaffected.
    14. Replace the self-comparison with a check of affirmative_action_digest.Minor

      The record is built from row.get("affirmative_action_evidence", byte[].class). Line 527-529 then compares the record's copy with the same column, so the comparison is always true. The method never checks the stored affirmative_action_digest against the stored evidence bytes. A row with mismatched action evidence and digest therefore reads back as valid. Compare the digest, as the code already does for the party source.

      Proposed fix

      --- "a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java"
      +++ "b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java"
      @@ -524,11 +524,10 @@
                   row.get("affirmative_action_evidence", byte[].class),
                   row.get("affirmative_action_digest", String.class),
                   row.get("accepted_at", OffsetDateTime.class));
      -    if (!Arrays.equals(
      -            acceptance.affirmativeActionEvidence(),
      -            row.get("affirmative_action_evidence", byte[].class))
      +    if (!HostedTermsEncoding.digest(acceptance.affirmativeActionEvidence())
      +            .equals(row.get("affirmative_action_digest", String.class))
               || !HostedTermsEncoding.digest(acceptance.individualPartySource())
                   .equals(row.get("individual_party_source_digest", String.class))) {
             throw new IllegalStateException("Stored acceptance evidence digest conflicts");
           }
           return acceptance;
      
      • Accepted Accepted validate affirmative action evidence digest instead of tautological byte self-comparison; prove corruption rejection without activating hosted terms.
  2. CLI Review 1 CompletedRuntime 3m 30s
    Found: 5 Accepted: 1/3/1 Routed: 0
    1. Avoid replaying the full Account event history on every source read.Trivial

      readCurrentSource now calls verifyEventHistory for every Account scope. That method decodes every event from sequence 1 to the checkpoint. For each closed event, requireRetainedEvent adds receipt lookups and, for security-state events, more shared row locks and readbacks.

      readCurrentSource runs several times per operation. Examples are recordAccountUpdate (before and after the append), readCurrentIssuerAccountSources, prepareClosedAccountAdvance, and advanceClosedAccountHead. Each Account stream grows with every security-relevant update, so the cost of each read grows without bound. The comment in verifyLatestEvent (lines 677-679) still says the read path avoids "replaying an ever-growing retained history". That statement is now true only for issuer scopes.

      Choose one of these options:

      • Validate history once, at append time. Persist a verified-history marker, such as a closed or legacy flag on the source head. Then verify only the latest event on read.
      • Rely on the V38/V40 immutability guards and verify only the event at the checkpoint.

      Update the stale comment in either case.

      • Accepted Partially accepted stale-comment correction. Reject latest-only shortcut: mixed legacy/closed history supplies retained legacy Account state and last security cutoff, absent from that shortcut. Performance optimization is not implemented or claimed.
    2. Do not keep superseded password hashes in the source-change journal.Major

      participate stores the Argon2 hash of the new password in account_password_reset_draft_source_changes.password_verifier. markSourceCommitted and markSourceAborted never clear it, so the row keeps the hash after the operation ends. The row is also never deleted.

      Consequence: after a later password change, the old hash still sits in a second table. Over time each Account collects every reset hash in a store that is not the credential table. Old hashes are offline-cracking material for the user's earlier passwords.

      The verifier is needed only while the intent is WAITING, to finish the deferred reset. Clear password_verifier when the intent becomes SOURCE_COMMITTED or SOURCE_ABORTED. Keep password_verifier_digest for receipt binding. Then relax the sha256Hex(intent.passwordVerifier()) check in requireIntent for terminal rows. Also define a retention horizon for terminal journal rows.

      • Accepted Accepted terminal verifier clearing with WAITING recovery and exact digest/receipt binding preserved; add SQL/readback proof. Reject invented numeric retention horizon; owner terminal receipt lifecycle remains incomplete.
    3. Map a terminal pending intent to Invalid token instead of a server error.Minor

      The capture-mismatch abort path (lines 2507-2514) marks the intent SOURCE_ABORTED but leaves the reset token unconsumed. On the next retry with the same token, findByTokenHash returns the aborted intent. participate then throws IllegalStateException("Terminal password-reset source intent has no receipt") (line 101 of AccountPasswordResetDraftSourceChangeRepository.java).

      The first response was IllegalArgumentException("Invalid token"). Every later retry gets an unhandled 500 instead. The token also stays readable until the cleanup job removes it, but the user can never use it.

      When originalIntent.status() is SOURCE_ABORTED, fail with the same client error before calling participate.

      Proposed fix

           Intent originalIntent = pending.orElse(null);
      +    if (originalIntent != null && "SOURCE_ABORTED".equals(originalIntent.status())) {
      +      throw new IllegalArgumentException("Invalid token");
      +    }
           if (originalIntent != null
      
      • Accepted Accepted: a same-Account SOURCE_ABORTED reset retry must return the existing Invalid token client denial rather than an unhandled terminal-intent server error, without weakening Account/request binding.
    4. Align the AA-1.3 capability row with the new password-reset status.Minor

      Lines 33-35 say that password-reset completion now claims and consumes its token atomically. The unchanged AA-1.3 row (line 51) still says "Recovery token consumption and reset-driven revocation remain incomplete". That row also has no anchors for the new production code: AccountPasswordResetOperationRepository.java, AccountPasswordResetDraftSourceChangeRepository.java, PasswordResetTokenRepository.java, V77, and V89. Its proof anchors also omit PasswordResetAuthorityProducerPostgresIntegrationTest.java and AccountPasswordResetOperationRepositoryTest.java.

      The Capability Status row is the scan-first status surface, so it now contradicts the narrative above it. Add the anchors to the AA-1.3 row. Replace its gap text with the remaining work: reset-driven revocation, other recovery workflows, and physical PostgreSQL proof.

      As per coding guidelines: "Keep its status, implementation record, validation, gaps, decisions, and service-map sections aligned when a domain boundary changes", and "implemented and partial rows name concrete production anchors."

      • Accepted Accepted: update AA-1.3 production/proof anchors and gap wording for atomic reset-token consumption; keep capability partial and physical PostgreSQL, revocation and other recovery gaps explicit.
    5. Close the jOOQ ignore blocks with [jooq ignore stop].Minor

      V77 and V78 close their ignore blocks with -- [jooq ignore end]. jOOQ does not recognize end as a stop token. Every other migration in this change uses -- [jooq ignore stop]. If the jOOQ DDL simulation carries the open ignore state into later scripts, later migrations drop out of jOOQ code generation.

      • services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql#L91-L91: replace -- [jooq ignore end] with -- [jooq ignore stop].
      • services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql#L90-L90: replace -- [jooq ignore end] with -- [jooq ignore stop].
      • Accepted Accepted: use recognized jOOQ ignore stop terminators in unreleased V77/V78; preserve SQL bodies and protected migration baseline, regenerate jOOQ and run owning validation.
  3. CLI Review 2 CompletedRuntime 4m 24s
    Found: 8 Accepted: 0/5/1 Routed: 0
    1. Account source reads now scale with the full event history.Trivial

      verifyEventHistory loads and verifies every event from sequence 1 to the head on every Account source read. For each closed event, closedEventReadback().requireRetainedEvent adds more queries: the receipt lookup, the checkpoint read, and for security-state events readOperation / requireReceiptNotAhead. readCurrentIssuerAccountSources then calls requireCurrentLatest, which walks the same history again (AccountAuthoritySourceEventReadback Lines 117-124).

      This affects live paths. AccountRepository.save → recordAccountUpdate → readCurrentSource runs on every security-relevant save, for example verifyEmail. Password reset adds two more full passes (before and after commit). The number of queries per call grows without bound as an Account accumulates events.

      Consider storing a verified prefix checkpoint. For example, keep a durable "history verified through sequence N" marker that the same owner transaction advances, and verify only events after N. Database guards already make events immutable.

      • Rejected A persistent verified-prefix cache adds an unproved authority mechanism: immutable event rows alone do not preserve current receipt/fence/operation readback. Linear verification is real but no measured failure/SLO establishes this proposed cache as necessary; preserve full currentness proof.
    2. Enforce the initial state on INSERT for the state-machine tables.Minor

      Both guards fire only BEFORE UPDATE OR DELETE. Each table CHECK accepts terminal states. An INSERT can therefore create a row that is already COMMITTED or DISCLOSED, without the transition and readback rules. The other new journals (V83, V85, V86, V88, V89) reject non-initial inserts.

      • services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql#L107-L109: add INSERT to the trigger. Require status = 'PREPARED' with null candidate and result columns.
      • services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql#L142-L144: add INSERT to the trigger. Require status = 'PREPARED', dispatch_attempts = 0 and null result columns.
      • Accepted V90 and V98 UPDATE/DELETE-only state guards allow initial inserts directly into terminal states satisfying table checks. Enforce initial PREPARED insert and null candidate/result/zero-attempt invariants with positive and negative PostgreSQL fixtures.
    3. Use IS DISTINCT FROM in the publication completeness guard.Minor

      These checks use <> on JSON extractions. A missing field gives NULL. NULL inside the OR chain does not raise. Two concrete cases:

      • If the selection frame has no intent.canonicalTenantId or no intent.publishRequestId, the frame passes "Changed publication selection identity" (lines 94-95).
      • If the bundle has no issuanceFence, or the source payload has no accountId or tenantId, the guard does not check them (lines 61, 65-66).

      V95 fixed the same guard with IS DISTINCT FROM. Apply that fix here too.

      Proposed fix

      -    IF convert_from(parsed, 'UTF8')::JSONB->'intent'->>'canonicalTenantId' <> NEW.tenant_uuid::TEXT
      -        OR convert_from(parsed, 'UTF8')::JSONB->'intent'->>'publishRequestId' <> NEW.publish_request_id THEN
      +    IF convert_from(parsed, 'UTF8')::JSONB->'intent'->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT
      +        OR convert_from(parsed, 'UTF8')::JSONB->'intent'->>'publishRequestId' IS DISTINCT FROM NEW.publish_request_id THEN
      

      Apply the same change to lines 58-66 and to the source_count/decode comparisons at lines 100-106.

      Also applies to: 94-95

      • Accepted V91 JSON identity/vector comparisons using <> permit missing fields via SQL NULL. Use null-safe IS DISTINCT FROM and fail closed on absent source/count fields, with malformed JSON/vector negatives.
    4. Password reset now fails permanently for any Account that has an older-format source event.Major

      requireCurrentLatest passes every earlier event through requireRetainedEvent → verifyEvent. verifyEvent accepts only the reset, logout-all, and security-state schemas. For any other schemaVersion it reaches default -> throw new SourceEvidenceUnavailableException() (Line 468).

      AccountRepository.save still writes events in the older AccountAuthoritySourceEventV1Codec format through recordAccountUpdate. A common trigger:

      • verifyEmail changes email_verified.
      • recordAccountUpdate appends an EMAIL_LOGIN_ELIGIBILITY_CHANGED event in the older format.
      • After that, completePasswordReset calls requireCurrentLatest and always throws SourceEvidenceUnavailableException, which callers see as retryable AUTH_UNAVAILABLE.

      Consequences:

      • Reset regression. Most verified accounts can no longer reset their password. Before this PR, the reset path went through save / recordAccountUpdate, which accepts these events.
      • Endless retries. The error says "retry", but no retry can succeed, so clients loop.
      • Other blocked paths. The same check now runs inside AccountAuthoritySourceEvidenceRepository.readCurrentIssuerAccountSources. That blocks first-JOIN membership production and creator bootstrap (AccountCreatorMembershipSourceReader.readCurrentUpstreamSourceEvidence) for these Accounts.

      The tracker states that generic events "fail closed as AUTH_UNAVAILABLE". It does not say that this covers nearly every verified Account.

      Either:

      • accept older-format Account events in the history walk, as AccountAuthoritySourceEvidenceRepository.verifyEventHistory already does, while requiring a closed receipt only for closed schemas; or
      • return a terminal, non-retryable error and record the limitation in the AA-1.3 gap.
      • Rejected Deliberate tested fail-closed currentness: generic history lacks exact owner receipts. Tracker Retained Account Source Prerequisite records AUTH_UNAVAILABLE and incomplete closure. Accepting generic digests or changing that outcome weakens the owning contract; full producer closure remains required.
    5. Lock source rows in the canonical sort-key order.Minor

      The comment says the guard uses "Same sorted original source locks as Account's producer/source writers". The query orders by l.source_key, which uses the database collation. V76, V93 and V97 order by account_publication_authorization_source_sort_key(source_key), which is UTF-16 code-unit order. If the two orders disagree for a key pair, this guard and a V76 readback guard can lock the same rows in opposite order. PostgreSQL then aborts one of the transactions with a deadlock error.

      Proposed fix

      -        WHERE s.operation_id = NEW.operation_id ORDER BY l.source_key FOR UPDATE OF l;
      +        WHERE s.operation_id = NEW.operation_id
      +        ORDER BY account_publication_authorization_source_sort_key(l.source_key) FOR UPDATE OF l;
      
      • Accepted V96 currently orders locks by database collation while V76/V93/V97 use canonical UTF-16 sort keys. Align settlement to shared sort-key function and add focused guard proof.
    6. Add the missing ; separators in the AA-1.3 anchor cells.Minor

      The implementation-anchor cell joins two links with a double space and no separator: ...V40__account_authority_source_baselines.sql) [AccountPasswordResetOperationRepository.java]. The proof-anchor cell has the same defect before [PasswordResetAuthorityProducerPostgresIntegrationTest.java]. Every other anchor list in this table uses ; . Strict anchor parsing (for example, dev-tools/tests/architecture-doc-contracts.sh) can merge or misread these links. Readers also see the cell as one run-on value.

      Proposed fix

      -...V40__account_authority_source_baselines.sql)  [AccountPasswordResetOperationRepository.java]...
      +...V40__account_authority_source_baselines.sql); [AccountPasswordResetOperationRepository.java]...
      -...AccountAuthoritySourceEvidencePersistenceIntegrationTest.java)  [PasswordResetAuthorityProducerPostgresIntegrationTest.java]...
      +...AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java]...
      

      As per coding guidelines: "Evidence targets must be repository-local and resolvable".

      • Accepted Repair two missing semicolon separators in AA-1.3 implementation/proof anchor cells; documentation-only fix assigned.
    7. Use the shared 2048-character source-key width in every source table.Minor

      V76 widened account_draft_authorization_source_locks.source_key to 2048 because keys are shared. V91 and V98 narrow the width to 512 again. Hosted-terms environment keys are 'HOSTED_TERMS:environment-boundary/' || environment_boundary, with a boundary of up to 512 characters, so these keys can reach 546 characters. Inserts with such keys fail.

      • services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql#L24-L24: declare source_key VARCHAR(2048).
      • services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql#L7-L7: declare VARCHAR(2048) and change the CHECK to octet_length(source_key) <= 2048.
      • services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql#L42-L43: declare source_key VARCHAR(2048).
      • Accepted V91 and V98 use narrower 512-character source keys than the V76 shared 2048-byte contract, rejecting legitimate max environment-derived keys. Align columns/checks and prove long valid key and oversized denial.
    8. Keep earlier codec failures as suppressed exceptions in verifyAccountSource.Trivial

      The nested catch (IllegalArgumentException ...) chain drops currentSchemaMismatch, resetFailure, and logoutFailure. The caller sees only the exception from AccountSecurityStateAuthorityEventV1Codec.verify. This can mislead operators. Example: a real PasswordResetAuthorityEventV1Codec event with a tampered eventDigest is reported as a security-state schema error, and the digest error is lost. Add the earlier failures to the final exception with addSuppressed. As an alternative, select the codec by eventType before verifying.

      ♻️ Proposed change

      -        } catch (IllegalArgumentException logoutFailure) {
      -          var security =
      -              AccountSecurityStateAuthorityEventV1Codec.verify(supplied.canonicalEventJson());
      +        } catch (IllegalArgumentException logoutFailure) {
      +          AccountSecurityStateAuthorityEventV1Codec.SecurityStateEvent security;
      +          try {
      +            security =
      +                AccountSecurityStateAuthorityEventV1Codec.verify(supplied.canonicalEventJson());
      +          } catch (IllegalArgumentException securityFailure) {
      +            securityFailure.addSuppressed(currentSchemaMismatch);
      +            securityFailure.addSuppressed(resetFailure);
      +            securityFailure.addSuppressed(logoutFailure);
      +            throw securityFailure;
      +          }
      

      The security variable type is an assumption. Use the actual return type of verify, or var with a helper method.

      • Accepted Preserve prior codec verification errors as suppressed diagnostics without changing evidence acceptance. Bounded fix and malformed reset-digest regression assigned.
  4. CLI Review 3 CompletedRuntime 3m 42s
    Found: 4 Accepted: 0/3/1 Routed: 0
    1. Align the PostgreSQL proof status with the companion docs.Minor

      Line 9 says "physical PostgreSQL proof remains pending." The other two docs give a more specific status:

      • runtime-and-data.md Line 13 says physical PostgreSQL execution at 7a665c83e81f5cec85fcd7ec9a205c291bc0eba2 "established partial evidence": fresh install through V97, the V73 upgrade, and selected V80/V86 cases passed, while other cases failed.
      • The tracker (Line 11) records 92 executed cases with three failures.

      A reader of the README can conclude that no physical execution happened. State the partial result, the failures, and the unrun V98 proof, or link only to the tracker section.

      Proposed wording

      -... Focused checks and integration-source compilation pass; physical PostgreSQL proof remains pending. ...
      +... Focused checks and integration-source compilation pass; physical PostgreSQL execution at 7a established only partial evidence (some cases failed, and V98 remains unrun). ...
      

      As per path instructions: "Review docs for canonical-current-state consistency. Flag ... conflicts between architecture docs".

      • Accepted Accepted README status correction; link owning physical-proof status rather than implying no execution occurred.
    2. Replace the stale migration numbers in the migration comments and the operator-facing error text.Minor

      These migrations name versions that no longer match the objects they describe: "V57" for the Draft source change (V75/V76), "V78" for security-state (V79), and "V107" for the publication guard (V91). Operators who read these failure messages will look in the wrong migration.

      • services/account-service/src/main/resources/db/migration/V80__account_security_event_source_guard.sql#L423-L424: replace "V78 security-state" with "V79 security-state" or "security-state" in this RAISE message and in the other V78 security-state messages in this function.
      • services/account-service/src/main/resources/db/migration/V80__account_security_event_source_guard.sql#L116-L118: change "V78 deliberately omits" to name V79.
      • services/account-service/src/main/resources/db/migration/V93__account_selected_publication_settlement.sql#L151-L160: replace "V107" with "V91" in the comment and the RAISE text.
      • services/account-service/src/main/resources/db/migration/V79__account_security_state_operations.sql#L236-L236: replace "V57" with the V75/V76 source-change name in the message and in the related comment at Line 208.
      • services/account-service/src/main/resources/db/migration/V88__account_logout_all_pending_draft_source_changes.sql#L152-L152: replace "V57" with "V76", matching the V89 wording, here and in Line 224.
      • Accepted Accepted stale migration references in V79/V80/V88/V93 operator diagnostics/comments; retain correct operation references.
    3. Move the duplicated strict-codec helpers into one shared package-private helper.Trivial

      requireExactFields, requireExactText, requireText, requireUuid, requirePositiveDecimal, digest, canonicalJson, the cutoff-binding checks, and the strict ObjectMapper setup appear twice. One copy is in this file. The other copy is in services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java (Lines 181-264). The two copies are nearly identical. AccountSecurityStateAuthorityEventV1Codec and RuntimeMembershipAuthorityEvidenceValidator also each redefine the same UUID, positive-decimal, and nil-UUID patterns.

      These codecs define the security-event wire contract that RuntimeMembershipAuthorityEvidenceValidator.verifyAccountSource accepts. If someone later fixes a validation rule in one copy only, the copies will diverge. Each event schema would then accept different inputs. Keep only the schema-specific field sets and bindings in each codec.

      ♻️ Sketch of a shared helper

      // package-private, same package
      final class StrictAuthorityEventSupport {
        static final Pattern UUID_PATTERN =
            Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
        static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*");
        static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}");
        static final ObjectMapper JSON = /* strict duplicate + trailing-token mapper */;
      
        static void requireExactFields(ObjectNode object, Set<String> required, String path) { ... }
        static String requireText(ObjectNode object, String field, String path) { ... }
        static String requireUuid(ObjectNode object, String field, String path) { ... }
        static String requirePositiveDecimal(ObjectNode object, String field, String path) { ... }
        static void requireAccountCutoffBinding(ObjectNode event, String streamKey) { ... }
        static String digest(ObjectNode preimage) { ... }
        static String canonicalJson(ObjectNode wire) { ... }
      }
      
      • Accepted Accepted shared strict-codec support to prevent validation drift; preserve schema-specific bindings, wire bytes and errors.
    4. Require resultdigest to equal the SHA-256 of resultpayload.Minor

      Require `result_digest` to equal the SHA-256 of `result_payload`.

      The table checks only that result_digest has the correct format. A terminal update can store a digest that does not match the payload, and the trigger accepts it. V85 and V86 enforce result_digest = 'sha256:' || encode(sha256(result_payload), 'hex') for the same kind of terminal result. Add the same constraint here.

      Proposed fix

           result_digest VARCHAR(71) CHECK (result_digest ~ '^sha256:[0-9a-f]{64}$'),
      +    CHECK (result_digest IS NULL
      +        OR result_digest = 'sha256:' || encode(sha256(result_payload), 'hex')),
      
      • Accepted Accepted V98 terminal result digest/payload integrity constraint with mismatch and valid-transition PostgreSQL regression.
  5. Hosted Review 2 CompletedRuntime 10m 03s
    Found: 5 Accepted: 0/3/2 Routed: 0
    1. Fix the stale Javadoc on markSourceAborted: a mixed commit-order outcome stays pending.Trivial

      The Javadoc says a commit-order abort needs two terminal owner readbacks, "including a mixed vector". The code does not do this. settlement() returns PENDING for a mixed COMMIT_ORDER vector, so allAffectedSettled rejects the abort. The V76 account_draft_authorization_is_settled check also requires count(DISTINCT outcome) = 1. A future owner verifier that relies on this Javadoc would expect a mixed result to settle the change, but the abort would always be rejected.

      Proposed fix

      -   * source commit applies: revoke order requires two definitive aborts; commit order requires two
      -   * exact terminal owner readbacks, including a mixed vector.
      +   * source commit applies: revoke order requires every required owner to report a definitive
      +   * abort; commit order requires every required owner to report one uniform exact terminal
      +   * outcome. A mixed vector remains pending.
      
      • Accepted Accepted Javadoc correction: COMMIT_ORDER requires uniform terminal owner outcome; mixed vector stays pending.
    2. Reuse one shared JsonMapper in all three canonical encoders.Trivial

      Each canonical helper calls JsonMapper.builder().build() every time it runs. A single currentness or publication request runs many encodings: party, catalog, acceptance, currentness source, and binding receipt. A built mapper is thread-safe and has no per-call configuration here. Build it once and reuse it.

      • services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncoding.java#L99-L107: add private static final JsonMapper JSON = JsonMapper.builder().build(); and call JSON.writeValueAsString(fields).
      • services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEncoding.java#L240-L247: make the same change with a static JsonMapper.
      • services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingEncoding.java#L79-L86: make the same change with a static JsonMapper.

      ♻️ Proposed refactor (pattern for each file)

      +  private static final JsonMapper JSON = JsonMapper.builder().build();
      @@
      -      return Rfc8785CanonicalJson.canonicalizeUtf8(
      -          JsonMapper.builder().build().writeValueAsString(fields));
      +      return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(fields));
      

      📍 Affects 3 files

      • services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncoding.java#L99-L107 (this comment)
      • services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEncoding.java#L240-L247
      • services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingEncoding.java#L79-L86
      • Accepted Accepted reuse immutable JsonMapper per canonical encoder; preserve exact bytes and validation.
    3. Make the local integration-run count match the latest recorded run, or name the run it describes.Minor

      Line 11 says the local integration run "executed two cases and skipped 83 without Docker." The PR description says the corrected V98 batch's local integration run reported 86 cases: two executed and 84 skipped. The tracker does not say which run its 85-case figure comes from. A reader will treat it as the current local result. Either update the counts to the latest run (2 executed, 84 skipped) or name the head/batch that produced 83 skips.

      As per path instructions: "Review docs for canonical-current-state consistency." As per coding guidelines: keep the tracker's "status, implementation record, validation, gaps … aligned".

      • Accepted Accepted qualify historical85-case result and corrected86-case scope by exact batch; do not imply unrun physical proof is complete.
    4. Add TRUNCATE guards to the three creator-party tables.Minor

      The immutable guard covers only UPDATE OR DELETE. A TRUNCATE on account_tenant_creator_party_history removes all prior history. Then account_creator_party_history_insert_guard accepts a new FRESH_INITIAL row for the same tenant. That breaks the stated rule "All history counts as prior state". The other immutable tables added in this PR (V74, V79, V81, V90, V91, V98) have statement-level TRUNCATE guards. Add the same guards here.

      🔒️ Proposed fix

       CREATE TRIGGER account_creator_party_operation_immutable
           BEFORE UPDATE OR DELETE ON account_fresh_creator_party_association_operations
           FOR EACH ROW EXECUTE FUNCTION account_creator_party_immutable_guard();
      +CREATE TRIGGER account_individual_creator_party_no_truncate
      +    BEFORE TRUNCATE ON account_individual_creator_party_sources
      +    FOR EACH STATEMENT EXECUTE FUNCTION account_creator_party_immutable_guard();
      +CREATE TRIGGER account_creator_party_history_no_truncate
      +    BEFORE TRUNCATE ON account_tenant_creator_party_history
      +    FOR EACH STATEMENT EXECUTE FUNCTION account_creator_party_immutable_guard();
      +CREATE TRIGGER account_creator_party_operation_no_truncate
      +    BEFORE TRUNCATE ON account_fresh_creator_party_association_operations
      +    FOR EACH STATEMENT EXECUTE FUNCTION account_creator_party_immutable_guard();
      
      • Accepted Accepted V84 statement-level TRUNCATE guards preserving creator source/history/receipts with retained-history rejection proof.
    5. Map a pending source change to AUTH_UNAVAILABLE.Minor

      When a new password-reset change overlaps a waiting source change, requestSourceChange throws IllegalStateException. completePasswordReset handles only SourceEvidenceUnavailableException as unavailable; the generic path returns INVALID_ARGUMENT.

      Map only this pending-change condition and rethrow other IllegalStateException instances.

      --- "a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java"
      +++ "b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java"
      @@ -133,8 +133,16 @@
                   nextSequence,
                   requestId,
                   eventId);
           SourceChange change = new SourceChange(UUID.randomUUID(), List.of(source), mutation);
      -    fences.requestSourceChange(change);
      +    try {
      +      fences.requestSourceChange(change);
      +    } catch (IllegalStateException pending) {
      +      if ("Another authority source change is already pending".equals(pending.getMessage())) {
      +        throw new net.firedevops.firemud.accountservice.repository
      +            .AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException();
      +      }
      +      throw pending;
      +    }
       
           dsl.execute(
               "INSERT INTO "
      
      • Accepted Accepted typed pending-source condition mapped only to retryable SourceEvidenceUnavailable; preserve unrelated failures and rollback.
  6. CLI Review 4 CompletedRuntime 3m 29s
    Found: 3 Accepted: 1/0/1 Routed: 0
    1. Every Account source read now runs one query round per retained event.Trivial

      readCurrentSource counts the stream events. For Account scope, it then calls verifyEventHistory. That method loads every event from sequence 1 to the head. For each closed event, it also builds a fresh AccountAuthoritySourceEventReadback and runs receipt lookups.

      readCurrentIssuerAccountSources repeats a full history walk through requireCurrentLatest. The cost of each read grows with the number of Account security mutations. The walk runs on every source read, including reads that happen while the Account row lock is held. History has no bound, because receipt retention is unresolved.

      Before this path serves LOGIN or JOIN traffic:

      • Add a verified history watermark, for example the last fully verified sequence and digest on account_authority_source_records.
      • Verify only the events after that watermark.
      • Add a latency metric for history length.

      Also applies to: 756-857

      • Rejected Repeated optional watermark proposal, with no measured latency defect. Current owner proof requires full immutable history/receipt verification; persisting a cache changes provenance and tamper guarantees. This passive slice does not justify skipping older evidence.
    2. V97 rejects this intake authorization at commit, so the test fails.Major

      V97 adds the deferred constraint trigger account_game_logic_intake_source_read_finalize_validate on account_game_logic_intake_authorizations. That trigger runs account_game_logic_intake_source_read_terminal_guard(), and the guard runs:

      SELECT * INTO STRICT original FROM account_game_logic_intake_source_read_reservations
          WHERE operation_id = NEW.operation_id FOR UPDATE;
      

      This fixture inserts the authorization and its sources without a matching account_game_logic_intake_source_read_reservations row. When the executeWithoutResult transaction commits, STRICT raises NO_DATA_FOUND. gameLogicSettlementAcceptsCompleteTerminalAndUsesCanonicalSourceLockOrder therefore never reaches the settlement insert.

      Fix the fixture so the run is valid under V97. In the same transaction, insert a reservation with matching identity fields, issuance evidence, and source rows. The reservation's 7th scope_bytes frame must equal the snapshot's bindingJson. Also seed a COMMIT_ORDER, settled Draft fence for that selection, because account_game_logic_intake_source_read_complete_guard requires it.

      • Accepted V97 deferred terminal guard requires the exact source-read reservation and settled original Draft fence; the new canonical-order fixture omits them and will fail at commit. Correct fixture only; preserve all guards and assertions.
    3. Run Argon2 hashing before you take the Account row lock.Trivial

      completePasswordResetInOwnerTransaction runs findByIdForUpdate first. While the Account row stays locked, it then runs:

      • verifyPassword (Line 2446)
      • hashPassword (Line 2462)

      Each call is Argon2 with 64 MiB of memory and 2 iterations. During that time the transaction holds the accounts row lock and a pooled connection. Concurrent resets, retries, and other writers to the same Account must wait for this work. The new-intent path does not need the lock to compute hashPassword(request.newPassword()). Compute the hash before passwordResetOwnerTransaction.execute(...) and pass it in. If an existing intent is found, discard the precomputed hash.

      • Accepted Fresh reset hashes its replacement password while holding the Account lock. Precompute only the new candidate verifier before the owner transaction; retain locked receipt/intent rechecks, original retry verifier and exact conflict checks.
  7. CLI Review 5 CompletedRuntime 3m 50s
    Found: 6 Accepted: 0/3/2 Routed: 0
    1. Bind the original globalRoles from the receipt, not from the current role source.Major

      expected_before_state and expected_after_state both read globalRoles from role_source_row.global_roles. As a result, before_state->'globalRoles' must always equal after_state->'globalRoles'. For a V79 receipt with GLOBAL_ROLE_CHANGED, the stored before_state has the old roles, so the guard raises at line 497.

      V79 allows mutation_kinds to contain GLOBAL_ROLE_CHANGED together with up to three other kinds. A role change alone does not touch protected accounts columns, so this trigger returns early. A combined change, for example role plus lifecycle, always fails, and changed_kinds can never contain GLOBAL_ROLE_CHANGED.

      Use the receipt's original roles for the before image. Keep the current role source for the after image.

      🐛 Proposed fix

               expected_before_state := jsonb_build_object(
                   'emailVerified', OLD.email_verified,
      -            'globalRoles', to_jsonb(role_source_row.global_roles),
      +            'globalRoles', before_state->'globalRoles',
                   'lifecycleState', upper(OLD.lifecycle_state),
                   'loginAuthModes', expected_old_modes);
      
      • Rejected Current V74 enforces empty immutable global roles; no migration74-98 or service registers a role writer. Combined role changes cannot occur. V79 checks original locked preimage; do not loosen V80 to self-asserted roles for an unimplemented future producer.
    2. Require the exact source evidence before DISPATCHAUTHORIZED.Minor

      Require the exact source evidence before `DISPATCH_AUTHORIZED`.

      The PREPARED → DISPATCH_AUTHORIZED transition does not check that account_hosted_terms_disclosure_sources contains a row for NEW.source_key. After this transition, account_hosted_terms_disclosure_source_insert_guard rejects all new source rows. A handoff authorized with no source row is therefore permanent. That handoff carries no source evidence, so the exact-source fence ("Exact hosted terms source has authorized disclosure") cannot apply to it. Add the check to the transition branch.

      🛡️ Proposed fix

           IF OLD.status = 'PREPARED' AND NEW.status = 'DISPATCH_AUTHORIZED'
               AND OLD.dispatch_attempts = 0 AND NEW.dispatch_attempts = 1
               AND NEW.result_outcome IS NULL AND NEW.result_payload IS NULL
      -        AND NEW.result_digest IS NULL AND NEW.result_recorded_at IS NULL THEN
      +        AND NEW.result_digest IS NULL AND NEW.result_recorded_at IS NULL
      +        AND EXISTS (SELECT 1 FROM account_hosted_terms_disclosure_sources s
      +            WHERE s.handoff_id = NEW.handoff_id AND s.source_key = NEW.source_key) THEN
               RETURN NEW;
      
      • Accepted V98 currently authorizes dispatch with no exact source row then prevents insertion. Require matching handoff/source before dispatch and prove missing or unrelated sources rejected.
    3. Every Account source read now does work that grows with the full event history.Trivial

      verifyEventHistory reads every event from sequence 1 to the checkpoint on each readCurrentSource call. For each closed event it also calls closedEventReadback(). That call builds a new AccountAuthoritySourceEventReadback and new operation repositories, then runs the receipt lookups. recordAccountUpdate calls readCurrentSource twice for each update. advanceClosedAccountHead calls it several times. The query count per Account mutation therefore grows linearly with the stream length, and the stream has no bound.

      Do these two things:

      • Create the readback once per call and reuse it outside the loop.
      • Persist a verified-history watermark, for example the last fully verified sequence on account_authority_source_records. Then reads verify only the events after that watermark.
      • Accepted Partially accepted: reuse one closed-event readback per history verification. Reject persisted watermark: no latency proof; skipping immutable old receipts changes current tamper/provenance verification.
    4. Deny TRUNCATE on every immutable evidence table.Minor

      Several "immutable" tables block only row-level UPDATE and DELETE. TRUNCATE does not fire row triggers, so it removes all retained evidence. Later guards depend on this evidence: V80 and V88 read the receipts, V84 reads the bootstrap rows, and V86 reads the catalog. V79, V81, V84, and V88–V98 already add statement-level truncate guards. Apply the same pattern here.

      • services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql#L88-L90: add BEFORE TRUNCATE ... FOR EACH STATEMENT EXECUTE FUNCTION account_password_reset_operation_immutable_guard().
      • services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql#L87-L89: add the same statement trigger that runs account_logout_all_operation_immutable_guard().
      • services/account-service/src/main/resources/db/migration/V83__account_tenant_creation_bootstrap.sql#L186-L188: add a statement trigger that runs account_tenant_creation_bootstrap_no_delete().
      • services/account-service/src/main/resources/db/migration/V85__account_hosted_terms_acceptance_workflow.sql#L124-L129: add statement triggers that run account_hosted_terms_immutable_guard() for catalog versions, acceptances, and publication operations. The V87 truncate trigger only holds source locks and does not deny the truncate.
      • services/account-service/src/main/resources/db/migration/V86__account_hosted_terms_environment_binding.sql#L105-L107: add statement triggers for account_hosted_terms_environment_bindings and account_hosted_terms_environment_binding_publications.
      • Accepted Add statement-level TRUNCATE denial for immutable V77/V78 receipts, V83 bootstrap and V85/V86 terms evidence; retain normal protected transitions and prove preservation.
    5. Use one current physical PostgreSQL and V98 proof status in all three documents.Minor

      The tracker records a current-head physical run at c69fa364…. That run executed 98 cases with one V97 settlement-fixture failure, and its fresh V98 coverage passed. Other passages still say that V98 is unrun or that the replacement physical run is pending. Readers get contradictory proof status.

      • design/project-management/implementation-tracking/player-access-and-session.md#L11-L11: Keep this line as the single source of the exact current-head counts and failures.
      • design/project-management/implementation-tracking/player-access-and-session.md#L37-L39: Replace "V98 disclosure persistence proof is unrun" and "V98 remains unexecuted" with the current-head result. Alternatively, mark the 7a statements as historical.
      • design/architecture/microservices/account-service/runtime-and-data.md#L13-L13: Remove "V98 and its disclosure persistence proof remain unrun", or update it to the current-head result. Then link to the tracker.
      • design/architecture/microservices/account-service/README.md#L9-L9: Replace "remains pending" with "executed with one failure (see tracker)", or keep only the link to the tracker.

      As per coding guidelines, keep the tracker's "status, implementation record, validation, gaps … sections aligned". As per path instructions, flag "conflicts between architecture docs".

      • Accepted Align secondary Account docs and later tracker paragraphs with actual c69 physical98cases/1fixture failure; preserve historical7a limitations and current repair proof distinction.
    6. Replace the nested decoder ladder with one ordered decoder list and a wrapping error.Trivial

      The four-level try/catch nesting repeats the same AccountSource mapping four times. It also throws the last decoder's exception (AccountSecurityStateAuthorityEventV1Codec) as the primary error for every account-source failure. As a result, a malformed password-reset carrier reports the generic security-state message "object must contain exactly the declared fields", and the useful diagnostic stays hidden in the suppressed exceptions. Throw one account source error that carries every decoder failure as a suppressed exception.

      ♻️ Proposed refactor

      -    AccountSource event;
      -    try {
      -      var verified = AccountAuthoritySourceEventV1Codec.verify(supplied.canonicalEventJson());
      -      ...
      -    }
      +    List<java.util.function.Function<String, AccountSource>> decoders =
      +        List.of(
      +            json -> {
      +              var verified = AccountAuthoritySourceEventV1Codec.verify(json);
      +              if (!(verified instanceof AccountAuthoritySourceEventV1Codec.AccountEvent a)) {
      +                throw invalid("account source", "must be an Account event");
      +              }
      +              return new AccountSource(a.eventId(), a.eventDigest(), a.canonicalJson(),
      +                  a.outboxStreamKey(), a.outboxSequence(), a.accountId(),
      +                  a.accountAuthorityGeneration(),
      +                  a.accountSecurityCutoff().accountAuthorityGeneration(),
      +                  a.accountSecurityCutoff().outboxStreamKey(),
      +                  a.accountSecurityCutoff().outboxSequence());
      +            },
      +            json -> { var r = PasswordResetAuthorityEventV1Codec.verify(json); return new AccountSource(/* same mapping */); },
      +            json -> { var l = AccountLogoutAllAuthorityEventV1Codec.verify(json); return new AccountSource(/* same mapping */); },
      +            json -> { var s = AccountSecurityStateAuthorityEventV1Codec.verify(json); return new AccountSource(/* same mapping */); });
      +    AccountSource event = null;
      +    IllegalArgumentException failure =
      +        invalid("account source", "matches no supported Account source schema");
      +    for (var decoder : decoders) {
      +      try {
      +        event = decoder.apply(supplied.canonicalEventJson());
      +        break;
      +      } catch (IllegalArgumentException schemaMismatch) {
      +        failure.addSuppressed(schemaMismatch);
      +      }
      +    }
      +    if (event == null) {
      +      throw failure;
      +    }
      
      • Accepted Replace nested codec ladder with ordered supported decoders and one account-source error retaining all decoder failures; preserve strict event mappings and validation.
  8. Hosted Review 3 CompletedRuntime 7m 13s
    Found: 4 Accepted: 0/3/1 Routed: 0
    1. Stop the read-only inspection paths from taking fence row locks before source locks.Minor

      readOperation always runs SELECT ... FOR UPDATE. The following methods reach it, or FOR UPDATE OF f, without calling lockSources first:

      • read
      • readSettlement
      • readOriginalBinding
      • readOwnerResult
      • readUnresolvedOperations

      The mutating paths lock source rows first and fence rows second:

      • reserve
      • claimCommitOrder
      • requestSourceChange
      • recordOwnerReadback
      • the V76 account_draft_authorization_owner_readback_guard

      The class Javadoc also requires sources before operations. The following sequence is feasible:

      1. A recovery transaction calls readUnresolvedOperations, which locks fence A.
      2. The same transaction calls recordOwnerReadback for A, which waits on source S.
      3. A concurrent requestSourceChange holds S and waits on fence A.

      PostgreSQL then aborts one transaction with 40P01. The readUnresolvedOperations Javadoc already says that consumers re-read settlement before they act. Discovery therefore needs no row lock.

      Use an unlocked read for these inspection paths. Keep FOR UPDATE only for paths that have already locked their sorted sources.

      Proposed fix

         public FenceSnapshot read(DraftAuthorizationFenceBinding binding) {
           requireTransaction();
      -    return snapshot(requireExact(readOperation(binding.operationId()), binding));
      +    return snapshot(requireExact(readOperationUnlocked(binding.operationId()), binding));
         }
       ...
      -    Record row = requireExact(readOperation(binding.operationId()), binding);
      +    Record row = requireExact(readOperationUnlocked(binding.operationId()), binding);
       ...
      -    sql += " ORDER BY f.reserved_at, f.operation_id LIMIT ? FOR UPDATE OF f";
      +    sql += " ORDER BY f.reserved_at, f.operation_id LIMIT ?";
       ...
      +  private Record readOperationUnlocked(UUID operation) {
      +    return dsl.fetchOne("SELECT * FROM " + FENCES + " WHERE operation_id = ?", operation);
      +  }
      

      Apply readOperationUnlocked in readOriginalBinding and readOwnerResult as well.

      Also applies to: 606-631, 641-669

      • Accepted Accepted: inspection/discovery must not acquire fence before source locks; use unlocked exact reads there only, retaining source-first locked mutations and deterministic independent-transaction proof.
    2. Add statement-level TRUNCATE guards to the remaining immutable evidence tables.Minor

      These migrations protect immutable evidence only with row-level UPDATE/DELETE triggers. A TRUNCATE bypasses those triggers. After a truncate, the insert guards accept a new "initial" state: a new INITIAL catalog, a second creator bootstrap for the same tenant, or a replayed presented token. V84, V90, V91 and V98 already guard TRUNCATE for equivalent tables.

      • services/account-service/src/main/resources/db/migration/V85__account_hosted_terms_acceptance_workflow.sql#L124-L129: add BEFORE TRUNCATE ... FOR EACH STATEMENT EXECUTE FUNCTION account_hosted_terms_immutable_guard() triggers on account_hosted_terms_catalog_versions, account_individual_hosted_terms_acceptances, account_hosted_terms_scopes and account_hosted_terms_publication_operations.
      • services/account-service/src/main/resources/db/migration/V83__account_tenant_creation_bootstrap.sql#L186-L188: add a BEFORE TRUNCATE statement trigger on account_tenant_creation_bootstrap_operations that uses account_tenant_creation_bootstrap_no_delete().
      • services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql#L87-L89: add a BEFORE TRUNCATE statement trigger on account_logout_all_operation_receipts that uses account_logout_all_operation_immutable_guard().

      📍 Affects 3 files

      • services/account-service/src/main/resources/db/migration/V85__account_hosted_terms_acceptance_workflow.sql#L124-L129 (this comment)
      • services/account-service/src/main/resources/db/migration/V83__account_tenant_creation_bootstrap.sql#L186-L188
      • services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql#L87-L89
      • Accepted Accepted; overlaps CLI5#6, with additional hosted-terms scope TRUNCATE guard. Existing immutable deny functions and physical preservation regression; no production activation.
    3. Use the shared AccountPostgresIntegrationFixture instead of a direct Docker Hub image.Trivial

      This test creates its own PostgreSQLContainer<>("postgres:16-alpine"). HostedTermsEnvironmentBindingFencePostgresIntegrationTest in this PR uses the shared AccountPostgresIntegrationFixture. According to the PR description, Account integration jobs already failed during Testcontainers image pulls (Docker Hub HTTP 429 and 504), and #3137 is fixing trusted registry access separately. A hard-coded image reference bypasses any registry or image pinning that the shared fixture applies. This test then stays exposed to the same pull failures after #3137 merges.

      Start the container through the shared fixture, and build each schema's DataSource with POSTGRES.dataSource(schema).

      • Accepted Accepted: reuse canonical AccountPostgresIntegrationFixture and per-schema DataSource; keep exact source/receipt proofs and Docker-unavailable behavior, remove bypass of trusted image selection.
    4. Update the proof-status prose after the c69fa36 run and the fb6ca4dd publication.Minor

      Root cause: Some proof statements were written before the c69fa36 physical run and were not updated afterward. That run executed 98 cases, and fresh V98 coverage and the V84 disclosure guards passed. The fixture correction is now published on head fb6ca4dd but has not been physically rerun. The documents now contradict each other about V98 and about which head is current.

      • design/project-management/implementation-tracking/player-access-and-session.md#L11-L11: Change the "current head c69fa36…" wording to name c69fa36 as the historical run. State that the corrected canonical-order fixture is published on fb6ca4dd and is not yet physically rerun. Do not say that the correction is only "prepared locally".
      • design/project-management/implementation-tracking/player-access-and-session.md#L37-L39: Replace "V98 disclosure persistence proof is unrun" and "V98 remains unexecuted". State that fresh V98 coverage passed at c69fa36, and that the Game Logic canonical-order fixture failed there and has no rerun yet.
      • design/architecture/microservices/account-service/runtime-and-data.md#L11-L13: Replace "V98 and its disclosure persistence proof remain unrun" with the same c69fa36 result. Keep the link to the tracker for the exact counts.

      As per path instructions: "Review docs for canonical-current-state consistency." As per coding guidelines: "Keep its status, implementation record, validation, gaps, decisions, and service-map sections aligned".

      📍 Affects 2 files

      • design/project-management/implementation-tracking/player-access-and-session.md#L11-L11 (this comment)
      • design/project-management/implementation-tracking/player-access-and-session.md#L37-L39
      • design/architecture/microservices/account-service/runtime-and-data.md#L11-L13
      • Accepted Accepted; same current-PR documentation obligation as CLI5#3. Align historical c69 versus published fixture and actual physical fb6 Account job success, retain whole-gate and activation limits.
  9. CLI Review 6 CompletedRuntime 3m 29s
    Found: 4 Accepted: 1/1/1 Routed: 0
    1. A missing sources array passes the reservation completeness check.Minor

      If source_payload has no sources key, vector is SQL NULL. Both jsonb_array_length(vector) < 1 and <> (SELECT count(*) ...) then evaluate to NULL, so the IF does not raise. The following FOR loop over jsonb_array_elements_text(NULL) runs zero times. The reservation commits with zero participating sources.

      A reservation with no rows in account_game_logic_intake_source_read_sources fences no source key. The preliminary source read then has no serialization effect.

      V91 and V95 guard the same input with IS DISTINCT FROM, and publicationCompletenessRejectsMissingJsonValues... covers V91. Make the V97 check fail closed in the same way.

      🛡️ Proposed fix

           vector := convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources';
      -    IF jsonb_array_length(vector) < 1 OR jsonb_array_length(vector) <>
      -        (SELECT count(*) FROM account_game_logic_intake_source_read_sources WHERE operation_id = NEW.operation_id) THEN
      +    IF jsonb_typeof(vector) IS DISTINCT FROM 'array' OR jsonb_array_length(vector) < 1
      +        OR jsonb_array_length(vector) IS DISTINCT FROM
      +        (SELECT count(*)::INTEGER FROM account_game_logic_intake_source_read_sources WHERE operation_id = NEW.operation_id) THEN
      
      • Accepted Fail closed in V97 on missing/null/non-array source vectors and mismatched or zero participation; add negative and existing positive PostgreSQL regression.
    2. Verify that the transaction actually starts, so the ordering assertion cannot pass vacuously.Trivial

      The ordering check runs only inside the getTransaction stub. Suppose completePasswordReset rejects the invalid token without calling transactionManager.getTransaction(...). Two examples are a pre-transaction token lookup or a declarative transaction boundary. In that case the stub never runs. The test then passes on candidateVerifierPrepared alone. Hashing before the transaction is never checked.

      Add an explicit verify of getTransaction after the assertThrows. A regression that moves hashing inside the transaction or removes the transaction then fails this test.

      ♻️ Proposed change

           }
       
           assertTrue(candidateVerifierPrepared.get());
      +    org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.atLeastOnce())
      +        .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class));
         }
      
      • Accepted Implement explicit transaction-start verification so verifier-before-transaction regression cannot pass vacuously.
    3. Zero-row region or spawn inventories always fail settlement.Major

      jsonb_agg returns SQL NULL for an empty input set. If regionGeneratorInputs or spawnBindingInputs is [], the expression becomes NULL IS DISTINCT FROM '[]'::JSONB. That expression evaluates to TRUE, so the guard raises 'Inventory differs from exact original selected Account, APPLIED graph or freeze'.

      The function explicitly accepts a zero count for these families:

      • Line 126 accepts spawnBindingCount matching ^(0|[1-9][0-9]*)$.
      • Line 139 requires only counts[3] >= 1 (ROOM).

      As a result, a valid publication with no spawn bindings (or no region generator inputs) cannot insert its settlement. V93's account_selected_publication_is_settled then stays false. account_control_ui_hold_required_sources keeps raising 55P03 for every source writer on those keys. Wrap both aggregates in COALESCE(..., '[]'::JSONB).

      🐛 Proposed fix

      -        OR (SELECT jsonb_agg(entry ORDER BY entry->>'regionTemplateId') FROM
      -            jsonb_array_elements(model->'regionGeneratorInputs') entry)
      -            IS DISTINCT FROM model->'regionGeneratorInputs'
      +        OR (SELECT COALESCE(jsonb_agg(entry ORDER BY entry->>'regionTemplateId'), '[]'::JSONB) FROM
      +            jsonb_array_elements(model->'regionGeneratorInputs') entry)
      +            IS DISTINCT FROM model->'regionGeneratorInputs'
      @@
      -        OR (SELECT jsonb_agg(entry ORDER BY entry->>'bindingTemplateId') FROM
      -            jsonb_array_elements(model->'spawnBindingInputs') entry)
      -            IS DISTINCT FROM model->'spawnBindingInputs'
      +        OR (SELECT COALESCE(jsonb_agg(entry ORDER BY entry->>'bindingTemplateId'), '[]'::JSONB) FROM
      +            jsonb_array_elements(model->'spawnBindingInputs') entry)
      +            IS DISTINCT FROM model->'spawnBindingInputs'
      

      Also applies to: 287-289

      • Accepted Fix V94 empty optional region/spawn aggregate NULL versus [] mismatch; prove valid empty inventories settle while malformed/count-mismatched cases remain denied.
    4. Full-history verification now runs on every Account source read.Trivial

      verifyEventHistory reads and verifies every event from sequence 1 on each readCurrentSource call for an Account scope. For each closed event it also queries receipts. For each security-state event, findCommittedByRequestIdShared runs nested readbacks, and AccountAuthoritySourceEventReadback.requireRetainedEvent loads that operation twice (Line 212-227 and again in requireSecurityStateReceipt).

      readCurrentIssuerAccountSources scans the history twice, once here and once in requireCurrentLatest. recordAccountUpdate and advanceClosedAccountHead also run several reads. Cost and lock hold time grow with every reset, logout-all and security change on the Account.

      Consider one of these options:

      • Store a verified-history watermark (sequence plus digest) in account_authority_source_records, and verify only events after it.
      • Verify the history once per transaction and pass the result to later reads.

      Add an oldest-history or source-read-latency metric before a LOGIN path depends on this read.

      • Rejected Repeated unmeasured history-cache/watermark proposal; immutable retained provenance is deliberately reverified. Per-invocation object reuse already fixed; transaction memoization risks hiding in-transaction source changes. No measured LOGIN latency defect.

Routed Findings

0 Open0 Accepted/Fixed0 Rejected

No routes recorded

Unlinked items

no items unlinked