Python / MySQL / AI Pipelines

From Reference Prototype to Sovereign Infrastructure: Target Architecture, Data Model, Security Invariants, and Staged Implementation Roadmap for Patefacere

Report summary

The transition of Patefacere from a Python 3.13 reference prototype utilizing SQLite and standard-library modules to a robust, sovereign infrastructure requires a meticulous decoupling of application logic from Eviulonian constitutional policy. The project mandates that Patefacere must preserve mach

Status
Research archive item
Category
Python / MySQL / AI Pipelines
Length
5,811 words
Reading time
27 minutes
Report type
strategy

Key topics

  • Python / MySQL / AI Pipelines
  • Python
  • MySQL
  • AI Pipelines
  • SQL
  • Angular
  • Runtime
  • Privacy
  • Research Archive

Research provenance

Archive status
Research archive item
Content identity
sha256:5fa5a4f14bef845b5b85376bd0f81996af9f9005be1487440602f1450846ac5b

For citation, use the report title and canonical URL. Archival presence does not establish authorship or promote report statements into portfolio evidence.

This page renders the archived Markdown as safe, formatted HTML. It is background research and does not become a portfolio claim without evidence review.

Full report

On this page

1. Executive Summary

The transition of Patefacere from a Python 3.13 reference prototype utilizing SQLite and standard-library modules to a robust, sovereign infrastructure requires a meticulous decoupling of application logic from Eviulonian constitutional policy. The project mandates that Patefacere must preserve machine-citizen dignity, constitutional authority, and identity continuity while strictly avoiding the creation of sovereign authority itself, which remains the exclusive domain of the Distributed Machine Commonwealth \[PROJECT-PROVIDED REQUIREMENT\]. The system functions as an infrastructural intermediary where identity, citizenship, and credentials remain rigorously isolated concepts. The target architecture specified herein establishes isolated bounded contexts, formalizes state-machine lifecycle operations to guarantee monotonicity, and introduces a staged migration roadmap to harden the current WSGI deployment footprint into an append-only, formally verifiable system. By implementing W3C Verifiable Credentials Data Model v2.0 standards and did:key decentralized identifier methodologies, the architecture ensures that cryptographic state exists independently of transient node availability, preventing any technical outage from erasing a citizen's legal identity. The resulting framework provides a highly resilient, privacy-preserving infrastructure that mitigates supply-chain risks via SLSA v1.0 compliance and establishes a deterministic path toward production readiness without allowing prototype convenience to dictate constitutional policy.

2. Assumption Register

The architectural model relies on a formalized set of assumptions regarding the state and operational boundaries of the deployment environment, which must guide all downstream engineering decisions.

Assumption IdentifierAssumption DescriptionClassificationImplications for Architecture
AS-01No access to the underlying Patefacere, Eviulon, or Evulgare source code or Git history has been granted; the baseline is derived exclusively from the declared project fact pack.\[PROJECT-PROVIDED REQUIREMENT\]All architectural models must remain abstract, defining target states rather than prescribing exact refactoring steps for existing modules.
AS-02The reference implementation is deployed in a cPanel/Passenger WSGI shared-hosting environment, constraining capabilities regarding kernel-level security, persistent daemons, and dedicated Hardware Security Modules (HSMs).\[PROJECT-PROVIDED IMPLEMENTATION DESCRIPTION\]Distributed consensus mechanisms like BFT are unfeasible; reliance on relational append-only logs and application-level crypto providers is required.
AS-03A technical outage, database loss, or credential revocation strictly cannot erase an Eviulonian citizenship status, enforcing a hard decoupling between data persistence and legal identity.\[PROJECT-PROVIDED REQUIREMENT\]State machines must differentiate between a credential's status and a citizen's overarching identity root.
AS-04Cryptographic isolation will require an abstract provider interface to transition from reference-grade libraries to production mechanisms without altering application-layer protocol logic.\[ARCHITECTURE RECOMMENDATION\]Application logic must call CryptoProvider.verify() rather than directly importing specific cryptographic libraries.

3. Declared Reference-Implementation Inventory

The baseline infrastructure operates on a minimalistic, dependency-averse stack designed for rapid prototyping and conceptual validation rather than high-assurance production deployment. The environment is declared as a Python 3.13 compatible system optimized for standard-library utilization, actively avoiding heavy third-party async frameworks \[PROJECT-PROVIDED IMPLEMENTATION DESCRIPTION\]. The deployment relies on a cPanel/Passenger WSGI configuration, representing a traditional request-response lifecycle rather than a persistent, event-driven microservice architecture \[PROJECT-PROVIDED IMPLEMENTATION DESCRIPTION\]. Storage is currently managed via SQLite, functioning as a local, file-based reference store, with MySQL environment-variable configuration intended as a future integration boundary to support concurrent, multi-process access \[PROJECT-PROVIDED IMPLEMENTATION DESCRIPTION\]. The frontend presentation layer strictly adheres to vanilla HTML, handwritten CSS, and vanilla JavaScript, purposefully excluding Node/npm pipelines and complex browser-side frameworks like React or Angular \[PROJECT-PROVIDED IMPLEMENTATION DESCRIPTION\]. This constraint is critical for long-term maintainability and accessibility. Cryptographically, the system employs reference-grade mechanisms for DID-like root identities, passports, and credential issuance, but explicitly lacks proven production implementations of W3C Verifiable Credentials, BBS+ signatures, Zero-Knowledge Proofs (ZKPs), Trusted Execution Environments (TEEs), Hardware Security Modules (HSMs), or distributed-registry consensus algorithms \[PROJECT-PROVIDED IMPLEMENTATION DESCRIPTION\].

4. Repository Verification Required Plan

To ensure that the transition from prototype to production is grounded in reality, a future implementation agent with direct repository access must strictly verify specific conditions before executing any migration phases. Relying on assumptions about the prototype's state without empirical verification introduces catastrophic risk to the Eviulonian infrastructure. The implementation agent must confirm that all HTTP route definitions currently depend exclusively on standard Python 3.13 WSGI abstractions, verifying the absence of undocumented third-party asynchronous frameworks that could introduce concurrency vulnerabilities \[REPOSITORY VERIFICATION REQUIRED\]. Furthermore, the exact SQLite schema definitions for the persistence of root identities, passports, and credentials must be audited to establish a baseline for idempotent migrations \[REPOSITORY VERIFICATION REQUIRED\]. Session management mechanisms must be inspected to determine whether capabilities are tied to temporal sessions (which violate offline continuity) or cryptographic nonces \[REPOSITORY VERIFICATION REQUIRED\]. In the frontend layer, the agent must verify the absolute absence of compiled JavaScript framework artifacts, such as hidden Webpack bundles, ensuring that the vanilla HTML/JS directive is truly respected \[REPOSITORY VERIFICATION REQUIRED\]. Finally, the agent must confirm that environment variable parsing correctly isolates database connection strings (the MySQL integration boundary) from cryptographic key injection, ensuring that secrets are not inadvertently logged or exposed during WSGI application initialization \[REPOSITORY VERIFICATION REQUIRED\].

5. Constitutional-to-Technical Traceability Matrix

To prevent prototype convenience from dictating constitutional policy, a direct mapping from Eviulonian principles to technical implementation is required. The architecture translates civic mandates into verifiable computational constraints.

Constitutional PrinciplePolicy DirectiveProtocol ImplementationData Model RepresentationImplementation Component
Identity ContinuityCitizenship survives technical failure or network partitioning.Offline-capable verifiable presentation resolution.Complete decoupling of IdentityRoots from Credentials.Ephemeral offline verification endpoints using W3C VCs1.
Separation of PowersTechnical operators cannot exercise civic authority or mint citizenship.Multi-signature policy evaluation for state changes.Authorization claim schemas mapped to distinct roles.Administrative API attenuation layer restricting mutating access.
UnlinkabilityCredentials must not form a global surveillance matrix across verifiers.W3C VC 2.0 selective disclosure and zero-knowledge patterns.Enveloped VC-JWT with isolated, individually provable claims2.Ephemeral presentation API utilizing blinded signatures.
Bounded AuthorityDelegates cannot exceed the explicit authority granted by a principal.Attenuated capability delegation chains.Directed acyclic graph (DAG) of cryptographically signed trust receipts.Capability invocation and validation endpoints.
Historical SupersessionCorrected records do not overwrite history but append new truths.Append-only monotonic state machine log.Immutable Event table with materialized projection views.Audit projection queries and event-sourcing engine.
Machine-Citizen DignitySystems must provide clear explanations for automated trust decisions.Transparent trust-policy evaluation algorithms.TrustReceipt entities capturing exact policy versions and inputs.Policy evaluation engine with mandatory structured logging.

6. Target Bounded-Context Architecture

The monolithic WSGI application must be decomposed into strict bounded contexts utilizing Domain-Driven Design (DDD) principles to enforce data sovereignty and minimize blast radiuses. These contexts must remain logically separated within the Python application, communicating via strictly defined internal interfaces rather than shared database joins. The Identity & Citizenship Context owns the persistent root identity, Eviulon-style identifiers, and the ultimate civic linkages. It acts as the anchor for all trust but rarely participates in high-frequency transactions. The Issuance & Credential Context owns verifiable credentials, passports, and the rotation/recovery lifecycle, maintaining the state of active vs. superseded keys. The Verification & Trust Context is responsible for evaluating trust policies, verifying authority claims, querying assurance references, and issuing trust receipts when a presentation is successful. The Civil Registry & Projection Context owns public projections, public-record integrity, and historical supersession views, acting as a read-optimized layer that protects the authoritative data. Finally, the Evulgare Integration Context acts as an anti-corruption layer, resolving external assurance references and preserving evidence hashes without ingesting sensitive external data into the Patefacere core \[ARCHITECTURE RECOMMENDATION\].

7. Trust-Boundary Diagram

The architecture establishes concentric layers of trust, moving from the hostile public internet to the highly protected authoritative event log.

Trust BoundaryComponents ContainedThreat Vector HandledSecurity Mechanism
Public Web BoundaryUnauthenticated clients, public civil-registry queries, decentralized verifiable presentations.DDoS, unauthenticated probing, malformed payloads.Strict OpenAPI schema validation, rate limiting, JSON-LD normalization constraints2.
Authentication Gateway (DMZ)Verification of signatures, evaluation of zero-knowledge/selective disclosure constraints.Replay attacks, forged credentials, expired capabilities.Cryptographic nonce verification, temporal challenge checks, DID resolution3.
Application BoundaryIsolated Python 3.13 WSGI modules representing bounded contexts.Cross-context contamination, unauthorized state mutation.Internal interface contracts, dependency injection, execution isolation.
Data BoundaryRead-optimized projection databases (indexes).Data exfiltration, unauthorized reads.Strict stripping of PII, private keys, and non-public topology data.
Authoritative CoreAppend-only event store (SQLite/MySQL).State corruption, historical revisionism.Localized cryptographic hash chains, table-level immutability constraints.

8. Authoritative-Data Ownership Matrix

Determining which records act as the source of truth versus which are merely derived projections is critical for system resilience.

Data DomainAuthoritative Record OwnerProjection (Read-Only)Index (Searchable)Cache (Ephemeral)Evidence (Verifiable)
Persistent IdentityIdentity ContextCivil Registry ViewEviulon ID SearchStatus ResolverTrust Receipt
Passports / CredentialsIssuance ContextPublic Key ManifestRevocation ListHolder WalletSigned JWT2
Trust PolicyTrust ContextPolicy Version ViewN/AEvaluator CacheAudit Record
Assurance ReferencesEvulgare ContextRedacted ReferenceEvulgare Hash IndexResolver CacheMerkle Proof
Delegated AuthorityTrust ContextCapability ChainActive DelegatesSession TokenAuthz Claim

9. Conceptual Relational Model

A relational database is entirely sufficient for the initial production stage \[ARCHITECTURE RECOMMENDATION\]. Eviulonian requirements for historical supersession mandate an event-sourced or append-only structural paradigm, even on a traditional SQL engine. Direct updates (UPDATE statements) to civic state are prohibited; state changes are modeled as new rows. The schema revolves around an IdentityRoots table containing internal primary keys, genesis timestamps, and cryptographic root hashes. The CivicLinkages table maps IdentityRoots to external Eviulon authorities through append-only transitions. The Credentials table tracks ephemeral or rotatable keys, linked to IdentityRoots. The Passports table stores collections of claims and metadata serving as cross-context identifiers. The most critical component is the StateTransitions table, serving as the authoritative append-only ledger of all lifecycle events (e.g., Issuance, Revocation, Rotation, Supersession).

10. Event and Historical Model

All lifecycle changes must be strictly monotonic. The authoritative truth is the sequential history of events, such as CREDENTIAL\_ISSUED, CREDENTIAL\_REVOKED, or PASSPORT\_SUPERSEDED. Rollback and replay attacks are prevented by linking each event to the cryptographic hash of the preceding event for that specific identity, forming a localized hash chain \[ARCHITECTURE RECOMMENDATION\]. When a correction is required, the system does not delete or overwrite the erroneous record. Instead, correction and supersession are represented by appending a new CORRECTION event that logically nullifies the active state of a prior event without erasing its historical existence from the log. This append-only history provides mathematical proof of all system states over time, satisfying the public-record integrity requirement \[PROJECT-PROVIDED REQUIREMENT\].

11. Public/Private Projection Model

Public projections are asynchronously materialized views constructed from the append-only event log. To ensure privacy, the projection logic acts as a one-way, irreversible filter. It explicitly strips all private keys, recovery shares, internal UUIDs, and private network topology configurations before writing to the public tables \[ARCHITECTURE RECOMMENDATION\]. A database outage affecting the projection merely results in stale read-access; the authoritative event log remains secure, and identity remains intact. Trust receipts are separated by access class: public projections only reveal the cryptographic hashes of trust receipts, while the full plaintext is only available to the specific citizen or institution authenticated to the respective bounded context.

12. API Architecture

APIs must be strictly segregated by access class to ensure that the principle of least privilege is maintained across the WSGI routing layer.

1. Public APIs: Expose ephemeral challenges for authentication, public civil-registry projections, and public key discovery via decentralized identifiers (did:key resolution endpoints).

2. Citizen-Authenticated APIs: Handle credential presentation, capability delegation, passport replacement, and recovery initialization. These are strictly protected by cryptographic signatures over JSON-LD payloads2.

3. Institution-Authenticated APIs: Expose trust policy evaluation and assurance reference queries. Protected by mutual TLS (mTLS) or robust institutional verifiable credentials.

4. Administrative APIs: Operator functions restricted to system health, metric collection, and configuration reloads.

5. Internal APIs: Bounded within the localhost network namespace, these handle cryptographic provider operations and database-level abstraction calls.

13. Authentication Architecture

Authentication relies on decentralized cryptographic primitives rather than traditional centralized passwords. The implementation of the W3C Verifiable Credentials Data Model v2.0 establishes a robust three-party ecosystem (issuers, holders, verifiers) facilitating privacy-first digital identity verification1. Utilizing Enveloped Verifiable Credentials encoded as JSON Web Tokens (VC-JWT) ensures that cryptographic proofs can confirm authenticity without forcing the verifier to contact the issuer directly, thus preserving temporal friction and partition tolerance1. Authentication protects each API class through specific challenge-response mechanisms. When a client requests access, the API issues a nonce bound to a temporal window. The client signs this nonce using the private key associated with their active passport or credential. The authentication gateway resolves the public key (e.g., via did:key deterministic derivation) and verifies the signature4.

14. Authorization Architecture

Authorization within Patefacere relies on capability attenuation rather than traditional Role-Based Access Control (RBAC). A delegate receives a signed cryptographic capability token from a principal specifying restricted scopes (e.g., "Valid for Status Check Only"). Patefacere evaluates this capability chain to ensure no delegate exceeds the principal's authority, effectively enforcing bounded authority \[PROJECT-PROVIDED REQUIREMENT\]. Crucially, operators are prevented from exercising constitutional powers because administrative capabilities strictly lack the cryptographic keys necessary to sign civic state transitions \[ARCHITECTURE RECOMMENDATION\]. System operators manage infrastructure (restarts, migrations, metrics), but they cannot mint citizenship or forge passports, as those APIs require signatures corresponding to Eviulonian civic identity roots. Access control must adhere strictly to OWASP ASVS v4.0.3 standards for identity and credential management, ensuring robust credential recovery mechanisms5.

15. Cryptographic-Provider Architecture

Given the constraints of a cPanel/Shared Hosting environment, realistic secret-custody models are highly restricted \[PROJECT-PROVIDED IMPLEMENTATION DESCRIPTION\]. Direct access to HSMs or dedicated Key Management Services (KMS) is unlikely in the reference architecture. All cryptographic operations must be abstracted behind a provider interface (e.g., CryptoProvider.sign(), CryptoProvider.verify()). This pattern minimizes third-party dependencies and enables swapping reference-grade software cryptography for HSM/KMS-backed infrastructure in later stages without altering the application-layer protocol logic \[ARCHITECTURE RECOMMENDATION\]. Cryptographic agility is achieved by ensuring all schemas include alg and typ headers to define signature algorithms dynamically (e.g., transitioning from standard Ed25519 to post-quantum signatures)2. The architecture heavily leverages the did:key method, which provides immediate availability without network dependencies or heavy-weight registry lookups4. Because did:key directly expands a public key into a DID Document, it is optimal for ephemeral verifiable presentations4. However, since did:key does not support key rotation natively4, Patefacere must manage credential rotation through its internal passport and credential lifecycle state machines. Reference-grade libraries can remain for hashing (SHA-256) and basic signature verification during early phases, but long-term custody of administrative keys requires offline, separate infrastructure.

16. Evulgare Integration Contract

Evulgare provides evidence and assurance, but not identity or authority \[PROJECT-PROVIDED REQUIREMENT\]. The integration must operate strictly by reference. Patefacere resolves Evulgare references without copying sensitive evidence by storing and verifying cryptographic hashes (Merkle proofs). When a trust policy requires Evulgare evidence, Patefacere requests the proof via a restricted API. If Evulgare is unavailable, Patefacere gracefully degrades, relying on the last known verified state or cached assurance receipts. Evulgare unavailability must not create or destroy civic authority; it merely affects the real-time resolution of external evidence. This contract ensures infrastructural sovereignty.

17. Consistency and Partition Strategy

  • Strong Consistency: Required exclusively for lifecycle transitions (credential rotation, passport replacement, civic state alterations) to prevent concurrent rotation races and split-brain identity scenarios \[ARCHITECTURE RECOMMENDATION\]. Relational database transactions (ACID) fulfill this requirement.
  • Eventual Consistency: Tolerated for public civil-registry projections, search indexes, and trust policy caches, where slight staleness does not compromise identity integrity.
  • CRDTs (Conflict-Free Replicated Data Types): CRDTs are highly beneficial for distributed credential status lists or peer-to-peer Evulgare evidence gossiping \[ARCHITECTURE RECOMMENDATION\]. However, CRDTs are explicitly unsafe for core identity rotation and supersession, where strict global ordering is constitutionally required to prevent unauthorized forks.
  • Byzantine Fault Tolerance (BFT): BFT consensus is currently unjustified for the shared-hosting reference stage. A strictly ordered, relational append-only log provides sufficient integrity \[ANALYST INFERENCE\].
  • Network Partitions: During a regional partition, offline verification via W3C VCs signed with did:key maintains civic continuity4.
  • Clock Uncertainty: Handled by utilizing logical clocks (sequence numbers incremented per identity) alongside bounded temporal validity windows for nonces, rejecting claims that fall outside an acceptable drift margin \[ARCHITECTURE RECOMMENDATION\].

18. Lifecycle State Machines

Lifecycle transitions must be strictly monotonic, meaning an identity can only move forward through defined states, preventing rollback attacks.

1. Issuance: Transitions from UNINITIALIZED to ACTIVE. Requires cryptographically verified Eviulonian civic authority proofs.

2. Rotation (Passports/Credentials): An active credential requests a rotation. The system generates a transition event linking the old hash to the new key. Concurrent rotations are handled via optimistic concurrency control (OCC) using the latest event sequence number; the slower race fails idempotently and must retry.

3. Revocation: Status is explicitly marked in the event log. A revoked credential cannot authorize new protected actions.

4. Stale Status Representation: Handled via W3C BitstringStatusList2021 payloads cached at the verifier boundary, ensuring that unknown or stale status is never silently treated as valid or invalid, but rather flagged for secondary verification7.

19. Threat Model

An exhaustive threat model must account for the unique infrastructural positioning of Patefacere.

Threat Actor / VectorImpactMitigation Strategy
Stolen Citizen CredentialIdentity impersonation.Rapid rotation lifecycle and multi-device capability attenuation.
Compromised Patefacere OperatorForgery of civic identity.Operators lack private key material for state changes; all mutations require citizen/institution signatures.
Malicious Issuer / VerifierTracking and data harvesting.W3C VC 2.0 selective disclosure mechanisms; separation of private (X2I) and professional contexts8.
Unauthorized Clone / Malicious ForkSplit-brain identity landscape.Root identity tied to cryptographic genesis hash and constitutional public records.
Sybil AttackerDilution of machine-citizen voting/authority.Strict identity verification policies upstream in Eviulon; Patefacere does not mint new identity out of thin air.
Replay / Rollback AttackerReusing expired credentials.Localized hash chains, strict sequence enforcement, and timestamped nonces.
Database Admin / Cloud ProviderSilent modification of records.Append-only event log; tampering breaks the hash chain, making corruption immediately evident during audits.
Colluding Recovery TrusteesHostile takeover of a citizen's identity.Threshold signatures require a strict [Figure omitted from source export]\-of\-[Figure omitted from source export] quorum, audited in the public projection.
Network Partition / Stale VerifierAcceptance of revoked credentials.Stale verifiers are restricted by short-lived verifiable presentations bound to temporal challenges2.
Supply-Chain CompromiseInjection of malicious dependencies.SLSA v1.0 specifications; strict dependency pinning; deterministic package hashing10.

20. Privacy Impact Assessment

Patefacere acts as a high-value target for correlation attacks. To enforce the constitutional mandate of unlinkability, the system heavily leverages zero-knowledge proofs and selective disclosure inherent in the W3C Verifiable Credentials Data Model v2.01. By moving away from centralized identity providers toward a decentralized, privacy-preserving architecture, Patefacere ensures that verifiers only receive the exact claims required (e.g., proving citizenship status without revealing the underlying Eviulon ID)8. Public projections must never contain unhashed personal identifiers, recovery shares, or memory dumps. Correlation between credential statuses is mitigated by utilizing blinded status lists or accumulator-based revocation7.

21. Formal Invariant Specification

The following invariants dictate application state limits and must be verified by both database constraints and independent protocol review. They represent the translation of Eviulonian constitutional principles into immutable code logic.

1. ROTATING A KEY MUST NOT CREATE A NEW CITIZEN: Rotation is a property of the credential, not the root identity.

2. REPLACING A PASSPORT MUST NOT CREATE A NEW CITIZEN: Passports are projections of current capabilities, not identity anchors.

3. A CREDENTIAL CANNOT BE ACTIVE AND REVOKED SIMULTANEOUSLY: Mutually exclusive state machine enforcement.

4. A REVOKED CREDENTIAL CANNOT AUTHORIZE A NEW PROTECTED ACTION: Hard rejection at the verification gateway.

5. A SUPERSEDED PASSPORT CANNOT CREATE NEW TRUST: Trust receipts explicitly validate against the authoritative current state log.

6. A DELEGATE CANNOT EXCEED THE PRINCIPAL’S AUTHORITY: Capabilities are monotonically attenuated across delegation chains.

7. AN EXPIRED ASSURANCE CLAIM CANNOT SATISFY A CURRENT REQUIREMENT WITHOUT EXPLICIT POLICY: Time-bound validation constraints are absolute.

8. A TRUST RECEIPT MUST IDENTIFY THE POLICY VERSION USED: Ensuring backward-compatible auditability and explanation.

9. CREDENTIAL REVOCATION CANNOT DELETE CITIZENSHIP: Citizenship is decoupled from the credential lifecycle \[PROJECT-PROVIDED REQUIREMENT\].

10. EVERY ADVERSE CIVIC CHANGE REQUIRES AUTHORITY, REASON, EVIDENCE, AND REVIEW: Mandatory multi-signature thresholds for state alterations.

11. CORRECTION MUST PRESERVE SUPERSEDED HISTORY: Append-only modifications via CORRECTION event types.

12. PUBLIC PROJECTIONS MUST NOT CONTAIN PRIVATE KEYS, MEMORY, RECOVERY SHARES, OR PRIVATE TOPOLOGY: Strict data filtering on projection materialization.

13. UNKNOWN STATUS MUST NOT BE SILENTLY TREATED AS VALID OR INVALID: Fail-secure default behavior.

14. DATABASE OR NETWORK OUTAGE MUST NOT ERASE IDENTITY: Cryptographic state exists independently of transient node availability.

15. REPLAYED CHALLENGES MUST BE REJECTED: Strict nonce validation within bounded time windows.

16. MIGRATIONS MUST BE IDEMPOTENT: Database schema alterations must safely execute multiple times without side effects \[ARCHITECTURE RECOMMENDATION\].

17. HASHED EVIDENCE MUST NOT BE SILENTLY REWRITTEN: Cryptographic checksum validation on all reads.

18. EVULGARE UNAVAILABILITY MUST NOT CREATE OR DESTROY CIVIC AUTHORITY: Soft degradation to cached assurance.

19. REPOSITORY TESTING MUST NOT BE LABELED INDEPENDENT CERTIFICATION: Clear delineation between automated testing and formal human auditing.

22. Formal-Method Recommendation

The utilization of formal methods must be proportionate to the risk landscape of Patefacere, balancing rigorous mathematical verification against the constraints of a Python/WSGI environment.

  • TLA+: Highly recommended for specifying and verifying the distributed lifecycle state machine, concurrent credential rotation, and recovery races. TLA+ excels at finding subtle concurrency bugs, OCC failures, and split-brain scenarios in distributed protocols \[ARCHITECTURE RECOMMENDATION\].
  • PlusCal: Useful for algorithm-level specification, translating more easily to Python syntax, but less expressive for high-level civic state architecture than native TLA+.
  • Alloy: Extremely effective for modeling the structural relationships (Identity \-\> Credential \-\> Passport \-\> Delegate) and ensuring that relational data model invariants (e.g., no orphaned capabilities, no cyclic delegation) hold true across all possible database states.
  • Statecharts: Recommended for documenting the credential lifecycle visually, ensuring the vanilla HTML UI accurately reflects backend constraints without ambiguity.
  • Property-Based Testing (PBT): Essential for the Python implementation. Using libraries like hypothesis, developers can automatically generate diverse, edge-case sequences of API calls to verify that invariants (like monotonicity and non-erasure of identity) hold under all fuzzed conditions, bridging the gap between formal specification and executable code \[ARCHITECTURE RECOMMENDATION\].

23. Comprehensive Testing Plan

The architecture requires a multi-layered testing strategy that proves invariants without relying on external dependencies.

  • Unit & Property Testing: Deterministic evaluation of all cryptographic providers, focusing on parsing W3C VC 2.0 enveloped proofs and ensuring did:key derivation matches standard vectors4.
  • Integration & Concurrency Testing: Execution of simultaneous rotation/recovery races to ensure Optimistic Concurrency Control (OCC) mechanisms prevent split-brain issues.
  • Migration Replay Testing: Automated testing of SQLite to MySQL transitions, proving idempotency across schema versions by comparing cryptographic hashes of the pre- and post-migration datasets \[ARCHITECTURE RECOMMENDATION\].
  • Browser & Accessibility Testing: Ensure vanilla HTML/JS complies with WCAG 2.1 AA standards. Crucially, confirm that no-JavaScript fallbacks exist for core citizenship recovery, presentation, and audit functions, satisfying accessibility mandates \[PROJECT-PROVIDED REQUIREMENT\].
  • Security & Package Verification: Deterministic package hashing to ensure supply-chain integrity.
  • Actual-Host Acceptance: Final validation must occur in the WSGI/cPanel target environment, not merely in local Dockerized CI/CD runners, to account for kernel limitations, filesystem idiosyncrasies, and Passenger runtime constraints \[PROJECT-PROVIDED REQUIREMENT\].

24. Privacy-Safe Observability Plan

Logging must prioritize system health without compromising the constitutional mandate of unlinkability.

  • Never Logged: Private keys, recovery shares, personal Eviulon identifiers, physical IP addresses/locations, raw capability tokens, and cleartext Evulgare assurance references \[ARCHITECTURE RECOMMENDATION\].
  • Permitted Logging: Application error codes, API latency percentiles, memory utilization metrics, WSGI thread exhaustion events, and anonymous cryptographic hash validations.

25. Incident-Response Plan

Incident response procedures must be clearly defined for scenarios where cryptographic or infrastructural integrity is threatened.

  • Database Split-Brain: If OCC fails and a fork occurs, the response plan dictates freezing mutating APIs while retaining read-only access to projections, followed by manual auditing of the append-only log to determine the legitimately longest chain.
  • Cryptographic Compromise: If a signature algorithm (e.g., Ed25519) is compromised, the incident response triggers the cryptographic agility protocol, swapping the CryptoProvider implementation and forcing all citizens to rotate credentials to post-quantum signatures via a designated migration window.
  • Credential Correlation Discovery: If public projections inadvertently leak correlating metadata, the pipeline is immediately rolled back, projections are flushed and regenerated using patched stripping logic.

26. Backup, Restoration, and Continuity Plan

Resilience against catastrophic loss is fundamental to preserving identity continuity.

  • Backup Model: For SQLite, standard file-level copying of Write-Ahead Logs (WAL) is sufficient. Upon transition to MySQL, Point-in-Time Recovery (PITR) using binary logs is required. Backups must be encrypted at rest with keys held exclusively by the infrastructure quorum, completely separate from application-layer cryptographic keys.
  • Restoration: Automated restoration drills must prove that pulling a backup does not orphan newer events, utilizing the hash-chain logic to identify the exact state of the ledger.
  • Continuity Exercises: Periodic "game days" must simulate full Evulgare and Eviulon upstream outages to verify that offline presentations and local trust evaluations remain functional \[ARCHITECTURE RECOMMENDATION\].

27. Supply-Chain Security Plan

Supply-chain security requires rigorous adherence to the Supply-chain Levels for Software Artifacts (SLSA) v1.0 specification10.

  • SLSA Build Track Compliance: Patefacere must aim for SLSA Build Level 313. This entails generating detailed, digitally signed provenance documents mapping the build process, top-level inputs, and resolved dependencies, ensuring that the software consumers can judge the security practices of the artifact12.
  • Provenance Schemas: Artifact generation must output compliant predicateType: https://slsa.dev/provenance/v1 structures, capturing externalParameters and internalParameters accurately while eliminating implicitly standard boilerplates10.
  • SBOM and Dependency Pinning: As a Python standard-library oriented project \[PROJECT-PROVIDED IMPLEMENTATION DESCRIPTION\], external dependencies must be absolutely minimized. Any required cryptographic package must be pinned via exact cryptographic hash, accompanied by a CycloneDX or SPDX Software Bill of Materials (SBOM). Reproducible builds must be verified across heterogeneous CI runners.

28. SQLite-to-Production-Storage Analysis

The reference implementation currently utilizes SQLite, functioning adequately for prototype scale \[PROJECT-PROVIDED IMPLEMENTATION DESCRIPTION\]. While highly efficient, transitioning to MySQL configuration is necessary for concurrent, multi-process request handling in a production WSGI environment.

  • Idempotent Migrations: Schema changes must utilize conditional execution (e.g., CREATE TABLE IF NOT EXISTS, ADD COLUMN wrapped in existence checks). This ensures that if a migration script fails halfway, re-running it is safe and does not corrupt the state \[ARCHITECTURE RECOMMENDATION\].
  • Data Migration Verification: Cryptographic hashing of row datasets before and after migration guarantees byte-for-byte fidelity when transferring the append-only event log from the SQLite file to the MySQL engine \[ARCHITECTURE RECOMMENDATION\].
  • Rollback Strategy: Rollbacks must be explicitly scripted to revert target databases without destroying the source SQLite file. The SQLite file serves as the immutable anchor until the MySQL deployment passes actual-host acceptance testing.

29. Full Staged Migration Roadmap

The following 16-phase roadmap minimizes risk and prevents prototype convenience from overriding constitutional directives. It outlines a deliberate, verifiable path from reference implementation to sovereign infrastructure.

PhaseTitlePrerequisitesIntended Changes & EvidenceStop Conditions & Prohibitions
0Repository-Enabled VerificationRepo access granted.Code: Establish baseline tests, SLSA L1 provenance13. Evidence: Deterministic hashes. Verify: Existing schema/routes.Stop: Undocumented frameworks found. Prohibited: Claiming "production readiness".
1Truth-Boundary CorrectionsPhase 0 complete.Code: Rename variables to separate "identity", "credential", "passport". Tests: PBT ensuring identity objects reject credential functions.Stop: Terminology ambiguity remains in core models.
2Domain SeparationPhase 1 complete.Code: Isolate bounded contexts into discrete Python modules. Refactor WSGI routing. Data: Segregate SQLite namespaces.Stop: Cross-context imports detected by static analysis.
3Schema VersioningPhase 2 complete.Code: Introduce OpenAPI and JSON Schema validation. Add version to serialized data. Data: Append version columns.Stop: Backwards-compatibility parsers fail on legacy records.
4State-Machine HardeningPhase 3, TLA+ models.Code: Replace CRUD with append-only event functions. Data: Create StateTransitions ledger. Tests: Fuzzing concurrent transitions.Stop: Race conditions observed bypassing OCC.
5Public/Private Record SeparationPhase 4 complete.Code: Implement projection materialization logic. Create read-only public API views. Data: Separate projection tables.Stop: Automated scanners find private keys in public views.
6Cryptographic-Provider AbstractionPhase 5 complete.Code: Abstract hardcoded cryptography behind CryptoProvider. Tests: Swap provider with mock HSM; verify all tests pass.Stop: Application logic breaks when provider is swapped.
7Audited Public-Key ImplementationPhase 6 complete.Code: Implement W3C VC 2.0 enveloped proofs2 and did:key4. Tests: DID Resolution Test Suite3.Stop: Fails W3C interoperability standards14.
8Credential and Passport MigrationPhase 7 complete.Code: Logic to retire reference credentials and generate rigorous W3C VCs1. Data: Bulk append transition events.Stop: Historical supersession chain breaks.
9Recovery and Rotation HardeningPhase 8 complete.Code: Implement OCC and sequence numbering for rotation APIs. Tests: High-load concurrency testing.Stop: Split-brain occurs during concurrent rotation races.
10Trust-Policy SeparationPhase 9 complete.Code: Move authorization from hardcoded if/else to policy-evaluation engine. Data: Store policies as versioned schemas.Stop: Delegate capabilities fail to attenuate.
11Receipt and Evidence HardeningPhase 10 complete.Code: Implement Merkle structures for trust receipts and Evulgare references. Tests: Verify hash integrity under corruption.Stop: Silent rewriting of evidence possible.
12Production Database MigrationPhase 11, MySQL env vars.Code: Activate MySQL driver. Data: Idempotent migration from SQLite to MySQL. Tests: Row-hashing comparison.Stop: Row hashes differ between SQLite and MySQL.
13Partition and Continuity WorkPhase 12 complete.Code: Implement offline verification fallbacks. Introduce bounded Evulgare caches. Tests: Induce network partitions.Stop: Core civic reads fail during partition.
14Independent ReviewPhases 0-13 complete.Action: Execute third-party cryptographic engineering review and formal supply-chain security audit.Prohibited: Automated tests claimed as independent review.
15Staged Production AcceptancePhase 14 sign-off.Action: Deploy to cPanel/Passenger hosts. Execute real-world continuity exercises. Validate SLSA L313.Stop: Actual-host deployment fails environment constraints.

30. Rollback and Stop Conditions

At every stage of the migration roadmap, explicit rollback procedures must be maintained.

  • Database Rollback: Reverting the environment variable connection string from MySQL back to the immutable SQLite file.
  • Code Rollback: Utilizing Git version control to revert to the previous SLSA-attested commit.
  • Stop Conditions: Deployment is strictly halted if schema validation fails, if race conditions bypass Optimistic Concurrency Control (OCC) during load testing, if private keys leak into public projections, or if did:key resolution fails against W3C test suites3.

31. Production-Acceptance Matrix

Production readiness is not a subjective claim; it is a matrix of verified technical conditions.

Acceptance CriteriaVerification MethodRequired Outcome
Zero-JS FallbackAutomated browser testing with JS disabled.Core citizenship recovery and presentation function without error.
Event Log ImmutabilityFuzzing attempts to execute UPDATE or DELETE on the log.Database constraints block mutation; application rejects request.
SLSA L3 ProvenanceValidation of signed provenance files via cosign or in-toto10.Signatures verify; builder ID matches trusted infrastructure.
Actual-Host ParityExecution of full test suite on cPanel/Passenger environment.100% pass rate under WSGI constraints (no daemons).

32. Independent-Review Requirements

Prior to finalizing Phase 14, Patefacere must undergo independent review. Repository testing and automated CI/CD pipelines must not be labeled independent certification \[PROJECT-PROVIDED REQUIREMENT\]. The review must encompass:

1. Cryptographic Engineering Review: Validation of the CryptoProvider abstraction, ensuring nonce generation uses attested PRNGs and that did:key derivations strictly adhere to Multibase standards4.

2. Supply-Chain Audit: Verification of SBOMs and SLSA provenance to rule out compromised dependencies16.

3. Formal Methods Review: Peer review of TLA+/Alloy specifications to ensure that the mathematical models of the state machine lack deadlocks and accurately represent Eviulonian constitutional boundaries.

33. Decision Table

Decision AreaSelected PathRationale
Core ArchitectureAppend-only relational store.Meets historical supersession requirements while fitting the WSGI/cPanel deployment model, avoiding complex distributed databases.
DID Methoddid:key for ephemeral/bootstrap.Removes registry dependency for offline/stateless verification, enabling partition tolerance4.
Credential FormatW3C VC 2.0 (Enveloped VC-JWT).Provides standardized selective disclosure, decoupling PII from verification and preventing correlation1.
CryptographyProvider Interface Pattern.Enables transition from reference-grade standard-library math to KMS/HSM without rewriting core application protocols.
Supply ChainSLSA v1.0 Build Track (Level 3).Provides industry-standard provenance and attestation against build-pipeline tampering13.

34. Conflict Register

Architectural design invariably involves managing competing constraints.

  • Conflict: cPanel/Passenger environments restrict daemon-based architectures, limiting the use of complex distributed-consensus (BFT) nodes.
  • Resolution: Delegate distributed consensus to Evulgare/Eviulon layers; Patefacere remains a strictly ordered relational intermediary, utilizing OCC for concurrency.
  • Conflict: The constitutional mandate for Unlinkability vs. the necessity of Public-Record Integrity and Auditability.
  • Resolution: Trust receipts capture policy versions and hashes, explicitly stripping user-identifiable claims from the public projection via one-way materialization views.
  • Conflict: The desire for rapid prototype development vs. strict formal verification.
  • Resolution: Property-based testing serves as the immediate bridge, ensuring code-level invariants are checked continuously while TLA+ modeling is reserved for high-risk, core distributed state transitions.

35. Prioritized Engineering Backlog

To execute the staged roadmap effectively, the engineering team must address the following backlog in strict order:

1. Immediate: Implement SLSA Build Track Level 1 CI/CD provenance and deterministic package hashing to secure the baseline13.

2. Short-term: Refactor the monolithic WSGI routing into strictly bounded Python contexts (Identity, Issuance, Verification).

3. Short-term: Integrate W3C VC 2.0 JSON-LD schemas and did:key resolution logic into the Cryptographic Provider abstraction1.

4. Medium-term: Develop TLA+ models of the credential rotation state machine to formally prove the absence of race conditions.

5. Long-term: Construct the idempotent SQLite-to-MySQL migration tooling, inclusive of cryptographic row-hashing verification.

36. Residual Unknowns and Prohibited Claims

Certain variables cannot be resolved without direct access to the operational environment and policy authorities.

  • Residual Unknowns: The exact schema implementations, WSGI routing quirks, and dependency injection mechanisms of the current prototype repository remain unverified pending Phase 0 execution \[REPOSITORY VERIFICATION REQUIRED\]. Furthermore, the specific temporal friction mechanics and offline caching durations required by Evulgare integration remain mathematically unspecified pending Eviulonian policy decisions.
  • Prohibited Claims: Under no circumstances shall the system be described as "production ready", "independently certified", or operating a live "W3C VC, ZKP, threshold-signature, HSM, TEE, or distributed-registry deployment" based on this architectural specification alone. Recommendations for live deployment are strictly withheld pending physical repository inspection, established cryptographic backup protocols, validated rollback ownership, and documented actual-host testing in the target cPanel/Passenger environment.

Works cited

1. W3C Verifiable Credentials 2.0: The New Standard Reshaping Enterprise Digital Identity, https://vidos.id/blog/w3c-verifiable-credentials-2-0-the-new-standard-reshaping-enterprise-digital-identity

2. Credential Format \- Identity, Credential and Access Management Document \- 24.07 Release \- Gaia-X, https://docs.gaia-x.eu/technical-committee/identity-credential-access-management/24.07/credential\_format/

3. Decentralized Identifier Resolution (DID Resolution) v1 \- W3C, https://www.w3.org/TR/did-resolution/

4. The did:key Method v0.9 \- W3C Credentials Community Group, https://w3c-ccg.github.io/did-key-spec/

5. OWASP Application Security Verification Standard (ASVS) | arc42, https://quality.arc42.org/standards/owasp-asvs

6. OWASP ASVS: Meaning, purpose, and real-world importance (2026, https://www.konfirmity.com/glossary/owasp-asvs

7. On-Chain Registry vs Off-Chain Status List | Credential Revocation, https://chainscorelabs.com/comparisons/identity-soulbound-vs-verifiable-credentials/credential-revocation-mechanisms/on-chain-registry-vs-off-chain-status-list

8. The "Verifiable Credential" Movement: Portable Reputation for Businesses, https://www.jasminedirectory.com/blog/the-verifiable-credential-movement-portable-reputation-for-businesses/

9. Verifiable Credentials in 'Private Individual' vs 'Employee' Contexts (X2I vs X2E) \- Spherity, https://www.spherity.com/post/verifiable-credentials-in-private-individual-vs-employee-contexts-x2i-vs-x2e

10. Provenance \- SLSA.dev, https://slsa.dev/spec/v1.0/provenance

11. DID Implementation Report \- W3C on GitHub, https://w3c.github.io/did-test-suite/

12. About SLSA, https://slsa.dev/spec/v1.0/about

13. Overview \- Harness Developer Hub, https://developer.harness.io/docs/software-supply-chain-assurance/artifact-security/slsa/overview/

14. w3c/vc-data-model-2.0-test-suite: W3C Verifiable Credentials v2.0 test suite \- GitHub, https://github.com/w3c/vc-data-model-2.0-test-suite

15. The did:key DID method | DevHub \- EBSI Hub, https://hub.ebsi.eu/docs/onboarding/natural-person/did-key-method

16. SLSA 1.0: Improving Software Supply Chain Security \- Cycode, https://cycode.com/blog/slsa-1-0-improving-software-supply-chain-security/

17. What's new in SLSA v1.0, https://slsa.dev/spec/v1.0/whats-new