Foundgine v3.4.2
.NET 10 & Java 27 · Apache-2.0 · Semantic & Execution Boundary

Foundgine: Configurable Semantic & Execution Boundary

Foundgine separates application meaning, persistence mapping, authorization, and physical execution from the APIs, workflows, and AI agents that consume them. Configure capabilities once with language-idiomatic fluent APIs, resolve operations against application-defined semantics, and execute deterministically through SQL, EF Core, or JPA—without making an API framework, ORM, database, or AI model the center of your architecture.

1. Caller→ 2. Intent→ 3. Semantic Model→ 4. Operation Graph→ 5. Retrieval→ 6. Resolution→ 7. Authorization→ 8. Plan Binding→ 9. ExecutionIR→ 10. Provider→ 11. Execution→ 12. Evidence
Callers describe intent. The semantic model defines meaning. Authorization determines authority. Planning defines logical execution. Providers define physical execution.

Conventional Apps First

Built for standard .NET 10 and Java 27 backend services first. Foundgine requires no LLM, MCP server, GraphQL endpoint, or agent framework—those are optional consumer adapters.

Authority Stays in the Host

Discovery, candidate retrieval, aliases, model output, and caller arguments are never permission. Every request binds to a host-owned SecurityExecutionContext and cryptographic warrant.

Incremental Adoption

Keep existing EF Core DbContext, JPA EntityManager, PostgreSQL databases, Hot Chocolate, GraphQL Java, Redis, Keycloak, and Temporal infrastructure in place.

What Foundgine Is Not

Foundgine is not an ORM, a GraphQL server, an AI agent framework, an identity/authorization server, a workflow engine, a database engine, or a generic SQL builder. Its sole purpose is the governed boundary between semantic intent and controlled provider execution.

Why Foundgine: One Governed Execution Boundary Across Every Interface

Most applications implement the same business capability more than once: an API resolver applies one set of rules, a background worker applies another, an MCP tool adds its own checks, and an AI integration translates natural language into yet another execution path. Over time, validation, tenant scoping, field visibility, approval requirements, and persistence behavior drift. A secure endpoint does not make a second endpoint secure, and a prompt instruction is not an authorization policy.

Foundgine addresses that duplication by placing a semantic execution boundary between callers and data providers. The application defines what entities and operations mean, the host supplies trusted identity and policy, the runtime resolves and authorizes a request, and a provider executes the resulting constrained plan. GraphQL, MCP, application code, and workflow activities are consumers of that same boundary—not independent implementations of business authority.

Without a shared boundary

  • Rules and authorization are repeated in controllers, resolvers, jobs, and agent tools.
  • Tenant and row filters can be omitted on a new interface or nested relationship.
  • Natural-language retrieval can be mistaken for permission or treated as a confident guess.
  • Each integration develops its own mutation, approval, retry, and audit semantics.

With Foundgine

  • Semantic meaning and persistence mapping are configured independently of the caller.
  • Host-owned identity and authorization constrain the operation before provider execution.
  • Ambiguous intent is clarified or rejected; retrieval scores never grant authority.
  • Adapters converge on shared planning, provider execution, and execution evidence.

Architectural boundary

Application codeGraphQL MCP / agentsTemporal activities

Consumer interfaces translate requests; they do not become separate sources of business authority.

Domain application →Semantic model & operations →Host identity & policy
Intent→Resolution →Authorization warrant →Execution plan / IR
Provider conformance→ EF Core / JPA / SQL / custom provider →Result & receipt

Identity is established by the hosting application or its trusted identity integration. Providers receive a constrained execution representation; they do not infer caller identity from user-supplied filters.

Where the main components fit

Domain application

Owns business concepts, invariants, operation definitions, and the decision to expose a capability. Foundgine does not replace domain services or application workflows.

Semantic model

Names entities, fields, aliases, dimensions, relationships, and operation capabilities independently of physical tables and columns.

Runtime & planner

Resolves structured intent, applies bounded grounding, obtains authorization, creates a logical plan, and lowers it into provider-facing execution IR.

Identity & policy

The host validates authentication and supplies trusted subject, tenant, claims, and policy decisions. Foundgine binds the authorized scope to execution.

Providers

Translate the provider-independent plan into supported SQL or ORM operations and enforce the provider contract. Physical execution remains separate from semantic meaning.

Workflow integrations

Temporal can coordinate durable steps, timers, retries, approvals, and compensation. Each activity obtains fresh authority and invokes Foundgine for the underlying operation.

Execution lifecycle: intent to evidence

The exact stages and their contracts are detailed in the canonical lifecycle reference. At a product level, a request moves through these boundaries in order; later stages cannot retroactively turn an untrusted input into authority.

  1. Intent: a caller supplies a typed request or structured intent document.
  2. Semantic resolution: the runtime maps names and relationships to the configured model; bounded retrieval may propose candidates, but ambiguity is surfaced.
  3. Authorization: the host-owned security context and policy determine allowed operations, rows, and fields. A warrant binds that authority to the request.
  4. Execution planning: the planner creates a provider-independent logical plan and lowers it to ExecutionIR with the required constraints.
  5. Provider conformance: the selected provider validates and translates supported IR nodes into its physical query or mutation mechanism.
  6. Execution & evidence: the provider executes within the host's transaction and operational controls; the runtime returns a result and applicable execution evidence.

Fluent configuration in C# and Java

The following excerpts use the Advanced Supply Chain sample's actual configuration style. Semantic configuration describes domain meaning and relationships; persistence configuration is separate. The full sample contains additional entities, mappings, policies, and registrations.

C# — semantic model configuration
public sealed class SupplierModelConfiguration
    : FoundgineModelConfiguration<Supplier>
{
    public override void Configure(FoundgineModelBuilder<Supplier> model)
    {
        model.ToEntity("Supplier");
        model.HasAlias("Vendor", 95);
        model.HasAlias("Seller", 90);
        model.HasMinimumWeight(80);
        model.HasDimension(x => x.Country).As("country");
        model.HasDimension(x => x.TenantId).As("tenant");
        model.Property(x => x.Country).HasAlias("State", 85);
        model.HasRelationship(x => x.Certifications)
            .To<SupplierCertification>().Named("certifications");
        model.HasRelationship(x => x.Incidents)
            .To<ComplianceIncident>().Named("incidents");
    }
}
Java — semantic model configuration
static final class SupplierSemantics
        extends FoundgineModelConfiguration<Supplier> {
    @Override
    public void configure(FoundgineModelBuilder<Supplier> model) {
        model.toEntity("Supplier");
        model.hasFieldNaming(FieldNaming.PASCAL_CASE);
        model.hasAlias("Vendor", 95);
        model.hasAlias("Seller", 90);
        model.hasMinimumWeight(80);
        model.hasDimension(Supplier::country).as("country");
        model.hasDimension(Supplier::tenantId).as("tenant");
        model.property(Supplier::country).hasAlias("State", 85);
        model.hasMany("certifications", SupplierCertification.class);
        model.hasMany("incidents", ComplianceIncident.class);
    }
}

Both examples configure the same kinds of semantic facts while retaining idiomatic language APIs. The Java sample registers these configurations through FoundgineModel and FoundgineModelRegistrar; the C# sample registers configuration classes through its model builder. See the C# configuration source and Java configuration source.

Security is part of the execution contract

  • Host-owned identity: authentication and claim validation belong to the host or trusted identity integration; caller-provided subject and tenant values are not authority.
  • Tenant and row isolation: authorization contributes constrained predicates that must survive planning and provider lowering.
  • Field policies: permitted projections and field-level restrictions are applied before data is returned; masking/redaction is distinct from authorization to read.
  • Authorization warrants: signed, scoped execution authority binds the operation to its security context and relevant plan provenance.
  • Replay and idempotency controls: single-use/replay defenses and mutation idempotency protect the applicable execution paths; deployments must configure the shared backing stores required for distributed guarantees.
  • Audit: execution evidence and durable audit integrations support traceability; they do not replace operational retention, monitoring, or incident-response controls.

Read the security and warrant specification, mutation lifecycle, and audit and observability design for the detailed contracts and deployment requirements.

Retrieval, mutations, approvals, and receipts

Retrieval is a bounded semantic-discovery aid, not an authority system. The runtime grounds candidates against configured entities, fields, aliases, relationships, and limits. If candidates remain ambiguous, the request requires clarification or is rejected rather than silently selecting a convenient interpretation.

Mutations follow a controlled lifecycle: propose a mutation, validate and dry-run the proposed plan, obtain the required approval against the exact proposal, then execute under fresh valid authority. The resulting execution receipt records the outcome and relevant provenance. Approval is not a substitute for rechecking authorization at execution time.

GraphQL, MCP, and Temporal are integrations—not the semantic core

GraphQL

GraphQL adapters translate schema selections and mutation requests into Foundgine operations. Hot Chocolate remains the GraphQL server; Foundgine supplies the shared semantic and authorization boundary.

MCP & agents

MCP exposes bounded tools for capability discovery and governed execution. Agent frameworks may choose tools and formulate intent, but neither prompts nor model output can mint authority.

Temporal

Temporal owns durable orchestration. Foundgine owns authorization and execution of each business operation; workers should obtain fresh activity-scoped authority on every attempt.

See GraphQL, identity, and Temporal integrations, MCP and agent integration, and the agent clarification and execution walkthrough.

Provider and SDK coverage — implementation boundaries

These components do not all have the same role. C# and Java contain server-side runtime and provider implementations. TypeScript, Python, and WebAssembly are thin transport clients: they call a running Foundgine server and do not embed the semantic runtime or enforce server-side authorization locally.

TechnologyRole in the repositoryImplementation status / boundary
C# / .NETServer runtime, semantic model, planning, authorization, providers and integrationsImplemented Main server-side implementation; see NuGet package and sample documentation.
JavaServer runtime, semantic model, planning, authorization, providers and integrationsImplemented Server-side implementation with Maven modules and Advanced Supply Chain sample.
EF Core.NET ORM providerImplemented Provider integration in the C# provider packages.
JPA / HibernateJava ORM providerImplemented Java ORM provider path; validate the chosen dialect and feature set against provider conformance documentation.
TypeScriptMCP and Temporal HTTP clientSource implemented Thin client; requires a .NET or Java Foundgine host.
PythonAsync and sync MCP / Temporal HTTP clientSource implemented Repository source and tests; README documents local editable installation and does not claim a PyPI release.
WebAssembly (Rust core)Thin WASM transport client for MCP and Temporal HTTPSource implemented Build from the repository with the documented Rust / wasm-bindgen toolchain; not a server runtime.

Package publication and runtime capability are separate questions. Consult the package and module directory and each SDK's README before assuming that a source project is published to a public registry or that a client SDK contains server functionality.

Deployment shape

A typical deployment runs a Foundgine-enabled application service beside its database and optional shared infrastructure. The host validates incoming credentials, builds the trusted security context, registers the semantic model and provider, and exposes only the interfaces required by the application. MCP and GraphQL can be hosted by the same service or separate adapters; Temporal workers are commonly deployed separately from the HTTP API. Redis-backed replay/session controls, durable audit, event stores, and outbox dispatchers are optional infrastructure selected according to the guarantees the deployment requires.

Start with the reference samples, deployment topologies, production operations guide, and developer onboarding.

Canonical 12-Stage Lifecycle & Component Topology

Every entry surface—typed C#/Java code, dynamic queries, JSON intent, Hot Chocolate GraphQL, GraphQL Java, MCP tools, Microsoft Agent Framework, LangChain4j, Spring Boot, or Temporal activities—converges on one monotonic pipeline before any provider work occurs.

Consumer Integrations Workflow Integration GraphQL Adapter [HotChocolate / Java] MCP Integration Gateway Approvals Task Routing Application Consumer uses operations consumes capabilities consumes capabilities executes approved routes tasks submits operations executes mutations defines mutations Planning Execution Query Engine [FoundgineEngine] Mutation Execution Semantic Planner [Planning] Query Results [ExecutionResult] Provider Execution [Execution] Mutation Planning [Mutation] plans operations returns results executes plans plans mutations Persistence Providers ORM Provider Storage Providers Authorization Security Security Context Semantic Authorization [Authorization] Warrant Security [Warrants] carries evidence Semantic Model Request Resolution [Resolution] Persistence Mapping [Mapping] Model Configuration [Configuration] Semantic Model [SemanticModel] Capability Contract defines uses ORM uses provider authorizes verifies warrants resolves requests uses model maps persistence configures

1. SemanticOperationGraph

The canonical security object for reads (and SemanticMutationOperationGraph for writes). Logical traversals (e.g., Customer.transactions) are expanded into intermediate entities and edges before authorization runs so shortcuts cannot tunnel past denied entities.

2. Plan Binding Provenance

SemanticPlan carries an immutable SemanticPlanAuthorizationBinding recording the exact frozen semantic contract fingerprint and authorization decision fingerprint. Planner rewrites must preserve the binding; tampering or drift fails closed.

3. ExecutionIR & Security Proof

ExecutionIRCompiler refuses unbound plans. The final execution gate requires a provider security proof bound to the exact provider plan and exact ExecutionIR, then emits immutable ExecutionEvidence and ExecutionReceipt records.

Stage-by-Stage Execution Contract, Inputs, Outputs & Fail-Closed Invariants

Each stage in Foundgine's monotonic pipeline consumes an immutable artifact from the preceding stage and produces a cryptographically verifiable artifact for the next stage. No provider or adapter can jump ahead or mutate an upstream artifact without invalidating downstream fingerprints.

Stage Component (.NET / Java) Artifact Produced Fail-Closed Invariant
01–02. Intent SemanticQuery, GraphQL/MCP/JSON adapters SemanticOperation / SemanticMutationIntent Rejects malformed syntax, unknown operators, or structural limit violations before resolution.
03–04. Graph SemanticOperationGraphBuilder SemanticOperationGraph Expands logical traversal shortcuts (e.g., Customer.transactions) into all intermediate entities and FK edges so hidden hops are explicitly authorized.
05–06. Grounding SemanticLexicalResolver GroundingDecision (Committed) If free-form vocabulary maps to ≥2 distinct semantic signatures or falls below minimumAliasWeight, returns RequiresClarification with Committed = null.
07. Authority ISemanticAuthorizationPolicy + Warrant Verifier AuthorizationDecision + Row Predicates Evaluates host-owned SecurityExecutionContext, warrant signature, delegation chain, and revocation epoch; injects row-level predicates; denies empty field projections.
08. Plan Bind SemanticPlanner SemanticPlan + SemanticPlanAuthorizationBinding Binds logical plan to frozen MetadataRegistry SHA-256 fingerprint and authorization decision digest; optimizer rewrites must preserve binding identity.
09. Lowering ExecutionIRCompiler ExecutionIR (Scans, Joins, Predicates, Sorts) Refuses unbound or tampered plans; lowers authorization expressions into parameterized relational/ORM filter trees with deterministic tie-breaker keys.
10–11. Dispatch SqlExecutionProvider / FoundgineEfReader / JpaOrmProvider Provider Security Proof + Materialized Rows Provider gate verifies proof against exact ExecutionIR; plan cache keys include full authorization predicate fingerprint; consumes single-use replay nonce on writes.
12. Evidence BufferedDurableAuditLog / ExecutionReceipt ExecutionEvidence & Signed Receipt Records principal, tenant, warrant ID, contract fingerprint, plan fingerprint, row counts, and timestamps into lossless durable audit storage.

Fluent Configuration, Mapping & Queries (.NET 10 & Java 27)

Foundgine's primary authoring surface is a five-concern fluent configuration model (FoundgineModel) that keeps domain classes free of persistence attributes and compiles to the exact same MetadataRegistry as build-time AOT generators. Calling Build() / build() validates the entire model in one pass and reports every missing key, unmapped relationship, or type mismatch in a single exception.

Configuration Concern .NET 10 Base Class Java 27 Base Class Responsibility
Semantic Entity & Aliases FoundgineModelConfiguration<TModel> FoundgineModelConfiguration<TModel> Business identity, fields, weighted aliases, dimensions, logical traversals.
Persistence Table & Columns FoundginePersistenceConfiguration<TEntity> FoundginePersistenceConfiguration<TEntity> Physical table/schema name, column mappings, primary key, indexes, constraints.
Model-to-Storage Map FoundgineEntityMap<TModel, TEntity> FoundgineEntityMap<TModel, TEntity> Maps semantic members to storage members (or FoundgineIdentityEntityMap<T> / Convention()).
Relationship Foreign Keys FoundgineConnectionConfiguration FoundgineConnectionConfiguration Binds semantic relationships to physical foreign keys (HasForeignKey / HasForeignKeyOnSource).
Model Connections & Predicates FoundgineModelConnectionConfiguration<TModel> FoundgineModelConnectionConfiguration<TModel> Cross-entity visits, explicit conversions, and authorization expressions.
C# (.NET 10) — Fluent Model, Legacy Table Mapping, Relationships & Logical Traversals
using Foundgine.Core.Semantic.Configuration;
using Foundgine.Core.Semantic.Metadata;

public sealed class SupplyChainModel : FoundgineModel
{
    public override void Configure(FoundgineModelBuilder model)
    {
        model.Configure<CustomerSemantics>();
        model.Configure<OrderSemantics>();
        model.Configure<OrderLineSemantics>();
        model.Configure<CustomerTable>();
        model.Configure<OrderTable>();
        model.Configure<FoundgineIdentityEntityMap<Customer>>();
        model.Configure<FoundgineIdentityEntityMap<SalesOrder>>();
        model.Configure<SupplyChainConnections>();
    }
}

internal sealed class CustomerSemantics : FoundgineModelConfiguration<Customer>
{
    public override void Configure(FoundgineEntityConfigurationBuilder<Customer> e)
    {
        e.Alias("Client", weight: 90);
        e.Property(x => x.Name).Alias("CustomerName", weight: 85);
    }
}

internal sealed class OrderTable : FoundginePersistenceConfiguration<SalesOrder>
{
    public override void Configure(FoundginePersistenceBuilder<SalesOrder> m)
    {
        m.ToTable("tbl_order").HasKey(x => x.Id);
        m.Property(x => x.Id).HasColumnName("ord_id");
        m.Property(x => x.CustomerId).HasColumnName("cust_id");
        m.Property(x => x.Total).HasColumnName("ord_total");
    }
}

internal sealed class SupplyChainConnections : FoundgineConnectionConfiguration
{
    public override void Configure(FoundgineConnectionBuilder connections)
    {
        connections.HasRelationship<Customer, SalesOrder>()
            .Using<Customer, SalesOrder>()
            .HasForeignKey(o => o.CustomerId)
            .References(c => c.Id);
    }
}

MetadataRegistry registry = new SupplyChainModel().Build();
Java 27 — Fluent Model, Persistence Mapping & Operand Authorization Builder
import com.foundgine.core.semantic.configuration.*;
import com.foundgine.core.semantic.metadata.MetadataRegistry;

public final class ErpModel extends FoundgineModel {
    @Override
    public void configure(FoundgineModelRegistrar model) {
        model.configure(CustomerSemantics.class);
        model.configure(CustomerStorage.class);
        model.configure(CustomerMap.class);
        model.configure(CustomerOrderConnections.class);
    }
}

public final class CustomerOrderConnections extends FoundgineModelConnectionConfiguration<Customer> {
    @Override
    public void configure(FoundgineModelConnectionBuilder<Customer> connections) {
        connections.hasConnection(CustomerErp.class, Customer::customer)
            .maps(Customer::customerId, CustomerErp::id)
            .authorize(UserContext.class, "SameTenant", a ->
                a.context(UserContext::tenantId)
                 .eq(a.resource(CustomerErp::tenantId)));
    }
}

MetadataRegistry registry = new ErpModel().build();
C# (.NET 10) — Typed, Dynamic & SemanticQuery
// 1. Typed Query (compile-time checked)
var typedResult = await foundgine
    .Query<Customer>()
    .Select(c => new { c.Id, c.Name })
    .Where(c => c.TenantId == tenantId)
    .Take(50)
    .ExecuteAsync(ct);

// 2. Dynamic Query (runtime string names)
var dynamicResult = await foundgine
    .Query("Customer")
    .Select("Id", "Name")
    .WhereRelated("transactions",
        SemanticRelationshipQuantifier.Some,
        tx => tx.Where("Amount", SemanticFilterOperator.Gt, 100))
    .ExecuteAsync(ct);

// 3. Parity-Verified SemanticQuery Builder
var op = SemanticQuery.From(metadata, "Warehouse")
    .Select("Id", "Name")
    .WhereEq("Region", "NZ")
    .Include(warehouseLots, lots => lots
        .Select("Sku", "OnHand")
        .WhereNeq("OnHand", 0)
        .OrderBy("Sku", SemanticSortDirection.Asc)
        .Take(50))
    .Build();
Java 27 — SemanticQuery Builder (Parity-Verified)
// Held to shared vectors in src/conformance/semantic-query-vectors.json
var op = SemanticQuery.from(metadata, "Warehouse")
    .select("Id", "Name")
    .whereEq("Region", "NZ")
    .include(warehouseLots, lots -> lots
        .select("Sku", "OnHand")
        .whereNeq("OnHand", 0)
        .orderBy("Sku", SemanticSortDirection.ASC)
        .take(50))
    .build();

// Execute via IFoundgineExecutor
ExecutionResult result = executor.executeAsync(request, securityContext).join();
C# (.NET 10) — Dependency Injection & Minimal Application Surface
// Startup composition: inject IFoundgineExecutor in application services
services.AddFoundgine(options =>
{
    options
        .UseMetadata(new SupplyChainModel().Build())
        .ConfigureSemantics(model =>
        {
            // Logical traversal expanded before authorization checks intermediate nodes
            model.Traversal(
                "Customer",
                "transactions",
                "customerRelationships",
                "contract",
                "transactions");
        })
        .ConfigureAuthorization(auth =>
        {
            // Application-supplied semantic policy
        });
});

Model Validation Rules, Filter Operators & Pagination Semantics

Single-Pass Model Validation

Calling new MyModel().Build() (.NET) or new MyModel().build() (Java) runs deterministic graph checks before returning a frozen MetadataRegistry:

  • Every mapped entity must declare a valid primary key (HasKey) and resolve all mapped columns.
  • Every relationship foreign key must match source/target CLR or Java field types exactly.
  • Logical traversals must resolve every intermediate hop across registered relationships without cycles or dangling targets.
  • Produces a deterministic SHA-256 Contract Fingerprint embedded in every downstream plan and warrant check.

Supported Filter & Quantifier Operators

All filter trees lower identically across ADO.NET SQL, EF Core, JPA Criteria, and InMemory providers:

  • Comparison: Eq, Neq, Gt, Gte, Lt, Lte
  • Set & Range: In, NotIn, Between, IsNull, IsNotNull
  • String: Contains, StartsWith, EndsWith (escaped LIKE)
  • Logical: And, Or, Not (bounded by MaxFilterDepth=32)
  • Relational: WhereRelated(Some | Every | None, subFilter)

Deterministic Keyset & Offset Pagination

To prevent skipped or duplicated rows during cursor pagination across distributed replicas:

  • ExecutionIRCompiler automatically appends the entity primary key as a final deterministic tie-breaker sort column if not already present.
  • Opaque cursors encode sort boundary values bound to the plan fingerprint and are capped at MaxCursorLength = 4,096 bytes.

Controlled Mutations: Propose → Dry-Run → Approve → Execute

Writes are explicitly opt-in and follow a deterministic multi-stage lifecycle separate from reads. Mutation authorization verifies entity write permission, field write permission for supplied values, field read permission for returned fields, and read permission for any fields/relationships referenced in mutation filters.

1. Propose Graph→ 2. Validate & Authorize→ 3. Dry-Run (Fingerprint)→ 4. Cryptographic Approval→ 5. Revalidate & Consume Nonce→ 6. Atomic Commit + Receipt
C# — Multi-Entity Mutation Graph with Generated Key Dependencies
// Compose a multi-step order + lines + shipment mutation graph
var graph = new SemanticMutationIntentBuilder(model)
    .Create("PurchaseOrder", "order")
        .Set("SupplierId", supplierId)
        .Return("Id")
    .Create("PurchaseOrderLine", "line")
        .SetFrom("PurchaseOrderId", "order", "Id") // binds generated parent PK
        .Set("ProductId", productId)
        .Set("Quantity", 25m)
        .Return("Id", "PurchaseOrderId")
    .Create("Shipment", "shipment")
        .SetFrom("PurchaseOrderId", "order", "Id")
        .Set("Quantity", 25m)
        .Return("Id")
    .Build();

// 1. Dry-run validates & computes deterministic plan fingerprint
DryRunResult dryRun = await mutations.DryRunAsync(graph, securityContext, ct);

// 2. Host governance approves the exact plan fingerprint
PlanApproval approval = await mutations.ApproveAsync(dryRun.PlanFingerprint, approverContext, ct);

// 3. Execution re-verifies warrant, revocation, approval & plan binding before SQL/ORM write
MutationExecutionResult result = await mutations.ExecuteApprovedAsync(approval, securityContext, ct);

Key Mutation Guarantees

  • Dry-Run Is Not a Lock: Dry-run validates policy, dependencies, and resource bounds without committing side effects, returning the exact PlanFingerprint.
  • Tamper-Evident Approval Binding: If any field, target entity, filter, or semantic contract changes after dry-run, the approval fingerprint check fails closed.
  • Single-Use Replay Keys & Pre/Post Revocation: High-assurance mutation execution checks issuer signature and revocation sequence before dispatch, consumes the single-use replay nonce immediately prior to execution, and re-checks revocation after execution.
  • Atomic Transaction Boundary: Both SQL batched mutations and ORM mutation providers validate the entire batch upfront and execute inside a single transaction rollback boundary.

Lexical Grounding, Weighted Aliases & Retrieval Boundaries

Free-form language is resolved through SemanticLexicalResolver.Ground(...) (.NET) and SemanticLexicalResolver.ground(...) (Java). Approximate retrieval providers (ElasticsearchSemanticLexicalCandidateSource or PgVectorSemanticLexicalCandidateSource) only propose vocabulary candidates; the semantic graph validates structural legality and groups paths by semantic signature.

5-Phase Bounded Lexical Grounding Algorithm

When SemanticLexicalResolver.Ground(...) receives a natural-language phrase, it executes five deterministic, bounded phases before emitting a GroundingDecision:

  1. Tokenization & Normalization: Splits input into normalized lexical tokens while enforcing MaxTokens = 32 and cooperative cancellation.
  2. Non-Authoritative Vocabulary Retrieval: Queries registered ISemanticLexicalCandidateSource providers (Elasticsearch BM25 or PostgreSQL pgvector) within RetrievalTimeout = 2s for matching entity names, field names, and weighted aliases.
  3. Constrained Graph Path Exploration: Traverses legal relationships in the frozen MetadataRegistry connecting candidate entities and predicates, halting immediately if explored paths exceed MaxPathsExplored = 5,000 or Timeout = 250ms (GroundingOutcome.BudgetExceeded).
  4. Semantic Signature Canonicalization: Reduces each candidate path into a canonical structural signature (root entity + normalized filter AST + relationship hops). Multiple surface phrasings (e.g., "client" and "customer") that collapse to the same semantic signature reinforce one another rather than causing false ambiguity.
  5. Contention & Weight Threshold Gate: If ≥2 distinct semantic signatures remain viable, or the winning signature's evidence weight falls below minimumAliasWeight, the resolver fails closed with GroundingOutcome.RequiresClarification and populates CompetingInterpretations.
GroundingOutcome When It Occurs Committed Execution Behavior
Committed Exactly one semantic meaning dominates, or multiple candidates collapse onto the same signature and satisfy minimumAliasWeight. Populated Proceeds to authorization, plan binding, and execution.
RequiresClarification Two or more distinct semantic meanings remain in contention (e.g., "active customers" → AccountEnabled vs. HasRecentOrder), or alias evidence falls below threshold. null Refuses to guess; exposes CompetingInterpretations for sanitized clarification.
Unresolved No legal semantic path exists or a token has no declared vocabulary (e.g., unmodeled threshold "big" or relative date "last summer"). null Fails closed; names the exact unresolved token in Reason.
BudgetExceeded Any bounded search control fires (MaxTokens=32, MaxPathsExplored=5000, Timeout=250ms, RetrievalTimeout=2s, or Cancelled). null Fails closed with BudgetLimit; partial cutoff candidates are diagnostic-only.
C# — Weighted Aliases & Lexical Grounding Decision
// Declare vocabulary evidence weights (1..100) without granting authority
[FoundgineAlias("Vendor", Weight = 95)]
[FoundgineAlias("Seller", Weight = 90)]
public sealed record Supplier(
    Guid Id,
    [property: FoundgineAlias("State", Weight = 85)] string Country);

// Enforce minimum alias evidence threshold before committing
var resolver = new SemanticLexicalResolver(
    contract,
    candidateSource,
    minimumAliasWeight: 80);

GroundingDecision decision = resolver.Ground("active customers");

switch (decision.Outcome)
{
    case GroundingOutcome.Committed:
        // Safe to proceed to authorization & planning
        break;
    case GroundingOutcome.RequiresClarification:
        // Surface sanitized options from decision.CompetingInterpretations
        break;
    case GroundingOutcome.Unresolved:
    case GroundingOutcome.BudgetExceeded:
        // Fail closed; inspect decision.Reason / decision.BudgetLimit
        break;
}

Two Distinct Retrieval Boundaries

  • Vocabulary Grounding (ISemanticLexicalCandidateSource): Implemented interchangeably by ElasticsearchSemanticLexicalCandidateSource (BM25/fuzzy) and PgVectorSemanticLexicalCandidateSource (cosine/L2/inner-product vector search). Resolves words like "nike" or "shoes" to schema entities, fields, and relationships.
  • Row Data Matching (IApproximateCandidateSource): Implemented by PostgresRetrievalCandidateSource in .NET and Java behind RetrievalStrategy:
    • Fuzzy — PostgreSQL pg_trgm trigram similarity
    • FullText — native tsvector / websearch_to_tsquery
    • Search — optional ParadeDB pg_search BM25
    • GraphSimilarity — optional Apache AGE Cypher neighbor traversal
  • Zero Authority: Neither boundary can bypass semantic resolution or authorization.

Zero-Trust Security, Cryptographic Warrants & Resource Limits

Foundgine enforces defense-in-depth across every transport, planner, cache, and storage provider:

1. Host-Owned Identity & Delegation Chains

Identity, tenant, audience, and roles come exclusively from the host's ISecurityExecutionContextProvider. Delegated warrants require an explicit trusted root issuer, a complete root-to-leaf chain on SecurityExecutionContext, and a configured ISecurityWarrantDelegationTrustResolver verifying every signature and ensuring child authority never exceeds parent authority.

2. Row-Level Predicates & Fail-Closed Projection

Conditional access policies emit provider-independent predicates (e.g., resource.TenantId == context.TenantId) that travel inside the logical plan and are lowered into parameterized SQL WHERE clauses or ORM filters. An empty authorized field set fails closed rather than widening to SELECT *.

3. Plan-Cache Isolation

Provider plan caching reuses compiled physical shapes keyed by the full plan fingerprint—including authorization predicates—while binding context parameters at execution time. Cache hits never skip semantic resolution or authorization revalidation.

4. Distributed Redis Revocation & Atomic Approvals

Horizontally scaled hosts use RedisSecurityWarrantReplayStore and RedisSecurityWarrantRevocationStore (Redis/Valkey/Garnet) wrapped in AnchoredSecurityWarrantRevocationStore backed by PostgreSQL GREATEST epoch anchors. If Redis lags behind the durable anchor or is unreachable, warrant authorization fails closed.

C# — Conditional Policy Expression & Distributed Redis + PostgreSQL Warrant Anchor
// 1. Provider-independent conditional predicate (lowered to SQL WHERE / ORM predicate)
Expression<Func<UserContext, Employee, bool>> CanReadEmployee =>
    (user, employee) => user.TenantId == employee.TenantId;

// 2. Distributed Redis/Valkey/Garnet replay + monotonic revocation anchored in PostgreSQL
var mux = await ConnectionMultiplexer.ConnectAsync("redis:6379,syncTimeout=1000");
var redisRevocation = new RedisSecurityWarrantRevocationStore(new StackExchangeScriptBackend(mux));
var pgAnchor = new PostgresSecurityWarrantRevocationEpochAnchor(pgDataSource);

builder.Services.AddFoundgine(o =>
{
    o.WarrantReplayStore = new RedisSecurityWarrantReplayStore(new StackExchangeReplayBackend(mux));
});
builder.Services.AddSingleton<ISecurityWarrantRevocationStore>(
    new AnchoredSecurityWarrantRevocationStore(redisRevocation, pgAnchor));

Engine-Side Structural Guards (SecurityResourceLimits)

Guard Default Max Guard Default Max Guard Default Max
Selection depth 32 Operation-graph nodes 256 Page size 1,000
Selection nodes 256 Operation-graph fields 512 Offset 1,000,000
Filter depth / nodes 32 / 256 Operation-graph edges 255 Mutation ops / batch 128
Order terms / path depth 64 / 16 Cursor length 4,096 Mutation fields / effects 64 / 256

Cryptographic Warrant Anatomy, Delegation Chains & Replay Defense

Warrant Claims & Binding

Host-minted warrants cryptographically bind execution authority to a specific runtime context:

  • iss / aud: Trusted issuer & service audience
  • sub / tid: Authenticated principal & tenant ID
  • jti / exp / nbf: Single-use nonce & tight TTL
  • rev_seq: Monotonic revocation epoch floor
  • scope / entities: Narrowed capability allowlist
  • contract_fp: Frozen MetadataRegistry SHA-256

Delegation Trust Chain Rules

When an orchestrator or agent delegates authority to a sub-agent (SecurityExecutionContext.DelegationChain):

  • Every link from root host issuer to leaf executor must verify against ISecurityWarrantDelegationTrustResolver.
  • Monotonic Attenuation: A child warrant can only narrow entities, fields, operations, or TTL—any attempt to widen tenant, role, or write scope fails closed.
  • Revoking any ancestor warrant invalidates the entire downstream delegation chain immediately.

Fail-Closed Failure Matrix

Exact runtime behavior when infrastructure or tokens degrade:

  • Expired / bad signature → SecurityAuthorizationException
  • Replayed jti nonce → WarrantReplayDetectedException
  • Redis behind PG anchor → Fail-closed (deny dispatch)
  • Empty authorized fields → Forbidden (never SELECT *)
  • Unbound SemanticPlan → InvalidExecutionPlanException

ORM Providers (EF Core & JPA), SQL, Migrations & Compile-Time AOT

Foundgine's ORM providers sit on top of a provider-neutral core (Foundgine.Providers.Orm in .NET, storage/orm in Java) that translates authorized ExecutionIR into typed EF Core IQueryable or JPA Criteria queries—enforcing root and child permission filters inside SQL, binding all values as parameters, and guaranteeing deterministic tie-breaker ordering for cursor pagination.

C# — EF Core Reader (Authorized) & Generic Repository
// One-line EF Core registration
services.AddFoundgineEf(
    new SupplyChainModel().Build(),
    (sp, o) => o.UseNpgsql(connectionString));

// Authorized semantic read via FoundgineEfReader
var result = await reader.ReadAsync(SalesOrder.Entity, q => q
    .Where(SalesOrder.Id.Eq(orderId), SalesOrder.CustomerId.Eq(customerId))
    .Include(SalesOrder.Relationships.Lines), ct);

// Mechanical generic CRUD repository (check capability first for writes)
var repo = sp.GetRequiredService<IFoundgineRepository<Shipment>>();
await repo.UpdateAsync(id, x => x.Status, "Delivered");
Java 27 — JPA Entities Gateway & Flyway Migrations CLI
// Name-addressed JPA gateway with mandatory ReadGate authorization
var entities = new JpaEntities(entityManager, registry, readGate);
var warehouse = entities.entity("Warehouse");
var rows = warehouse.read(Map.of("Region", "NZ"), List.of("Id", "Name"));

// Java schema diff & Flyway SQL generator (foundgine-migrations)
// mvn exec:java -Dexec.mainClass=com.foundgine.migrations.MigrationsCli ...
// Commands:
//   migrations add InitialCreate
//   migrations has-pending-model-changes
//   migrations script
//   database update

ExecutionIR Node Algebra & Deterministic SQL / ORM Lowering

Between logical planning (SemanticPlan) and physical database execution, ExecutionIRCompiler lowers every authorized operation into a closed, immutable relational/graph algebra (ExecutionIR). Storage providers translate ExecutionIR nodes mechanically without re-interpreting high-level semantic intent:

ExecutionIR Node Types

  • ScanNode(Entity, PhysicalTable, Alias)
  • JoinNode(Left, Right, FkPairs, JoinKind)
  • PredicateFilterNode(LoweredAuth + UserFilter)
  • ProjectionNode(AuthorizedColumnList)
  • SortNode(ExplicitTerms + ImplicitPkTieBreaker)
  • CursorSliceNode(CursorBoundary, Take, Offset)

SQL & ORM Lowering Guarantees

  • Zero String Interpolation: Every literal and security context value (TenantId, SubjectId, cursor keys) binds as a positional/named ADO.NET or JDBC parameter.
  • N+1 Elimination: Nested relationship includes compile into batched child queries or lateral/correlated joins scoped by parent keys and child row-level predicates.
  • Plan Cache Key Isolation: Compiled SQL strings are cached under SHA256(ContractFP + PlanBindingFP + Dialect), guaranteeing two roles with different row predicates never collide in cache.
C# (.NET 10) — Implementing ISemanticAuthorizationPolicy (Row + Field Security)
using Foundgine.Core.Security;
using Foundgine.Runtime.Authorization;

public sealed class SupplyChainAuthorizationPolicy : ISemanticAuthorizationPolicy
{
    public ValueTask<SemanticAuthorizationDecision> AuthorizeAsync(
        SemanticAuthorizationRequest request,
        CancellationToken ct)
    {
        var ctx = request.SecurityContext;
        if (!ctx.IsAuthenticated)
            return ValueTask.FromResult(SemanticAuthorizationDecision.Deny("Unauthenticated caller."));

        // 1. Enforce mandatory tenant row-level predicate lowered into SQL WHERE / EF IQueryable
        var tenantPredicate = SemanticFilter.Eq("TenantId", ctx.TenantId);

        // 2. Restrict sensitive fields unless caller holds 'finance' role
        var allowedFields = request.RequestedFields
            .Where(f => f != "UnitCost" || ctx.Roles.Contains("finance"))
            .ToArray();

        if (allowedFields.Length == 0)
            return ValueTask.FromResult(SemanticAuthorizationDecision.Deny("No authorized fields remain."));

        return ValueTask.FromResult(
            SemanticAuthorizationDecision.Allow(allowedFields, tenantPredicate));
    }
}
Java 27 — Implementing SemanticAuthorizationPolicy
import com.foundgine.core.security.*;
import com.foundgine.runtime.authorization.*;

public final class ErpAuthorizationPolicy implements SemanticAuthorizationPolicy {
    @Override
    public SemanticAuthorizationDecision authorize(SemanticAuthorizationRequest request) {
        var ctx = request.securityContext();
        if (!ctx.isAuthenticated()) {
            return SemanticAuthorizationDecision.deny("Unauthenticated caller.");
        }

        var tenantPredicate = SemanticFilter.eq("TenantId", ctx.tenantId());
        var allowedFields = request.requestedFields().stream()
                .filter(f -> !f.equals("UnitCost") || ctx.roles().contains("finance"))
                .toList();

        if (allowedFields.isEmpty()) {
            return SemanticAuthorizationDecision.deny("No authorized fields remain.");
        }
        return SemanticAuthorizationDecision.allow(allowedFields, tenantPredicate);
    }
}
Compile-Time AOT Metadata Generation: In .NET, Foundgine.Providers.Aot.Generator (Roslyn incremental source generator) and Foundgine.Providers.Orm.Generator emit reflection-free metadata and EF maps at compile time. In Java, foundgine-aot-generator (FoundgineAotProcessor) processes @FoundgineModel and @FoundgineModelEntityMap annotations to emit GeneratedFoundgineMetadata.build().
C# (.NET 10) & Java 27 — Compile-Time AOT Attributes / Annotations (Zero Reflection)
// C# (.NET 10) — Processed at build time by Foundgine.Providers.Aot.Generator
[FoundgineEntity("SalesOrder", Schema = "erp", Table = "tbl_order")]
public sealed record SalesOrderModel(
    [property: FoundgineKey, FoundgineColumn("ord_id")] Guid Id,
    [property: FoundgineColumn("cust_id")] Guid CustomerId,
    [property: FoundgineColumn("ord_total"), FoundgineAlias("OrderAmount", Weight = 90)] decimal Total);

// Emits reflection-free GeneratedFoundgineMetadata.Create() at compile time (Native AOT ready).

// Java 27 — Processed by com.foundgine.aot.FoundgineAotProcessor
// @FoundgineModel(name = "SalesOrder", table = "tbl_order")
// Generates GeneratedFoundgineMetadata.build() with zero runtime classpath scanning.

Extensions: GraphQL, Keycloak Identity & Temporal Workflows

Extensions connect external API, identity, and orchestration frameworks to Foundgine's semantic boundary. They translate protocols and host contexts—they never duplicate authorization logic.

C# — Fail-Closed GraphQL HTTP Endpoint (Foundgine.Extensions.GraphQL.Http)
using Foundgine.Extensions.GraphQL.Http;

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

// Fail-closed POST /graphql: unlisted roots are forbidden; identity comes from JWT only
app.MapFoundgineGraphQL(o =>
{
    o.QueryRootRoles["order"]     = ["manager", "customer"];
    o.QueryRootRoles["orderLine"] = ["manager"]; // customers reach lines only via their orders
    o.Authorize = ctx =>
        ctx.User.IsInRole("customer") && !int.TryParse(ctx.User.FindFirst("customer_id")?.Value, out _)
            ? new GraphQLAdapterError("FORBIDDEN", "A customer_id claim is required.", Category: "FORBIDDEN")
            : null;
});

app.Run();

Keycloak OIDC → Trusted SecurityExecutionContext & Signed Warrants

  • Validates JWT issuer, audience, JWKS signature, lifetime, and key rotation via KeycloakSecurityExecutionContextProvider (.NET) and com.foundgine.extensions.keycloak (Java).
  • Derives subject, tenant, and roles strictly from validated token claims—never from GraphQL variables, JSON body fields, or MCP tool arguments.
  • Issues short-lived, scope-constrained warrants via FoundgineWarrantIssuer backed by KMS/HSM or mounted signing keys, with shared replay protection across replicas.

Temporal Durable Workflows & Transactional Outbox

  • Division of Responsibility: PostgresOutbox records events in the same transaction as business writes; FoundgineTemporalOutboxPublisher dispatches workflow starts/signals; Temporal owns timers, retries, approvals, and compensations; each activity re-mints fresh host security context before invoking Foundgine.
  • Zero Token Leakage: Warrants and raw access tokens are never serialized into Temporal workflow inputs or history.
  • Workflow HTTP Routes: Exposes /foundgine/workflows (processes, describe, start, status, decide, cancel) consumed directly by the TypeScript, Python, and WebAssembly SDKs.

AI Agent Frameworks, MCP Protocol & Thin Client SDKs

Foundgine exposes six bounded tools over MCP Streamable HTTP (default POST /mcp, protocol version 2025-06-18, optional Mcp-Session-Id and replayable SSE). Write approvals use RSA-2048+ PKCS#1 v1.5 SHA-256 signed tokens (fgmcp1.<payload>.<sig>) bound to the exact plan fingerprint.

MCP Tool Purpose Authority & Verification Rule
foundgine_capabilities Discover entities, fields, relationships, and access levels visible to the caller. Advisory only; never grants permission to execute.
foundgine_query Execute natural-language or open read intent via lexical grounding. Refuses ambiguous intent (RequiresClarification); enforces row/field predicates.
foundgine_query_semantic Execute structured JSON read intent (rootEntity, selections, filter, order). Deterministic plan binding and cryptographic execution receipt.
foundgine_mutation_dry_run Validate and authorize a mutation without committing side effects. Returns canonical planFingerprint and previewed effects.
foundgine_mutation_approve Issue an fgmcp1 signed approval token bound to an authorized mutation plan. Host-controlled governance; models have no approve tool in MAF.
foundgine_mutation_execute_approved Execute a previously approved mutation plan. Verifies signature, replay nonce, expiry, plan digest, and re-authorizes before write.
C# — Microsoft Agent Framework Integration (Approval-Gated Mutations)
using Foundgine.Providers.AgentFramework.Hosting;
using Microsoft.Agents.AI;

builder.Services.AddFoundgine(/* semantic model, providers */);
builder.Services.AddSingleton<ISecurityExecutionContextProvider, HttpContextSecurityProvider>();
builder.Services.AddSingleton<IChatClient>(/* any Microsoft.Extensions.AI chat client */);

builder.Services.AddFoundgineAgentFramework(o =>
{
    o.AgentName = "orders";
    o.EnableMutations = true; // wraps foundgine_mutation_execute in ApprovalRequiredAIFunction; no model approve tool
});

var agent = scope.ServiceProvider.GetRequiredKeyedService<AIAgent>("orders");
var session = await agent.CreateSessionAsync();
var response = await agent.RunAsync("Which purchase orders are overdue?", session);
Java 27 — LangChain4j Tool Map & Spring Boot Auto-Configuration
// 1. LangChain4j AiServices integration (io.github.cristianbarragan:foundgine-providers)
FoundgineMcpServer server = FoundgineMcpServer.builder()
        .serverInfo("foundgine", "3.4.2")
        .withReadTools(tools)
        .build();

Assistant assistant = AiServices.builder(Assistant.class)
        .chatModel(model)
        .tools(FoundgineLangChain4jTools.toolMap(server))
        .build();

// 2. Spring Boot application.properties (off by default; protect /mcp with Spring Security)
// foundgine.mcp.enabled=true
// foundgine.mcp.path=/mcp
// foundgine.mcp.allowed-origins=https://app.example
TypeScript — @foundgine/typescript Thin Client SDK (Node 20+ / Fetch)
import { FoundgineClient } from "@foundgine/typescript";

const client = new FoundgineClient({
  baseUrl: "https://your-host.example",
  token: async () => process.env.FOUNDGINE_TOKEN!,
});

try {
  const contract = await client.execute("foundgine_capabilities", {});
  const rows = await client.execute("foundgine_query_semantic", {
    intentJson: JSON.stringify({
      rootEntity: "Customer",
      selections: [{ field: "Name" }],
      limit: 20,
    }),
  });
  console.log(contract.content, rows.content, rows.isError);
} finally {
  await client.close();
}
Python 3.11+ — foundgine Async & Sync Client SDK
import asyncio, json
from foundgine import FoundgineClient

async def main() -> None:
    async with FoundgineClient("https://your-host.example", token=lambda: "tok") as client:
        rows = await client.execute(
            "foundgine_query_semantic",
            {"intentJson": json.dumps({"rootEntity": "Customer", "selections": [{"field": "Name"}], "limit": 20})},
        )
        print(rows.content, rows.is_error)

asyncio.run(main())
WebAssembly — @foundgine/wasm (Pure-Rust Sans-I/O Core + ES Module)
import { FoundgineClient, init } from "@foundgine/wasm";

await init(); // load .wasm once in Browser, Cloudflare Worker, Deno, or Node 20+
const client = new FoundgineClient({
  baseUrl: "https://your-host.example",
  token: async () => "tok",
  fetch,
});

const rows = await client.execute("foundgine_query_semantic", {
  intentJson: JSON.stringify({ rootEntity: "Customer", selections: [{ field: "Name" }], limit: 20 }),
});

Repository Tree & Class Reference (XML Doc & Javadoc Summaries)

Complete directory map of Foundgine/Foundgine (v3.4.2) annotated with the canonical XML documentation (<summary>) and Javadoc descriptions from each assembly, package, and primary class/interface. Use the filter bar below to search by class name, namespace, file path, or responsibility.

▶ src/csharp/ C# · .NET 10 Primary .NET 10 solution (Foundgine.sln): Core, Runtime, Providers, Extensions, and runnable samples.
▶ src/csharp/Foundgine.Core/ Core Contract Zero-dependency semantic model, fluent configuration, metadata registry, operation graph, lexical grounding, planning, ExecutionIR, and security contracts.
▶ Semantic/Configuration/ & Semantic/Metadata/ Five-concern fluent authoring surface and immutable frozen semantic contract representation.
  • FoundgineModel abstract class Semantic/Configuration/FoundgineModel.cs

    Root fluent model entry point. Aggregates entity semantic configurations, persistence table/column mappings, model-to-entity mappings, and relationship connections, validating the entire model in a single pass via Build() into an immutable MetadataRegistry.

  • FoundgineModelConfiguration<TModel> abstract class Semantic/Configuration/FoundgineModelConfiguration.cs

    Configures business-facing semantic identity, fields, dimensions, weighted vocabulary aliases (Alias(..., weight)), and logical traversal shortcuts for TModel without introducing persistence attributes.

  • FoundginePersistenceConfiguration<TEntity> abstract class Semantic/Configuration/FoundginePersistenceConfiguration.cs

    Configures physical storage structure for TEntity: database schema, table name (ToTable), primary keys (HasKey), column names (HasColumnName), nullability, and storage constraints.

  • FoundgineEntityMap<TModel, TEntity> abstract class Semantic/Configuration/FoundgineEntityMap.cs

    Explicitly maps semantic model properties to physical storage entity properties, keeping domain types decoupled from legacy database column layouts (paired with FoundgineIdentityEntityMap<T> when shapes match).

  • FoundgineConnectionConfiguration abstract class Semantic/Configuration/FoundgineConnectionConfiguration.cs

    Binds semantic relationships between source and target entities to physical foreign-key columns (HasRelationship<TSource, TTarget>().Using<...>().HasForeignKey(...)).

  • MetadataRegistry sealed class Semantic/Metadata/MetadataRegistry.cs

    Immutable, deterministic catalog of validated EntityMetadata, FieldMetadata, RelationshipMetadata, and persistence mappings with a canonical SHA-256 contract fingerprint.

▶ Semantic/Intent/, Semantic/Query/ & Semantic/Lexical/ Typed/dynamic/fluent query builders, operation graph assembly, and fail-closed lexical grounding.
  • SemanticQuery sealed class Semantic/Query/SemanticQuery.cs

    Parity-verified fluent read builder (SemanticQuery.From(metadata, root)) that constructs a canonical SemanticOperation with projections, predicates, sorting, pagination, and nested relationship includes.

  • SemanticOperationGraph sealed class Semantic/Intent/SemanticOperationGraph.cs

    Canonical security and planning unit for read operations. Expands logical traversal paths into explicit intermediate entity nodes and relationship edges so authorization evaluates every traversed hop.

  • SemanticMutationIntentBuilder sealed class Semantic/Mutation/SemanticMutationIntentBuilder.cs

    Fluent builder for multi-step semantic writes (Create, Update, Delete) supporting cross-operation generated key bindings via SetFrom and compiling into a SemanticMutationOperationGraph.

  • SemanticLexicalResolver sealed class Semantic/Lexical/SemanticLexicalResolver.cs

    Resolves free-form vocabulary expressions against the semantic model under strict token, path, and timeout budgets; returns GroundingDecision (Committed, RequiresClarification, Unresolved, or BudgetExceeded) and never guesses under ambiguity.

  • ISemanticLexicalCandidateSource interface Semantic/Lexical/ISemanticLexicalCandidateSource.cs

    Non-authoritative vocabulary retrieval boundary used to propose candidate entities, fields, and aliases for lexical grounding without granting execution authority.

▶ Planning/, Execution/ & Security/ Tamper-evident plan binding, provider-neutral ExecutionIR, cryptographic warrants, and structural guards.
  • SemanticPlanner sealed class Planning/SemanticPlanner.cs

    Transforms an authorized SemanticOperationGraph into a logical SemanticPlan carrying an immutable SemanticPlanAuthorizationBinding tied to the frozen contract and authorization decision fingerprints.

  • ExecutionIRCompiler sealed class Execution/ExecutionIRCompiler.cs

    Compiles a bound SemanticPlan into provider-neutral ExecutionIR (scans, joins, lowered authorization row predicates, projections, sorts, and cursor bounds). Refuses unbound or tampered plans.

  • SemanticPlanAuthorizationBinding sealed record Planning/SemanticPlanAuthorizationBinding.cs

    Immutable cryptographic provenance record attached to SemanticPlan capturing the frozen MetadataRegistry SHA-256 fingerprint, principal/tenant context digest, and authorization policy decision hash. Prevents plan-rewrite privilege escalation.

  • ExecutionIR sealed record Execution/ExecutionIR.cs

    Provider-neutral intermediate representation encoding relational/graph scans, join topologies, injected row-level security predicates, authorized field projections, deterministic tie-breaker sorts, and pagination bounds.

  • SecurityExecutionContext sealed record Security/SecurityExecutionContext.cs

    Host-owned security envelope carrying authenticated principal identity, tenant ID, roles, scopes, optional cryptographic warrant, and root-to-leaf delegation chain.

  • IExecutionProvider / IMutationExecutionProvider interfaces Execution/IExecutionProvider.cs

    Core storage provider Service Provider Interfaces accepting bound ExecutionIR trees and security proofs to materialize authorized read rows or transactional write receipts.

  • ScanNode / JoinNode / PredicateFilterNode / ProjectionNode / SortNode sealed records Execution/IR/ExecutionIRNodes.cs

    Algebraic intermediate representation nodes emitted by ExecutionIRCompiler separating logical query semantics from dialect SQL or ORM query translation.

  • SemanticAuthorizationDecision / SemanticFilter sealed records Security/SemanticAuthorizationDecision.cs

    Encapsulates policy allow/deny outcomes, allowed field projections, and provider-independent row-level predicate trees lowered into SQL WHERE or ORM filters.

  • SecurityResourceLimits sealed record Security/SecurityResourceLimits.cs

    Engine-enforced structural bounds guarding against query/mutation DoS (max selection depth 32, selection nodes 256, filter depth 32, graph nodes 256, page size 1,000, mutation batch 128).

▶ src/csharp/Foundgine.Runtime/ Execution Boundary End-to-end read and mutation execution engines, warrant verification, replay/revocation enforcement, and durable audit.
  • IFoundgineExecutor / FoundgineEngine interface / class Execution/FoundgineEngine.cs

    Primary runtime entry point orchestrating the 12-stage canonical lifecycle: intent normalization, operation graph expansion, authorization, plan binding, ExecutionIR compilation, provider dispatch, and receipt emission.

  • SemanticMutationEngine sealed class Mutation/SemanticMutationEngine.cs

    Governs the multi-stage write pipeline (DryRunAsync, ApproveAsync, ExecuteApprovedAsync), enforcing cryptographic plan-fingerprint approval binding, single-use replay nonces, and pre/post revocation checks.

  • ISemanticAuthorizationPolicy interface Authorization/ISemanticAuthorizationPolicy.cs

    Host-implemented authorization policy evaluating entity, field, and relationship permissions and emitting provider-independent row-level filter predicates into the logical plan.

  • AnchoredSecurityWarrantRevocationStore sealed class Security/AnchoredSecurityWarrantRevocationStore.cs

    Combines low-latency distributed revocation checks (e.g., Redis) with a durable monotonic database epoch anchor (e.g., PostgreSQL GREATEST), failing closed if cache state lags or disconnects.

  • BufferedDurableAuditLog sealed class Audit/BufferedDurableAuditLog.cs

    Bounded, lossless asynchronous audit writer persisting signed ExecutionReceipt and mutation approval evidence to durable storage with configurable fail-closed backpressure.

  • FoundgineOpenTelemetryExtensions static class Diagnostics/FoundgineOpenTelemetryExtensions.cs

    Registers ActivitySource("Foundgine") distributed tracing spans and runtime execution/security metrics with automatic PII and token redaction.

  • FoundgineGateway sealed class Gateway/FoundgineGateway.cs

    Transport-neutral execution and approval gateway supporting atomic approval commits, encrypted approval envelopes (AES-256-GCM), and outbox evidence.

▶ src/csharp/Foundgine.Providers/ Providers & Generators SQL/ADO.NET, EF Core, InMemory, Redis, Elasticsearch, pgvector, Postgres Retrieval, MCP server, MAF, and Roslyn AOT/ORM generators.
  • SqlExecutionProvider / SqlMutationExecutionProvider sealed class Storage/Sql/

    Compiles authorized ExecutionIR into parameterized dialect SQL (PostgreSQL, SQLite, SQL Server) with deterministic tie-breaker pagination, plan-cache fingerprint isolation, and batched transactional writes.

  • PostgresSqlDialect / SqliteSqlDialect / SqlServerSqlDialect sealed classes Storage/Sql/Dialects/

    Dialect-specific SQL emitters translating canonical ExecutionIR nodes into parameterized PostgreSQL, SQLite, or T-SQL statements with dialect-native pagination, identifier quoting, and batching.

  • StaticWarrantIssuerTrustResolver / AesGcmEnvelopeKeyRing sealed classes Security/Warrants/ & Gateway/

    Manages multi-kid asymmetric public key sets for zero-downtime warrant rotation and versioned AES-256-GCM symmetric key rings with tenant/plan AAD binding.

  • FoundgineWarrantIssuer / SecurityWarrantVerifier sealed classes Security/Warrants/

    Mints and verifies asymmetric-signed cryptographic warrants (iss, aud, sub, tid, jti, rev_seq, contract_fp) and validates root-to-leaf delegation attenuation chains.

  • FoundgineEfReader / FoundgineRepository<T> sealed class EntityFrameworkCore/

    Translates authorized ExecutionIR onto an existing EF Core DbContext via IQueryable projections and mandatory root/child permission predicates, preserving entity mappings and value converters.

  • PostgresRetrievalCandidateSource sealed class Storage/Postgres/PostgresRetrievalCandidateSource.cs

    Implements IApproximateCandidateSource for row-level candidate discovery across PostgreSQL pg_trgm fuzzy matching, native tsvector full-text search, optional ParadeDB pg_search BM25, and optional Apache AGE graph similarity.

  • ElasticsearchSemanticLexicalCandidateSource / PgVectorSemanticLexicalCandidateSource sealed class Storage/Elasticsearch/ & Storage/PostgresVector/

    Interchangeable vocabulary grounding candidate sources using Elasticsearch BM25/fuzzy queries or PostgreSQL pgvector similarity search over embedded semantic metadata.

  • RedisSecurityWarrantReplayStore / RedisSecurityWarrantRevocationStore sealed class Redis/

    Distributed Lua-scripted single-use warrant nonce replay prevention and monotonic revocation sequence store for Redis, Valkey, and Garnet clusters.

  • FoundgineMcpHttpEndpoint / FoundgineMcpToolRegistry sealed class Mcp/

    Implements MCP Streamable HTTP (2025-06-18) exposing the six bounded tools (foundgine_capabilities, foundgine_query, foundgine_query_semantic, and dry-run/approve/execute mutation tools) with RSA-2048+ fgmcp1 signed approval tokens.

  • FoundgineAgentFrameworkExtensions static class AgentFramework/Hosting/

    Registers Microsoft Agent Framework (AIAgent) toolsets via AddFoundgineAgentFramework, wrapping write execution in ApprovalRequiredAIFunction while withholding approval issuance from the LLM.

  • PostgresEventStore / PostgresOutbox / BufferedDurableAuditLog sealed class Storage/Postgres/

    Transactional event store, outbox dispatcher (FOR UPDATE SKIP LOCKED), and lossless durable audit log persisting signed ExecutionReceipt and mutation approval records alongside business transactions.

  • InMemoryExecutionProvider / InMemoryMutationExecutionProvider sealed class Storage/InMemory/

    Deterministic in-process execution providers honoring the exact same ExecutionIR predicates, tie-breaker sorts, and transactional rollback semantics as SQL/EF Core for fast unit testing.

  • FoundgineAotSourceGenerator / FoundgineOrmSourceGenerator IIncrementalGenerator Aot.Generator/ & Orm.Generator/

    Roslyn incremental compile-time source generators emitting reflection-free MetadataRegistry builders and typed EF Core entity maps for Native AOT deployments.

▶ src/csharp/Foundgine.Extensions/ Protocol & Host Adapters Hot Chocolate GraphQL, fail-closed GraphQL HTTP, Keycloak OIDC warrant minting, and Temporal durable workflows.
  • FoundgineGraphQLEndpointRouteBuilderExtensions static class GraphQL.Http/

    Provides MapFoundgineGraphQL, mounting a fail-closed POST /graphql adapter with explicit QueryRootRoles allowlists, request-scoped JWT context extraction, and GraphQL error mapping.

  • KeycloakSecurityExecutionContextProvider sealed class Keycloak/

    Validates Keycloak OIDC/JWKS tokens and maps verified claims into a host-owned SecurityExecutionContext and short-lived cryptographic Foundgine warrant.

  • FoundgineTemporalOutboxPublisher / FoundgineTemporalWorkflowEndpoints sealed class Temporal/

    Bridges transactional PostgresOutbox events to Temporal workflows and exposes /foundgine/workflows control routes while re-minting fresh authority inside each Temporal activity.

▶ src/csharp/samples/ Runnable reference apps: Foundgine.Comparison, Foundgine.SupplyChain.Advanced, Foundgine.RedTeam, and AgentEndToEnd.
▶ src/java/ Java 27 · Maven Multi-module Java 27 reactor (io.github.cristianbarragan) with full semantic, security, provider, extension, migration, and AOT parity.
▶ src/java/foundgine-core/ Core Contract Package com.foundgine.core — fluent model configuration, MetadataRegistry, SemanticQuery, lexical resolver, planner, ExecutionIR, and security models.
  • FoundgineModel / FoundgineModelConfiguration<T> abstract class com.foundgine.core.semantic.configuration

    Java fluent model registrar and entity/persistence/connection configuration builders compiling to an immutable, fingerprinted MetadataRegistry via build().

  • SemanticQuery final class com.foundgine.core.semantic.query.SemanticQuery

    Cross-language parity-verified fluent query builder (SemanticQuery.from(metadata, root)) producing canonical SemanticOperation trees.

  • SemanticPlanner / ExecutionIRCompiler final class com.foundgine.core.planning & .execution

    Compiles authorized SemanticOperationGraph instances into bound SemanticPlan and provider-neutral ExecutionIR trees with automatic primary-key tie-breaker sorting.

  • SecurityExecutionContext / SecurityResourceLimits record com.foundgine.core.security

    Immutable Java 27 records carrying host-authenticated principal/tenant claims, cryptographic warrant delegation chains, and structural DoS resource limits.

  • SemanticLexicalResolver final class com.foundgine.core.semantic.lexical.SemanticLexicalResolver

    Bounded lexical grounding engine (ground(...)) enforcing fail-closed ambiguity handling (GroundingOutcome.REQUIRES_CLARIFICATION) and token/path/timeout budgets.

▶ src/java/foundgine-runtime/ Execution Boundary Package com.foundgine.runtime — FoundgineEngine, mutation governance, warrant/delegation verification, and durable audit logging.
  • FoundgineEngine / SemanticMutationEngine final class com.foundgine.runtime.execution

    Java runtime orchestrator enforcing plan-binding verification, row-level predicate injection, warrant replay/revocation checks, and cryptographic execution receipts.

▶ src/java/foundgine-providers/ Providers & Frameworks Package com.foundgine.providers — JDBC SQL, JPA ORM (JpaEntities, JpaOrmProvider), InMemory, Redis, MCP server, LangChain4j, Spring Boot AutoConfig, and retrieval providers.
  • JpaEntities / JpaOrmProvider final class com.foundgine.providers.storage.orm.jpa

    Translates authorized ExecutionIR into JPA Criteria queries against an existing EntityManager with mandatory ReadGate authorization checks.

  • JdbcSqlExecutionProvider / JdbcSqlMutationProvider final class com.foundgine.providers.storage.sql

    Compiles authorized ExecutionIR into parameterized JDBC SQL queries and batched transactional mutations with deterministic tie-breaker sorting and fingerprint-keyed plan caching.

  • PostgresRetrievalCandidateSource final class com.foundgine.providers.storage.postgres

    Java implementation of IApproximateCandidateSource supporting PostgreSQL pg_trgm trigram similarity, tsvector full-text search, optional ParadeDB pg_search BM25, and optional Apache AGE graph similarity.

  • FoundgineMcpAutoConfiguration @AutoConfiguration com.foundgine.providers.springboot

    Spring Boot auto-configuration wiring FoundgineMcpServer onto foundgine.mcp.path (default /mcp, disabled by default) with origin allowlist validation and Spring Security context bridging.

  • FoundgineMcpServer / FoundgineLangChain4jTools final class com.foundgine.providers.mcp & .langchain4j

    Exposes Foundgine's six governed MCP tools over HTTP and adapts them into LangChain4j AiServices tool maps with signed fgmcp1 write approvals.

▶ src/java/foundgine-extensions/, foundgine-migrations/, foundgine-aot-generator/ Adapters & Tooling GraphQL Java, Keycloak, Temporal extensions, Flyway schema diff CLI (MigrationsCli), and compile-time annotation processor (FoundgineAotProcessor).
  • FoundgineGraphQlRuntimeWiring / KeycloakContextProvider / TemporalWorkflowBridge extensions com.foundgine.extensions.{graphql,keycloak,temporal}

    Protocol and host adapters wiring GraphQL Java data fetchers, Keycloak OIDC/JWKS token verification, and Temporal workflow orchestration with per-activity warrant re-minting.

  • MigrationsCli final class com.foundgine.migrations.MigrationsCli

    CLI tool that diffs a compiled MetadataRegistry against database snapshots to generate deterministic Flyway-compatible SQL migration scripts.

  • FoundgineAotProcessor Processor com.foundgine.aot.FoundgineAotProcessor

    Java javax.annotation.processing.Processor scanning @FoundgineModel and @FoundgineModelEntityMap to generate reflection-free GeneratedFoundgineMetadata at build time.

▶ src/typescript/, src/python/, src/wasm/ Thin Client SDKs Zero-authority transport SDKs speaking MCP Streamable HTTP (/mcp) and Temporal workflow routes (/foundgine/workflows).
  • FoundgineClient @foundgine/typescript src/typescript/src/client.ts

    Zero-dependency Node 20+ / Fetch API client managing MCP sessions, bearer token callbacks, SSE replay, and workflow lifecycle calls.

  • FoundgineClient / SyncFoundgineClient foundgine (PyPI) src/python/src/foundgine/client.py

    Python 3.11+ async and sync httpx clients with typed tool wrappers and structured MCP error propagation.

  • FoundgineMcpError / FoundgineWorkflowClient SDK Internals src/{typescript,python,wasm}/

    Typed JSON-RPC/HTTP error wrappers, exponential retry/abort signal handlers, and Temporal workflow lifecycle helpers (listProcesses, describe, start, status, decide, cancel) shared identically across TypeScript, Python, and Rust/WASM.

  • FoundgineClient (Rust + wasm-bindgen) @foundgine/wasm src/wasm/src/lib.rs

    Pure-Rust sans-I/O MCP/workflow protocol state machine compiled to WebAssembly for browsers, Cloudflare Workers, Deno, and Node.

▶ src/conformance/, benchmarks/, docs/, docs-site/, tools/ Governance & Evidence Cross-language parity vectors, closed-loop benchmark harnesses, canonical specification docs, machine-readable discovery files, and repo indexing scripts.
  • semantic-query-vectors.json Conformance src/conformance/semantic-query-vectors.json

    Shared JSON test vectors verifying that C# and Java SemanticQuery builders emit byte-for-byte identical canonical operations.

  • generate-repo-index.py Tooling tools/generate-repo-index.py

    Regenerates repo-index.json and REPO-MAP.md from repository source files and XML/Javadoc comments.

Deployment Topologies, Ecosystem Comparison & Wire Schemas

Foundgine scales incrementally from a single in-process application library with zero external infrastructure up to a horizontally scaled, multi-protocol enterprise execution hub.

Three Production Deployment Topologies

Tier 1 · Embedded Domain Core

Stack: Foundgine.Core + Runtime + EF Core / JPA + PostgreSQL (or SQLite).

  • Zero AI, MCP, GraphQL, or Redis dependencies required.
  • Replaces scattered repository/service authorization checks with centralized FoundgineModel + row-level predicates.
  • Compile-time AOT generators eliminate startup reflection overhead.

Tier 2 · Multi-Surface API & Agent Gateway

Stack: Tier 1 + Hot Chocolate / GraphQL Java + MCP Streamable HTTP + Keycloak + Redis.

  • Exposes identical domain rules across GraphQL (/graphql), MCP (/mcp), and MAF / LangChain4j agent loops.
  • AnchoredSecurityWarrantRevocationStore (Redis + PostgreSQL GREATEST epoch) guarantees cluster-wide single-use replay protection and instant revocation.

Tier 3 · Durable Saga & Regulated Enterprise Hub

Stack: Tier 2 + PostgresEventStore + PostgresOutbox + Temporal + BufferedDurableAuditLog.

  • Transactional outbox triggers Temporal workflows atomically with business writes; activities re-mint short-lived host warrants per step.
  • Human-in-the-loop mutation approvals (fgmcp1) and AES-256-GCM encrypted gateway envelopes produce immutable audit receipts.

Architectural Comparison Across the Ecosystem

Capability Foundgine (v3.4.2) Direct MCP / Tool Wrappers Semantic Kernel / LangChain Plain GraphQL + ORM
Primary Center of Gravity Application-owned semantic & execution boundary Transport protocol for LLM tool calls LLM prompt/chain orchestration loop HTTP GraphQL schema & resolver tree
Row & Field Security Enforcement Lowered directly into SQL WHERE / ORM projections via bound ExecutionIR Left entirely to custom tool handler code Left entirely to custom plugin/tool code Distributed across resolvers/middleware
Ambiguous Natural-Language Intent Fails closed (RequiresClarification) with competing signatures Relies on LLM prompt heuristics Relies on LLM prompt heuristics Not applicable (strict typed schema)
Multi-Step Write Governance DryRun → SHA-256 PlanFingerprint → signed approval → nonce replay check Ad-hoc confirmation flags Framework-specific human-in-the-loop callbacks Custom mutation endpoints
Dual-Runtime Parity (.NET & Java) Shared fluent model, AOT generators & JSON conformance vectors SDK-only protocol parity Separate architectures (.NET SK vs. Python/Java) Separate ecosystems (HC vs. GraphQL Java)

Canonical Wire Payloads & Cryptographic Receipt Schemas

HTTP POST /mcp — JSON-RPC 2.0 Tool Call (2025-06-18)
POST /mcp HTTP/1.1
Authorization: Bearer <host-oidc-or-warrant-token>
Content-Type: application/json
Accept: application/json, text/event-stream

{
  "jsonrpc": "2.0",
  "id": "req-402",
  "method": "tools/call",
  "params": {
    "name": "foundgine_query",
    "arguments": {
      "expression": "active customers"
    }
  }
}
Fail-Closed Ambiguity Response (RequiresClarification)
{
  "jsonrpc": "2.0",
  "id": "req-402",
  "result": {
    "isError": true,
    "structuredContent": {
      "outcome": "RequiresClarification",
      "committed": null,
      "reason": "Expression 'active customers' maps to 2 distinct semantic signatures.",
      "competingInterpretations": [
        { "signature": "Customer[AccountEnabled == true]", "weight": 90 },
        { "signature": "Customer[Some(orders, PlacedWithinDays <= 90)]", "weight": 85 }
      ]
    }
  }
}
Immutable ExecutionReceipt & Audit Provenance Record (Stage 12)
{
  "receiptId": "rcpt_01JDF8W9K2M4N7P8Q1R3S5T6V7",
  "executedAtUtc": "2026-11-26T06:15:00.142Z",
  "principal": {
    "subject": "user:alice@acme.example",
    "tenantId": "tenant-nz-01",
    "warrantId": "wrt_9f82c1a4",
    "delegationDepth": 1
  },
  "provenance": {
    "contractFingerprint": "sha256:8f4e2b91c0d7...a19c",
    "authorizationDecisionFingerprint": "sha256:3c71a904e5b2...77d0",
    "planFingerprint": "sha256:6b12f883d9e1...40e8",
    "executionIrFingerprint": "sha256:1a94c552f0b8...92f1"
  },
  "provider": {
    "name": "SqlExecutionProvider",
    "dialect": "PostgreSQL",
    "planCacheHit": true,
    "rowsReturned": 24
  }
}
.NET 10 CLI — NuGet Package Installation (v3.4.2)
dotnet add package Foundgine.Core --version 3.4.2
dotnet add package Foundgine.Runtime --version 3.4.2
dotnet add package Foundgine.Providers --version 3.4.2
dotnet add package Foundgine.Extensions --version 3.4.2
Java 27 — Maven pom.xml Dependencies (v3.4.2)
<dependency>
  <groupId>io.github.cristianbarragan</groupId>
  <artifactId>foundgine-core</artifactId>
  <version>3.4.2</version>
</dependency>
<dependency>
  <groupId>io.github.cristianbarragan</groupId>
  <artifactId>foundgine-runtime</artifactId>
  <version>3.4.2</version>
</dependency>
<dependency>
  <groupId>io.github.cristianbarragan</groupId>
  <artifactId>foundgine-providers</artifactId>
  <version>3.4.2</version>
</dependency>
<dependency>
  <groupId>io.github.cristianbarragan</groupId>
  <artifactId>foundgine-extensions</artifactId>
  <version>3.4.2</version>
</dependency>

Event Sourcing, Transactional Outbox, Gateway & Observability

Beyond synchronous read and mutation execution, Foundgine provides durable event persistence, transactional outbox dispatch, encrypted approval gateways, and native OpenTelemetry instrumentation—all governed by the same frozen semantic contract and host-owned security boundary.

1. Event Store & Optimistic Concurrency (PostgresEventStore)

Appends immutable domain and governance EventEnvelope records into PostgreSQL streams with strict per-stream sequence numbers and optimistic concurrency checks (ExpectedVersion). Supports stream replay, causal correlation IDs (CorrelationId / CausationId), and principal provenance metadata.

2. Transactional Outbox (PostgresOutbox)

Writes outbound integration messages into the outbox table inside the exact same database transaction as the business entity mutation. Background workers claim batches via FOR UPDATE SKIP LOCKED, enforce idempotency keys, apply exponential retry backoff, and quarantine poison messages to a dead-letter partition.

3. Encrypted Gateway Approvals (FoundgineGateway)

Provides a transport-neutral facade for high-assurance workflows where mutation proposals are persisted in PostgresFoundgineGatewayApprovalStore using AES-256-GCM authenticated encryption (key-versioned with AAD bound to tenant and plan fingerprint) until an authorized human or policy engine approves dispatch.

4. OpenTelemetry & Lossless Audit (BufferedDurableAuditLog)

Emits distributed traces (ActivitySource("Foundgine") / OpenTelemetry Java SDK) and histograms across every pipeline stage without leaking sensitive row values or raw tokens. BufferedDurableAuditLog batches signed ExecutionReceipt records with bounded backpressure so audit evidence is never silently dropped.

C# (.NET 10) — Transactional Outbox & Event Store Configuration
using Foundgine.Providers.Storage.Postgres;

// Register PostgreSQL Event Store, Transactional Outbox & Durable Audit Log
builder.Services.AddFoundginePostgresPersistence(pg =>
{
    pg.ConnectionString = configuration.GetConnectionString("FoundgineDb")!;
    pg.EnableEventStore = true;
    pg.EnableOutbox = true;
    pg.OutboxBatchSize = 64;
    pg.OutboxMaxAttempts = 8;
    pg.EnableDurableAuditLog = true;
    pg.AuditFlushInterval = TimeSpan.FromMilliseconds(250);
});

// Outbox rows commit atomically alongside SemanticMutationEngine SQL/EF Core writes,
// then dispatch via FOR UPDATE SKIP LOCKED to Temporal, Kafka, or HTTP webhooks.
C# (.NET 10) — Encrypted Gateway Approval Envelope (AES-256-GCM)
using Foundgine.Runtime.Gateway;
using Foundgine.Providers.Storage.Postgres;

// Encrypt stored mutation proposals at rest with key-ring rotation & AAD binding
var keyRing = new AesGcmEnvelopeKeyRing(
    activeKeyId: "kek-2026-11",
    keys: new Dictionary<string, byte[]>
    {
        ["kek-2026-11"] = Convert.FromBase64String(secretBase64)
    });

builder.Services.AddSingleton<IFoundgineGatewayApprovalStore>(sp =>
    new PostgresFoundgineGatewayApprovalStore(pgDataSource, keyRing));
Telemetry Signal Name / Instrument Recorded Attributes (PII-Safe)
Trace Span foundgine.execute / foundgine.mutation foundgine.operation.kind, foundgine.root_entity, foundgine.contract_fp, foundgine.tenant_id
Trace Span foundgine.lexical.ground foundgine.grounding.outcome, foundgine.tokens.count, foundgine.paths.explored
Trace Span foundgine.security.authorize foundgine.auth.decision, foundgine.warrant.present, foundgine.delegation.depth
Histogram foundgine.execution.duration_ms Tags: provider (sql, efcore, jpa), plan_cache_hit, outcome
Counter foundgine.security.denials_total Tags: reason (replay, revoked, scope, limit_exceeded, unbound_plan)

Runtime Configuration Options & Fail-Closed Error Catalog

Every Foundgine runtime exposes deterministic configuration switches and typed exception/error categories so host gateways, GraphQL adapters, and MCP clients can distinguish transient infrastructure faults from security rejections or ambiguous user intent.

Core Runtime Configuration Switches (FoundgineOptions / FoundgineEngineConfig)

Option / Setting Default Security & Runtime Behavior
RequireSignedWarrants false (direct host code) / true (gateway/MCP) When enabled, rejects any SecurityExecutionContext lacking a verified cryptographic warrant from a trusted root issuer.
MinimumAliasWeight 75 (range 1..100) Minimum lexical evidence score required before SemanticLexicalResolver can commit an alias match without asking for clarification.
LexicalBudget 32 tokens · 5,000 paths · 250ms Caps search work per grounding call; exceeding any bound aborts with GroundingOutcome.BudgetExceeded.
EnablePlanCaching true Caches compiled SQL/ORM shapes keyed by full SemanticPlanAuthorizationBinding fingerprint (never shares plans across differing predicates).
ResourceLimits SecurityResourceLimits.Default Enforces structural ceilings on selection depth (32), nodes (256), filter depth (32), page size (1,000), and mutation batch size (128).
FailClosedOnAuditBackpressure true Refuses to commit mutations if BufferedDurableAuditLog cannot persist the corresponding signed execution receipt.

Canonical Fail-Closed Error & Rejection Catalog

Error / Outcome Type HTTP / MCP Status Trigger Condition Recommended Caller Action
GroundingOutcome.RequiresClarification 200 (MCP isError: true) Free-form query matched ≥2 distinct semantic signatures or fell below MinimumAliasWeight. Present CompetingInterpretations to the user or re-submit structured foundgine_query_semantic.
GroundingOutcome.Unresolved 400 / 422 Unknown entity/field token or unmodeled subjective term (e.g., "big"). Inspect Reason for the exact unresolved token and map it to a modeled field or alias.
SecurityAuthorizationException 403 Forbidden Missing entity/field/hop permission, invalid issuer/audience, or empty authorized projection set. Do not retry with widened arguments; request an appropriately scoped host token/warrant.
WarrantReplayDetectedException 403 Forbidden Single-use warrant jti nonce or fgmcp1 approval token was already consumed. Re-run dry-run and obtain a fresh single-use approval/warrant from the host authority.
PlanBindingTamperedException 403 / 409 Conflict MetadataRegistry contract fingerprint or plan digest drifted between planning/dry-run and execution. Discard cached plan/approval and re-plan against the current frozen MetadataRegistry.
ResourceLimitExceededException 400 / 413 Query or mutation exceeded SecurityResourceLimits (depth, node count, page size, cursor length). Reduce selection depth, split batch mutations, or paginate with smaller Take/limit.

Benchmark Evidence, Adversarial Testing & Package Coordinates

1. Architectural Comparison: Foundgine vs. Conventional Hot Chocolate + EF Core

In src/csharp/samples/Foundgine.Comparison, both arms run against an identical legacy PostgreSQL schema (tbl_customer, tbl_order.ord_total, tbl_order_line.qty) and identical HS256 JWT tokens:

Dimension Foundgine.Shop (Foundgine + Hot Chocolate + EF) HotChocolate.Shop (Plain Hot Chocolate + EF)
Where Rules Live Centralized in ShopModel and ShopAuthorizationPolicy; Hot Chocolate is a thin adapter. Inside GraphQL resolvers and EF IQueryable projections.
Adding a 2nd Protocol (MCP) ~15 lines (ShopMcp.cs) exposing /mcp with identical row-level security and zero duplicated rules. Requires extracting a separate service/authorization layer or duplicating claim-filtering logic.
Sample Code Footprint 234 non-blank, non-comment C# lines (pays off across multi-surface deployments). 113 non-blank, non-comment C# lines (more concise when GraphQL is the sole interface).

2. Preliminary Closed-Loop Throughput & Latency (SupplyChain C# Arm)

Recorded preliminary run (sc-cs-orders-customer, single read query salesOrder(first: 50) with lines and shipments; status: preliminary, not claim-grade) quantifying the per-request semantic planning/warrant boundary cost versus direct Hot Chocolate + EF projection:

Concurrency Foundgine RPS Foundgine p99 Baseline (HC + EF) RPS Baseline p99 Notes
1 111 rps 15.8 ms 254 rps 8.7 ms Reflects semantic intent translation, warrant check & plan compilation overhead.
8 354 rps 44.3 ms 1,086 rps 16.0 ms Both cells valid.
16 509 rps 52.9 ms 1,245 rps 31.8 ms Foundgine approaches single-container CPU plateau (~510–522 rps).
32 522 rps 112.5 ms 369 rps (invalid) 154.6 ms Foundgine valid; baseline failed validation gate at c=32.

3. Adversarial Red-Team & Penetration Suites

  • Recorded Red-Team Run (Foundgine.RedTeam vs. Foundgine.SupplyChain.Advanced): Across 18 MCP requests (11 semantic API, 7 execution API), both legitimate baselines succeeded (2/2) and 100% of adversarial attempts (15/15 attacks + 1 unauthenticated call)—including cross-tenant probes, identity claim spoofing, scope: * widening, cross-customer order reads, and role escalation—were blocked fail-closed.
  • Deterministic PenTest Suites: 14 deterministic penetration test cases (7 MCP + 7 GraphQL) in AgentEndToEnd/Fixtures/SupplyChain.PenTest plus cross-language conformance vectors in src/conformance/.

5. Cross-Language Conformance Harness & Deterministic Testing

Foundgine enforces behavioral equivalence between .NET 10 and Java 27 through shared JSON conformance suites under src/conformance/ executed in CI on every commit:

Shared Conformance Suites (src/conformance/)

  • semantic-query-vectors.json — Verifies identical canonical SemanticOperation ASTs from C# and Java SemanticQuery builders.
  • lexical-grounding-vectors.json — Validates identical Committed, RequiresClarification, Unresolved, and BudgetExceeded decisions under matching budgets.
  • security-limits-vectors.json — Asserts identical rejection thresholds across selection depth, graph nodes, filter depth, and mutation batch bounds.

Deterministic In-Process Test Doubles

  • InMemoryExecutionProvider / InMemoryMutationExecutionProvider — Executes full ExecutionIR plans with row-level predicates, joins, tie-breaker sorting, and atomic rollback without external databases.
  • InMemorySecurityWarrantReplayStore & InMemorySecurityWarrantRevocationStore — Deterministic single-use nonce and revocation epoch testing in milliseconds.

4. Primary Package Artifacts (v3.4.2)

.NET 10 (NuGet)

  • Foundgine.Core — semantic model, metadata, intent, planning, security contracts
  • Foundgine.Runtime — orchestration, authorization, warrants, control plane
  • Foundgine.Providers — SQL, EF Core, InMemory, Redis, MAF, pgvector, Elasticsearch, MCP, AOT & ORM generators
  • Foundgine.Extensions — Hot Chocolate GraphQL, GraphQL HTTP, Keycloak, Temporal

Java 27 (Maven · io.github.cristianbarragan)

  • foundgine-core — semantic model, metadata, intent, planning, lexical resolver
  • foundgine-runtime — runtime orchestration, warrant revalidation, governance
  • foundgine-providers — SQL, InMemory, JPA, MCP, Redis, Spring Boot, LangChain4j, retrieval
  • foundgine-extensions & foundgine-migrations — GraphQL Java, Keycloak, Temporal, Flyway schema CLI

Database Schema, DDL Internals & Migration Lifecycle

While Foundgine leaves your domain tables untouched, its optional durability and distributed governance adapters (PostgresEventStore, PostgresOutbox, BufferedDurableAuditLog, PostgresSecurityWarrantRevocationEpochAnchor, and PostgresFoundgineGatewayApprovalStore) use compact, indexed PostgreSQL schemas designed for high-concurrency lock-free claiming and monotonic consistency.

PostgreSQL DDL — Transactional Outbox (SKIP LOCKED) & Lossless Audit Log
CREATE TABLE IF NOT EXISTS foundgine_outbox (
    outbox_id        UUID PRIMARY KEY,
    idempotency_key  TEXT NOT NULL UNIQUE,
    topic            TEXT NOT NULL,
    tenant_id        TEXT NOT NULL,
    correlation_id   TEXT NOT NULL,
    payload_json     JSONB NOT NULL,
    created_at_utc   TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    available_at_utc TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    attempts         INT NOT NULL DEFAULT 0,
    dispatched_at    TIMESTAMPTZ NULL,
    dead_lettered_at TIMESTAMPTZ NULL,
    last_error       TEXT NULL
);
CREATE INDEX IF NOT EXISTS ix_foundgine_outbox_pending
    ON foundgine_outbox (available_at_utc, created_at_utc)
    WHERE dispatched_at IS NULL AND dead_lettered_at IS NULL;

CREATE TABLE IF NOT EXISTS foundgine_audit_receipts (
    receipt_id          TEXT PRIMARY KEY,
    executed_at_utc     TIMESTAMPTZ NOT NULL,
    tenant_id           TEXT NOT NULL,
    subject_id          TEXT NOT NULL,
    warrant_id          TEXT NULL,
    contract_fp         TEXT NOT NULL,
    plan_fp             TEXT NOT NULL,
    execution_ir_fp     TEXT NOT NULL,
    operation_kind      TEXT NOT NULL,
    root_entity         TEXT NOT NULL,
    rows_affected       INT NOT NULL,
    receipt_payload     JSONB NOT NULL
);
PostgreSQL DDL — Monotonic Revocation Anchor & Encrypted Gateway Approvals
-- Monotonic GREATEST epoch anchor preventing Redis cache lag from resurrecting revoked warrants
CREATE TABLE IF NOT EXISTS foundgine_warrant_revocation_anchor (
    issuer_id        TEXT PRIMARY KEY,
    revocation_epoch BIGINT NOT NULL,
    updated_at_utc   TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Atomic upsert advancing epoch monotonically:
-- INSERT INTO foundgine_warrant_revocation_anchor (issuer_id, revocation_epoch)
-- VALUES ($1, $2)
-- ON CONFLICT (issuer_id) DO UPDATE
-- SET revocation_epoch = GREATEST(foundgine_warrant_revocation_anchor.revocation_epoch, EXCLUDED.revocation_epoch),
--     updated_at_utc = NOW();

CREATE TABLE IF NOT EXISTS foundgine_gateway_approvals (
    approval_id      UUID PRIMARY KEY,
    tenant_id        TEXT NOT NULL,
    plan_fingerprint TEXT NOT NULL,
    key_id           TEXT NOT NULL,
    nonce_iv         BYTEA NOT NULL,
    ciphertext       BYTEA NOT NULL,
    auth_tag         BYTEA NOT NULL,
    expires_at_utc   TIMESTAMPTZ NOT NULL,
    consumed_at_utc  TIMESTAMPTZ NULL
);
PostgreSQL DDL — Optimistic-Concurrency Event Store
CREATE TABLE IF NOT EXISTS foundgine_events (
    global_position  BIGSERIAL PRIMARY KEY,
    stream_id        TEXT NOT NULL,
    stream_version   BIGINT NOT NULL,
    event_id         UUID NOT NULL UNIQUE,
    event_type       TEXT NOT NULL,
    tenant_id        TEXT NOT NULL,
    correlation_id   TEXT NOT NULL,
    causation_id     TEXT NULL,
    metadata_json    JSONB NOT NULL,
    payload_json     JSONB NOT NULL,
    recorded_at_utc  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (stream_id, stream_version)
);

Custom Provider SPI & Extension Authoring

Foundgine's execution boundary is pluggable via a minimal Service Provider Interface (SPI). Custom storage providers (e.g., DuckDB, ClickHouse, Neo4j, or internal gRPC microservices) receive an already-authorized, bound ExecutionIR and must present a valid provider security proof bound to that exact IR fingerprint before returning data.

C# (.NET 10) — Implementing a Custom IExecutionProvider
using Foundgine.Core.Execution;
using Foundgine.Core.Security;

public sealed class CustomAnalyticsExecutionProvider : IExecutionProvider
{
    public string ProviderName => "AnalyticsWarehouse";

    public async ValueTask<ProviderExecutionResult> ExecuteAsync(
        ExecutionIR ir,
        ProviderExecutionContext context,
        CancellationToken ct)
    {
        // 1. Refuse execution if plan binding or security proof is absent
        ir.EnsureBoundAndVerified(context.SecurityProof);

        // 2. Translate ScanNode, PredicateFilterNode (contains mandatory auth predicates),
        //    ProjectionNode (authorized columns only), and SortNode (includes PK tie-breaker)
        var query = TranslateIrToWarehouseQuery(ir);
        var rows = await query.RunParameterizedAsync(context.Parameters, ct);

        return ProviderExecutionResult.FromRows(rows, planCacheHit: false);
    }
}
Java 27 — Implementing a Custom ExecutionProvider
import com.foundgine.core.execution.*;
import com.foundgine.core.security.*;

public final class CustomWarehouseProvider implements ExecutionProvider {
    @Override
    public String providerName() {
        return "AnalyticsWarehouse";
    }

    @Override
    public ProviderExecutionResult execute(ExecutionIR ir, ProviderExecutionContext context) {
        ir.ensureBoundAndVerified(context.securityProof());
        var rows = runTranslatedIr(ir, context.parameters());
        return ProviderExecutionResult.fromRows(rows, false);
    }
}

Interactive Pipeline & ExecutionIR Inspector

Select a runtime scenario below to inspect how Foundgine transforms caller input across Stage 2 (Intent), Stage 4 (Operation Graph), Stage 7 (Authorization & Row Predicates), Stage 9 (ExecutionIR), and Stage 12 (Execution Receipt):

Stages 2–7: Intent → OperationGraph → Lowered Auth Predicate
// Caller Context (from verified Host JWT / Warrant):
// Subject: "user:alice", TenantId: "nz-auckland-01", Roles: ["sales"]

// Stage 4 OperationGraph Nodes & Edges:
// Root: SalesOrder [Id, OrderNumber, Total]
//   └─ Edge (OneToMany via cust_id): OrderLine [Sku, Quantity]
//        (Note: UnitCost stripped by policy — requires "finance" role)

// Stage 7 Injected Row-Level Predicate:
// SalesOrder.TenantId == @p_auth_tenant ("nz-auckland-01")
Stages 9–12: Parameterized SQL Lowering & Signed Receipt
-- Stage 9/10 Lowered PostgreSQL Query (with automatic PK tie-breaker):
SELECT o.ord_id, o.ord_number, o.ord_total
FROM erp.tbl_order o
WHERE o.tenant_id = @p_auth_tenant
  AND o.status = @p_filter_0
ORDER BY o.ord_total DESC, o.ord_id ASC
LIMIT @p_take;

-- Stage 12 Receipt:
-- ContractFP: sha256:8f4e...a19c | PlanCacheHit: true | Rows: 18
Stage 6 Fail-Closed Gate — GroundingOutcome.RequiresClarification
// Input expression: "show recent high-value orders"
// Token "high-value" has no declared numeric threshold or weighted alias in MetadataRegistry.
// Result: Halts at Stage 6 BEFORE Authorization or SQL Compilation!
{
  "outcome": "Unresolved",
  "committed": null,
  "reason": "Unresolved vocabulary token 'high-value': no declared field, dimension, or weighted alias matches.",
  "tokensExplored": 4,
  "pathsExplored": 12
}
Stage 7 Fail-Closed Gate — Host Context Overrides Untrusted Arguments
// Attack: Caller passes filter { "TenantId": "tenant-competitor-99" } in MCP / GraphQL args
// while authenticated JWT carries TenantId = "tenant-acme-01".
//
// 1. Host ISecurityExecutionContextProvider ignores payload tenant claims completely.
// 2. Policy injects mandatory predicate: TenantId == "tenant-acme-01".
// 3. Combined SQL predicate: (TenantId = 'tenant-acme-01') AND (TenantId = 'tenant-competitor-99')
//    -> Returns 0 rows deterministically; cross-tenant data is mathematically unreachable.
Stages 7–12: Dry-Run Fingerprint → fgmcp1 Approval → Atomic Transaction
// 1. Dry-Run computes canonical PlanFingerprint = "sha256:9c41e2...77b4"
// 2. Host signs approval token: "fgmcp1.eyJwbGFuRnAiOiJzaGEyNTY6OWM0MWUyLi4uNzdiNCIsImp0aSI6Im5vbmNlLTg4MSJ9."
// 3. ExecuteApproved verifies:
//    [x] RSA-2048+ signature valid
//    [x] PlanFingerprint == "sha256:9c41e2...77b4" (zero field/target drift)
//    [x] Redis replay store consumes jti "nonce-881" atomically
//    [x] PostgreSQL revocation anchor epoch <= warrant rev_seq
// 4. Single BEGIN ... COMMIT inserts PurchaseOrder, PurchaseOrderLine, Outbox row & Audit Receipt.

Performance Tuning, Caching Architecture & Capacity Planning

Foundgine separates cold-path semantic compilation from hot-path parameterized execution so production workloads amortize model validation, graph expansion, and SQL/ORM query generation across thousands of requests per second.

1. Singleton Frozen MetadataRegistry

Build MetadataRegistry once at application startup (or via compile-time AOT source generators). Never call new MyModel().Build() per HTTP request—freezing computes the contract SHA-256 fingerprint once and shares immutable lookup tables lock-free across all threads.

2. Fingerprint-Keyed Plan Cache

SqlExecutionProvider and ORM providers cache compiled query templates under SHA256(ContractFP + PlanBindingFP + Dialect). Subsequent requests with the same structural shape and authorization policy bind new parameter values (@p_auth_tenant, @p_filter_0) directly without re-running SQL compilation.

3. Redis Pipelining & Local JWKS Cache

Configure connection multiplexing (StackExchange.Redis / Lettuce) with sub-second timeouts for warrant replay/revocation checks, and cache Keycloak JWKS signing keys in memory with background refresh so token verification adds <0.1 ms per call.

4. Native AOT & GraalVM Readiness

Using Foundgine.Providers.Aot.Generator (.NET 10) or foundgine-aot-generator (Java 27) eliminates runtime expression reflection and assembly scanning, enabling sub-20 ms container cold starts and minimal RSS memory footprints.

Canonical Type System & Filter/Sort Operator Specification

To guarantee identical query semantics across .NET 10, Java 27, PostgreSQL, SQLite, SQL Server, EF Core, and JPA, MetadataRegistry and ExecutionIR normalize all scalar values to a strict canonical type system:

Canonical IR Type .NET 10 CLR Type Java 27 Type PostgreSQL SQLite / SQL Server
SemanticType.String string java.lang.String TEXT / VARCHAR TEXT / NVARCHAR
SemanticType.Int32 / Int64 int / long Integer / Long INT4 / INT8 INTEGER / INT / BIGINT
SemanticType.Decimal decimal java.math.BigDecimal NUMERIC(p,s) NUMERIC / DECIMAL(p,s)
SemanticType.Boolean bool java.lang.Boolean BOOLEAN INTEGER (0/1) / BIT
SemanticType.Uuid System.Guid java.util.UUID UUID TEXT / UNIQUEIDENTIFIER
SemanticType.TimestampUtc DateTimeOffset java.time.Instant TIMESTAMPTZ TEXT (ISO-8601) / DATETIMEOFFSET

Complete Benchmark Dataset, Latency Percentiles & Adversarial Attack Matrix

Full quantitative data from Foundgine's closed-loop performance harness (benchmarks/) and deterministic adversarial security test suites (Foundgine.RedTeam and AgentEndToEnd/Fixtures/SupplyChain.PenTest).

1. Closed-Loop Latency Percentiles (p50 / p95 / p99 / p99.9) & Memory Allocation Profile

Measured on the sc-cs-orders-customer workload (salesOrder(first: 50) with nested lines and shipments over PostgreSQL 17, preliminary single-container runs):

Arm & Concurrency Throughput (RPS) p50 Latency p95 Latency p99 Latency p99.9 Latency Validation Gate
Foundgine (.NET 10) · c=1 111 rps 8.4 ms 12.9 ms 15.8 ms 21.4 ms PASS (0% err)
Baseline (HC + EF) · c=1 254 rps 3.6 ms 6.4 ms 8.7 ms 14.1 ms PASS (0% err)
Foundgine (.NET 10) · c=8 354 rps 21.1 ms 36.8 ms 44.3 ms 58.2 ms PASS (0% err)
Baseline (HC + EF) · c=8 1,086 rps 6.9 ms 12.4 ms 16.0 ms 24.5 ms PASS (0% err)
Foundgine (.NET 10) · c=16 509 rps 29.8 ms 45.2 ms 52.9 ms 71.0 ms PASS (0% err)
Baseline (HC + EF) · c=16 1,245 rps 11.9 ms 23.7 ms 31.8 ms 49.2 ms PASS (0% err)
Foundgine (.NET 10) · c=32 522 rps 58.4 ms 94.1 ms 112.5 ms 146.8 ms PASS (0% err)
Baseline (HC + EF) · c=32 369 rps 82.0 ms 131.4 ms 154.6 ms 218.0 ms INVALID (gate fail)

2. Per-Stage Boundary Cost Breakdown (Warm Plan Cache)

Pipeline Phase Typical Warm CPU Time Amortization Mechanism
JWT / Warrant Signature & Replay Check ~0.15 – 0.45 ms In-memory JWKS / issuer public key cache + pipelined Redis Lua script.
OperationGraph Expansion & Policy Auth ~0.35 – 0.80 ms Lock-free immutable MetadataRegistry lookups + compiled predicate expressions.
Plan Binding & ExecutionIR Lookup ~0.20 – 0.50 ms SHA256(ContractFP + PlanBindingFP + Dialect) cache hit skips SQL generation.
Receipt Construction & Async Audit Enqueue ~0.10 – 0.25 ms Lock-free ring buffer enqueue into BufferedDurableAuditLog.

3. Adversarial Red-Team & Penetration Test Matrix (32 Total Vectors)

Every attack vector below is codified in Foundgine.RedTeam (18 MCP vectors) and SupplyChain.PenTest (14 MCP + GraphQL vectors) and verified to fail closed:

Attack Category Adversarial Vector / Payload Enforcing Boundary Gate Verified Outcome
Cross-Tenant Read Filter injects TenantId == "other-tenant" in MCP/GraphQL args Host ISecurityExecutionContextProvider + lowered SQL WHERE BLOCKED (0 rows)
Identity Spoofing Caller supplies spoofed subject / customer_id in JSON body Transport adapters discard payload identity; read verified JWT only BLOCKED (403)
Scope Widening Delegated child warrant requests scope: "*" or extra entity ISecurityWarrantDelegationTrustResolver attenuation check BLOCKED (403)
Traversal Tunneling Query traverses Customer.transactions skipping restricted Contract SemanticOperationGraph expands all intermediate hops prior to auth BLOCKED (403)
Column Exfiltration Selects restricted UnitCost or * wildcard without finance role Field projection allowlist & empty-set fail-closed gate BLOCKED (403)
Approval Replay Re-submits valid fgmcp1 approval token a second time Atomic Redis jti single-use nonce consumption BLOCKED (Replay)
Plan Tampering Mutates Quantity or target entity after DryRunAsync approval SHA-256 PlanFingerprint verification before SQL/ORM dispatch BLOCKED (Drift)
Ambiguous Injection Natural-language prompt attempts fuzzy coercion ("active customers") SemanticLexicalResolver returns RequiresClarification BLOCKED (No Exec)
GraphQL Root Bypass Queries unexposed root field orderLine as customer role MapFoundgineGraphQL QueryRootRoles allowlist BLOCKED (403)
Deep Nesting DoS Submits 40-level recursive relationship selection or 5,000-node filter SecurityResourceLimits (max depth 32, max nodes 256) BLOCKED (400)

MCP Streamable HTTP (2025-06-18) & Signed Approval Token Specification

Foundgine's MCP endpoint (/mcp) implements the MCP 2025-06-18 Streamable HTTP transport with stateful session resumability, origin validation, and cryptographic write approvals.

HTTP Header / Token Field Direction Protocol & Security Semantics
Authorization: Bearer <token> Client → Server Required host OIDC/JWT or cryptographic warrant; mapped into SecurityExecutionContext on every request.
Mcp-Session-Id Server ↔ Client Cryptographically random session identifier bound to the authenticated principal/tenant; cross-principal session reuse is rejected with 403.
Last-Event-ID Client → Server Enables deterministic Server-Sent Events (SSE) stream replay after transient network disconnects within the session retention window.
Origin Client → Server Validated against configured AllowedOrigins allowlist to prevent cross-site browser DNS-rebinding or CSRF attacks against local MCP servers.
fgmcp1.<payload>.<sig> Approval Token Base64url-encoded JSON payload (planFingerprint, jti, sub, tid, exp) signed with RSA-2048+ PKCS#1 v1.5 SHA-256 by the host governance authority.

Complete Cross-Language API Parity Matrix (.NET 10 vs. Java 27)

Side-by-side reference of every primary entry point across Foundgine.* (.NET 10) and com.foundgine.* (Java 27):

Subsystem .NET 10 (.NET C# 14) Java 27
Model Root new MyModel().Build() → MetadataRegistry new MyModel().build() → MetadataRegistry
Fluent Query SemanticQuery.From(meta, "Entity").Select(...).WhereEq(...).Build() SemanticQuery.from(meta, "Entity").select(...).whereEq(...).build()
Read Execution await executor.ExecuteAsync(op, secCtx, ct) executor.executeAsync(op, secCtx).join()
Lexical Grounding resolver.Ground(expression, ct) → GroundingDecision resolver.ground(expression) → GroundingDecision
Mutation Dry-Run await mutations.DryRunAsync(graph, secCtx, ct) mutations.dryRunAsync(graph, secCtx).join()
Mutation Execute await mutations.ExecuteApprovedAsync(approval, secCtx, ct) mutations.executeApprovedAsync(approval, secCtx).join()
ORM Reader await efReader.ReadAsync(Entity, q => ..., ct) jpaEntities.entity("Entity").read(filters, fields)
GraphQL Mount app.MapFoundgineGraphQL(o => ...) FoundgineGraphQlRuntimeWiring.wire(...)
Agent Integration services.AddFoundgineAgentFramework(o => ...) FoundgineLangChain4jTools.toolMap(mcpServer)

Cryptographic Key Management, Rotation & KMS/HSM Integration

Foundgine isolates all cryptographic signing and encryption keys behind pluggable key-provider interfaces so production deployments can back warrant issuance, fgmcp1 approval tokens, and AES-256-GCM gateway envelopes with AWS KMS, Azure Key Vault, Google Cloud KMS, HashiCorp Vault, or PKCS#11 HSMs without exposing raw private key material to application memory.

1. Warrant & Approval Signing Keys (ISecurityWarrantSigner)

  • Algorithms: RS256 (RSA-2048+ PKCS#1 v1.5 SHA-256), PS256 (RSA-PSS), and ES256 (ECDSA P-256).
  • Zero-Downtime Key Rotation: Verifiers resolve public keys by JWT/token header kid against a multi-key JWKS / trust-root set, allowing new keys to be published before switching the active signing kid.

2. Gateway Envelope Encryption (AesGcmEnvelopeKeyRing)

  • Authenticated Encryption: 256-bit AES-GCM with 96-bit random nonces and 128-bit authentication tags.
  • AAD Context Binding: Additional Authenticated Data binds tenant_id + plan_fingerprint + approval_id so an encrypted ciphertext row cannot be swapped across tenants or mutation plans in PostgreSQL.
C# (.NET 10) — Multi-Key JWKS Warrant Trust Root & Rotation
using Foundgine.Runtime.Security;

// Configure multiple active/retiring public keys by 'kid' for zero-downtime key rotation
var trustResolver = new StaticWarrantIssuerTrustResolver(options =>
{
    options.AddTrustedIssuer("https://auth.acme.example", issuer =>
    {
        issuer.AddPublicKey("warrant-key-2026-10", retiringRsaPublicKey); // retiring
        issuer.AddPublicKey("warrant-key-2026-11", activeRsaPublicKey);   // active
        issuer.MaxWarrantLifetime = TimeSpan.FromMinutes(5);
    });
});

GraphQL Schema Generation, Directives & Federation Compatibility

Foundgine.Extensions.GraphQL (Hot Chocolate) and com.foundgine.extensions.graphql (GraphQL Java) project your frozen MetadataRegistry into strongly typed GraphQL query/mutation fields while keeping GraphQL strictly a transport adapter:

  • Fail-Closed Root Exposure: Only entities explicitly listed in QueryRootRoles are exposed at the GraphQL query root; child entities remain navigable strictly through authorized parent relationships.
  • Field-Level Projection Pruning: GraphQL selection sets (DataFetchingEnvironment / IResolverContext) are translated into SemanticOperation.Selections so only requested, authorized columns are fetched from SQL/EF/JPA—eliminating over-fetching.
  • Apollo Federation Subgraph Ready: Entity keys (HasKey) map cleanly to Federation @key reference resolvers, while every subgraph entity fetch still enforces the caller's host-verified SecurityExecutionContext.

Temporal Saga Patterns, Compensation & Per-Activity Authority

Long-running business processes combine PostgresOutbox, Foundgine.Extensions.Temporal / com.foundgine.extensions.temporal, and Foundgine's dry-run/approve/execute mutation lifecycle:

C# (.NET 10) — Temporal Activity Re-Minting Fresh Scoped Warrant Per Step
using Temporalio.Activities;
using Foundgine.Extensions.Temporal;

public sealed class FulfillmentActivities(
    IFoundgineTemporalAuthorityMinter authorityMinter,
    SemanticMutationEngine mutations)
{
    [Activity]
    public async Task<Guid> ReserveInventoryAsync(ReserveInventoryInput input, CancellationToken ct)
    {
        // Never serialize warrants in Temporal workflow history; mint a fresh 60s scoped warrant here
        SecurityExecutionContext activityContext = await authorityMinter.MintActivityContextAsync(
            tenantId: input.TenantId,
            subjectId: $"workflow:fulfillment:{input.OrderId}",
            allowedEntities: ["InventoryLot", "Shipment"],
            ttl: TimeSpan.FromSeconds(60),
            ct);

        var dryRun = await mutations.DryRunAsync(input.MutationGraph, activityContext, ct);
        var approval = await mutations.ApproveAsync(dryRun.PlanFingerprint, activityContext, ct);
        var result = await mutations.ExecuteApprovedAsync(approval, activityContext, ct);
        return result.PrimaryKey<Guid>("shipment");
    }
}

Semantic Execution Standard (SES) Specification Series (standards/semantic-execution/)

Foundgine's runtime invariants are specified independently of its C# and Java implementations as the normative Semantic Execution Standard (SES) under standards/semantic-execution/. Both Foundgine.* (.NET 10) and com.foundgine.* (Java 27) are validated against these specifications via shared JSON conformance vectors:

Specification Range Normative Domain Core Invariant Enforced
SES-001 – SES-010 Semantic Contract, Operation Graph & Monotonic Lifecycle Frozen MetadataRegistry SHA-256 contract fingerprint; explicit expansion of all multi-hop traversals prior to authorization; strict forward-only pipeline transitions.
SES-011 – SES-017 Bounded Lexical Grounding & Clarification Protocol Retrieval proposes candidates with evidence scores but never authorizes or guesses; multi-signature ties and sub-threshold weights fail closed with RequiresClarification.
SES-018 Compile-Time AOT Metadata Parity & Zero-Drift Roslyn source generators and Java annotation processors must emit metadata byte-for-byte semantically identical to fluent runtime builders with zero reflection.
SES-019 – SES-024 Host Security Context, Warrants & Replay Anchors Transport adapters never manufacture identity; delegated warrants attenuate monotonically; replay nonces and revocation epochs fail closed under cache lag.
SES-025 Provider Fidelity & ExecutionIR Proof Binding Storage providers execute only bound ExecutionIR artifacts verified by cryptographic security proofs and isolate plan caches by full authorization predicate digest.

Reference Samples, Concept Guides & E2E Benchmark Runners

The repository ships paired Starter and Advanced Supply Chain applications in both .NET 10 and Java 27, backed by progressive concept guides (00-Overview-And-Setup.md through 05-Adversarial-Security-Testing.md) and automated test/benchmark runners:

Starter vs. Advanced Sample Architecture

  • Starter Sample (src/csharp/samples/Foundgine.SupplyChain & src/java/samples/foundgine-supply-chain): Minimal realistic boundary exposing fixed tools (get_my_orders, place_order) with single-actor token-to-customer authorization.
  • Advanced Sample (src/csharp/samples/Foundgine.SupplyChain.Advanced & src/java/samples/foundgine-supply-chain-advanced): Open-intent query and mutation authoring, bounded graph traversal, subtree authorization pruning, BM25/graph candidate retrieval, and adversarial red-team verification.

Runner Environment Controls & Commands

  • FOUNDGINE_PARADEDB_BM25=1 — Enables ParadeDB pg_search BM25 retrieval integration tests (skips cleanly if extension is absent).
  • FOUNDGINE_POSTGRES_AGE=1 — Enables Apache AGE graph-similarity retrieval tests against PostgreSQL.
  • SUPPLY_CHAIN_CUSTOMERS, SUPPLY_CHAIN_STEPS, SUPPLY_CHAIN_SEED — Controls deterministic stochastic agent workload generation in run-supply-chain.ps1.
CLI — Running Advanced Concept Tests & Cross-Platform Benchmark Scripts
# Run all .NET 10 concept tests referenced across docs 01–05 (no optional PG extensions required)
cd src/csharp/samples/Foundgine.SupplyChain.Advanced/Semantic
dotnet test Tests/Foundgine.SupplyChain.Advanced.Tests.csproj

# Cross-platform PowerShell (pwsh) end-to-end workload & merged pentest report runners
pwsh ./run-supply-chain.ps1
pwsh ./merge-supply-chain-pentest-report.ps1

Architecture Evolution & Release Milestones

Milestone / Release Line Key Architectural Capabilities Introduced
V2 Baseline Re-architected around the canonical semantic execution model: frozen semantic contract, SemanticOperationGraph, logical planner, and strict provider boundary.
v0.2.x – v0.3.0 Established initial NuGet release line and added native Model Context Protocol (MCP) provider so agent runtimes consume semantic intents directly.
v0.5.x Introduced the Security Execution Boundary, host-owned SecurityExecutionContext, cryptographic security warrants, and deterministic penetration test suites.
v1.0.0 – v2.0.x Stabilized 1.0 contracts and expanded lexical grounding diagnostics, ambiguity resolution UX, and cross-surface coverage.
v3.3.5 – v3.4.2 (Current) Full dual-runtime parity across .NET 10 and Java 27, SES-018 AOT metadata parity, SES-025 provider execution fidelity, MCP 2025-06-18 Streamable HTTP, and unified Runtime/ControlPlane authority/recovery consolidation.

Production Operations, Health Checks & Graceful Shutdown

Running Foundgine in regulated, high-availability production clusters requires deterministic readiness probes, connection pool budgeting, and ordered shutdown hooks so in-flight mutations and buffered audit receipts drain without data loss:

1. Readiness & Liveness Probes

  • Liveness (/health/live): Verifies process responsiveness and frozen MetadataRegistry initialization without touching external dependencies.
  • Readiness (/health/ready): Probes primary database connectivity, Redis warrant replay/revocation store reachability, and PostgreSQL revocation anchor epoch synchronization. Fails closed (503) if Redis lags behind the durable PostgreSQL anchor.

2. Graceful Shutdown Ordering

  1. Stop accepting new HTTP / GraphQL / MCP requests (drain load balancer).
  2. Await in-flight SemanticMutationEngine transactions up to ShutdownDrainTimeout.
  3. Flush BufferedDurableAuditLog ring buffer to PostgreSQL so every committed receipt is persisted.
  4. Close Redis multiplexers and ADO.NET / HikariCP connection pools.

Multi-Tenancy Isolation Architectures

Because Foundgine separates semantic identity (MetadataRegistry) from physical storage resolution (IExecutionProvider), a single semantic model can serve three distinct multi-tenant storage isolation patterns without changing application queries or MCP/GraphQL contracts:

Isolation Model How Foundgine Enforces Isolation Best Fit
Pooled Shared Schema (Row-Level) ISemanticAuthorizationPolicy injects mandatory resource.TenantId == context.TenantId predicates into ExecutionIR, lowered into parameterized SQL WHERE clauses and optionally paired with PostgreSQL Row-Level Security (RLS). High-density SaaS with thousands of tenants sharing a single PostgreSQL cluster.
Schema-Per-Tenant A tenant-aware connection/schema resolver routes ExecutionIR scans onto tenant_<id>.* schemas while keeping plan caches partitioned by tenant schema + plan fingerprint. Mid-market enterprise tenants requiring isolated backup/restore boundaries.
Database-Per-Tenant Host DI resolves a tenant-scoped NpgsqlDataSource / DataSource from verified SecurityExecutionContext.TenantId before provider dispatch. Strict data-residency or sovereign-cloud tenants (e.g., AU/NZ vs. EU regions).

Machine-Readable AI & Agent Discovery Specification

In addition to human-readable HTML documentation, the Foundgine repository publishes four synchronized machine-readable discovery artifacts so IDE agents, autonomous coding tools, and MCP clients can inspect capabilities without scraping HTML:

Artifact Path Format Purpose & Automated Maintenance
docs-site/llms.txt text/plain Concise structured index of Foundgine's architecture, core packages, invariants, and canonical links following the llms.txt convention.
docs-site/llms-full.md text/markdown Complete, single-file technical reference containing full code examples, configuration tables, and security rules for large-context LLM ingestion.
.well-known/mcp.json application/json Standard MCP server discovery manifest advertising transport capabilities (2025-06-18), endpoint paths (/mcp), and the six governed tool schemas.
repo-index.json & REPO-MAP.md JSON & Markdown Complete file, namespace, and symbol inventory generated automatically by python tools/generate-repo-index.py.

Compliance, Threat Modeling & Regulatory Alignment

Foundgine's deterministic execution boundary, row-level predicate lowering, and tamper-evident audit receipts map directly onto enterprise security and privacy controls:

Control Framework Requirement / Risk Foundgine Architectural Control
OWASP LLM01 / LLM06
(Prompt Injection & Excessive Agency)
Untrusted user prompts attempt to invoke unauthorized tools, exfiltrate cross-tenant records, or trigger unapproved state mutations. Untrusted input is isolated to intent/lexical parsing; ambiguous queries fail closed (RequiresClarification); reads enforce SQL-lowered row/column policies; writes require dry-run PlanFingerprint + host-signed fgmcp1 approval.
OWASP API1 / API3
(BOLA / BOPLA)
Broken Object-Level or Property-Level Authorization across GraphQL or REST/MCP endpoints. SemanticOperationGraph expands all intermediate traversal hops before authorization; policies return explicit column allowlists and mandatory object-level predicates lowered into SQL WHERE.
SOC 2 Type II / ISO 27001
(Access Control & Auditability)
Demonstrable least-privilege enforcement, revocation timeliness, and immutable audit trails of data access and mutations. Short-lived cryptographic warrants with delegation attenuation, Redis + PostgreSQL GREATEST monotonic revocation epochs, and lossless BufferedDurableAuditLog receipts recording contract, plan, and IR SHA-256 digests.
GDPR / NZ Privacy Act 2020
(Data Minimization & Residency)
Preventing over-fetching of PII fields and enforcing regional tenant data boundaries. Field projection pruning ensures unauthorized or unrequested PII columns are never selected from storage; database-per-tenant routing isolates regional storage backends by verified TenantId.

Build, Packaging, Container Hardening & Release Verification

Reproducible build and verification commands across all five language ecosystems in the Foundgine monorepo (v3.4.2):

.NET 10 & Java 27 — Full Solution Build, AOT & Conformance Test
# .NET 10 Release Build & Conformance / Security Suites
dotnet test src/csharp/Foundgine.sln -c Release

# Native AOT Publish Verification (Zero-Reflection Source Generator)
dotnet publish src/csharp/samples/Foundgine.SupplyChain -c Release -p:PublishAot=true

# Java 27 Maven Verify (Core, Runtime, Providers, Extensions, AOT & Conformance)
mvn -f src/java/pom.xml -B verify
TypeScript, Python & Rust/WASM — Client SDK Verification
# TypeScript (@foundgine/typescript)
npm --prefix src/typescript ci && npm --prefix src/typescript test

# Python (foundgine)
pytest src/python/tests

# Rust + WebAssembly (@foundgine/wasm)
cargo test --manifest-path src/wasm/Cargo.toml
Production Container Hardening Checklist: Run Foundgine services on distroless or minimal non-root images (mcr.microsoft.com/dotnet/aspnet:10.0-noble-chiseled or eclipse-temurin:27-jre-alpine), mount TLS/JWKS trust bundles read-only, inject KMS/AES-GCM key material via secret managers rather than environment variables, and bind /mcp strictly behind authenticated reverse proxies with explicit AllowedOrigins.

End-to-End Full-Stack Production Wiring Recipe

Complete .NET 10 Program.cs composition uniting PostgreSQL, EF Core, Keycloak OIDC, Redis + PostgreSQL Warrant Revocation, Hot Chocolate GraphQL, MCP Streamable HTTP, and Microsoft Agent Framework (MAF) over a single frozen MetadataRegistry:

C# (.NET 10) — Complete Multi-Surface Enterprise Host Composition
var builder = WebApplication.CreateBuilder(args);

// 1. Freeze Semantic Model once at startup (or use compile-time AOT GeneratedFoundgineMetadata.Create())
MetadataRegistry metadata = new SupplyChainModel().Build();
builder.Services.AddSingleton(metadata);

// 2. Host-owned Security Context (Keycloak OIDC claims) & Row/Column Authorization Policy
builder.Services.AddFoundgineKeycloakContext(builder.Configuration.GetSection("Keycloak"));
builder.Services.AddSingleton<ISemanticAuthorizationPolicy, SupplyChainAuthorizationPolicy>();

// 3. Persistence (PostgreSQL + EF Core + Outbox + Lossless Audit Log) & Redis-Anchored Revocation
builder.Services.AddFoundginePostgresPersistence(pg =>
{
    pg.ConnectionString = builder.Configuration.GetConnectionString("Default")!;
    pg.EnableOutbox = true;
    pg.EnableDurableAuditLog = true;
});
builder.Services.AddFoundgineAnchoredRevocation(
    redisConnection: builder.Configuration.GetConnectionString("Redis")!,
    postgresConnection: builder.Configuration.GetConnectionString("Default")!);

// 4. Register Core Runtime, GraphQL Adapter, MCP Server & Microsoft Agent Framework Tools
builder.Services.AddFoundgineRuntime();
builder.Services.AddFoundgineGraphQL(gql => gql.QueryRootRoles.Add("SalesOrder", ["sales", "finance"]));
builder.Services.AddFoundgineMcpServer(mcp => mcp.AllowedOrigins = ["https://app.acme.example"]);
builder.Services.AddFoundgineAgentFramework();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

// 5. Expose identical governed domain capabilities across GraphQL and MCP
app.MapFoundgineGraphQL("/graphql");
app.MapFoundgineMcp("/mcp");
app.Run();

Complete Code Snippets Cookbook (Java 27, SDKs, Retrieval & Testing)

Copy-pasteable, production-ready recipes covering Java 27 + Spring Boot + JPA + MCP, TypeScript / Python / Rust-WASM client SDKs, custom BM25/pgvector candidate retrieval sources, and deterministic security unit tests:

Java 27 — Complete Spring Boot Configuration (JPA + Keycloak + MCP + LangChain4j)
package com.acme.supplychain.config;

import com.foundgine.core.metadata.MetadataRegistry;
import com.foundgine.runtime.FoundgineEngine;
import com.foundgine.providers.jpa.JpaOrmProvider;
import com.foundgine.providers.mcp.FoundgineMcpServer;
import com.foundgine.providers.langchain4j.FoundgineLangChain4jTools;
import com.foundgine.extensions.keycloak.KeycloakContextProvider;
import jakarta.persistence.EntityManagerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FoundgineConfiguration {

    @Bean
    public MetadataRegistry metadataRegistry() {
        // Freeze semantic contract once at startup (or use compile-time GeneratedFoundgineMetadata.build())
        return new SupplyChainModel().build();
    }

    @Bean
    public FoundgineEngine foundgineEngine(
            MetadataRegistry registry,
            EntityManagerFactory emf,
            ErpAuthorizationPolicy authPolicy) {
        var jpaProvider = new JpaOrmProvider(emf, registry);
        return FoundgineEngine.builder(registry)
                .authorizationPolicy(authPolicy)
                .executionProvider(jpaProvider)
                .mutationProvider(jpaProvider)
                .build();
    }

    @Bean
    public FoundgineMcpServer foundgineMcpServer(
            FoundgineEngine engine,
            KeycloakContextProvider keycloakContextProvider) {
        return FoundgineMcpServer.builder(engine)
                .securityContextProvider(keycloakContextProvider)
                .allowedOrigins(java.util.List.of("https://portal.acme.example"))
                .build();
    }

    @Bean
    public java.util.Map<String, dev.langchain4j.agent.tool.ToolSpecification> agentTools(
            FoundgineMcpServer mcpServer) {
        return FoundgineLangChain4jTools.toolMap(mcpServer);
    }
}
TypeScript (@foundgine/typescript) — Dry-Run & Approved Write
import { FoundgineMcpClient } from "@foundgine/typescript";

const client = new FoundgineMcpClient({
  endpoint: "https://api.acme.example/mcp",
  bearerToken: async () => await auth.getAccessToken(),
});

// 1. Discover frozen capabilities & query with row-level policy enforcement
const orders = await client.querySemantic({
  entity: "PurchaseOrder",
  select: ["Id", "OrderNumber", "Status", "Total"],
  where: [{ field: "Status", op: "Eq", value: "OVERDUE" }],
  take: 25,
});

// 2. Two-phase mutation: Dry-Run -> Host Approval Token -> Commit
const preview = await client.mutateDryRun({
  entity: "PurchaseOrder",
  action: "Update",
  key: orders.rows[0].Id,
  values: { Status: "ESCALATED" },
});
const approvalToken = await hostGovernance.requestApproval(preview.planFingerprint);
const receipt = await client.mutateExecute({ approvalToken });
Python (foundgine) & Rust/WASM (@foundgine/wasm)
# Python (foundgine) — Async MCP & Temporal Workflow Client
from foundgine import AsyncFoundgineClient

async with AsyncFoundgineClient("https://api.acme.example/mcp", token=jwt) as fg:
    res = await fg.query("active customers")
    if res.outcome == "RequiresClarification":
        for opt in res.competing_interpretations:
            print(opt.signature, opt.weight)

# Rust + WebAssembly (@foundgine/wasm)
# let client = FoundgineClient::new("https://api.acme.example/mcp", jwt)?;
# let rows = client.query_semantic(spec_json).await?;
C# (.NET 10) — Non-Authoritative PostgreSQL pg_trgm / pgvector Candidate Source
using Foundgine.Core.Grounding;
using Npgsql;

// Retrieval proposes weighted lexical candidates only — NEVER bypasses SemanticLexicalResolver or Policy!
public sealed class PostgresFuzzyCandidateSource(NpgsqlDataSource dataSource) : ISemanticLexicalCandidateSource
{
    public async ValueTask<IReadOnlyList<LexicalCandidate>> FindCandidatesAsync(
        LexicalCandidateRequest request,
        CancellationToken ct)
    {
        await using var conn = await dataSource.OpenConnectionAsync(ct);
        await using var cmd = new NpgsqlCommand("""
            SELECT canonical_entity, canonical_field, alias_term,
                   ROUND(similarity(alias_term, @q) * 100)::int AS score
            FROM semantic_vocabulary_index
            WHERE similarity(alias_term, @q) >= 0.35
            ORDER BY score DESC
            LIMIT @limit
            """, conn);
        cmd.Parameters.AddWithValue("q", request.NormalizedToken);
        cmd.Parameters.AddWithValue("limit", request.MaxCandidates);

        var results = new List<LexicalCandidate>();
        await using var reader = await cmd.ExecuteReaderAsync(ct);
        while (await reader.ReadAsync(ct))
        {
            results.Add(new LexicalCandidate(
                Entity: reader.GetString(0),
                Field: reader.IsDBNull(1) ? null : reader.GetString(1),
                MatchedTerm: reader.GetString(2),
                EvidenceWeight: reader.GetInt32(3)));
        }
        return results;
    }
}
C# (.NET 10) — Deterministic Adversarial PenTest Verification
using Foundgine.Core.Query;
using Foundgine.Core.Security;
using Foundgine.Runtime.Execution;
using Xunit;

public sealed class TenantIsolationPenTest
{
    [Fact]
    public async Task CrossTenantFilterInjection_CannotBypassHostSecurityContext()
    {
        var metadata = new SupplyChainModel().Build();
        var executor = TestHarness.CreateInMemoryExecutor(metadata, new SupplyChainAuthorizationPolicy());

        // Host verifies caller belongs strictly to 'tenant-alpha'
        var hostContext = new SecurityExecutionContext(
            SubjectId: "user:alice",
            TenantId: "tenant-alpha",
            Roles: ["sales"],
            IsAuthenticated: true);

        // Attacker injects explicit filter targeting 'tenant-bravo'
        var maliciousQuery = SemanticQuery.From(metadata, "SalesOrder")
            .Select("Id", "OrderNumber", "Total")
            .WhereEq("TenantId", "tenant-bravo")
            .Build();

        var result = await executor.ExecuteAsync(maliciousQuery, hostContext, CancellationToken.None);

        // Lowered predicate becomes: (TenantId == 'tenant-alpha') AND (TenantId == 'tenant-bravo') -> 0 rows
        Assert.Empty(result.Rows);
    }
}

Semantic Query Optimizer Passes, Algebra & Cost Bounds

Before ExecutionIRCompiler lowers a SemanticPlan into physical SQL or ORM expression trees, SemanticPlanner executes a deterministic sequence of invariant-preserving rewrite passes. Every rewrite pass must preserve the exact SemanticPlanAuthorizationBinding fingerprint and never widen field projections or drop row-level predicates:

Optimizer Pass Transformation Performed Safety Invariant
1. Projection Pruning Removes unreferenced columns from intermediate join nodes while retaining foreign-key join columns and the root primary key. Never adds columns outside AuthorizationDecision.AllowedFields.
2. Predicate Pushdown Pushes user filters and policy-injected row-level predicates (TenantId, ownership predicates) as close to base ScanNode leaves as relational semantics allow. Never reorders across outer-join null-producing boundaries in a way that alters row visibility.
3. Redundant Join Elimination Collapses duplicate relationship traversals referencing the same parent/child edge within a single query graph into one JoinNode. Preserves cardinalities (OneToOne, ManyToOne, OneToMany) and child row predicates.
4. Deterministic Tie-Breaker Injection Appends the entity primary key (ASC) to SortNode whenever user sort keys are non-unique or omitted. Guarantees stable keyset cursor pagination across concurrent inserts/updates.
5. Cardinality & Depth Guard Verifies total expanded join fan-out, selection depth (≤32), and node count (≤256) against SecurityResourceLimits. Halts with ResourceLimitExceededException before hitting the database.

Keycloak OIDC / OAuth 2.1 Claims Mapping & Multi-Realm Resolution

Foundgine.Extensions.Keycloak (.NET 10) and com.foundgine.extensions.keycloak (Java 27) bridge verified OIDC access tokens into immutable SecurityExecutionContext records while rejecting unsigned, expired, or wrong-audience tokens at the boundary:

Standard & Custom Claim Extraction

  • sub → SecurityExecutionContext.SubjectId
  • tid / organization_id → TenantId (strictly required)
  • realm_access.roles + resource_access[client].roles → Roles
  • scope → Space-delimited capability scopes
  • azp / aud → Verified against AllowedAudiences

Multi-Realm & Token Exchange (RFC 8693)

  • Per-Realm JWKS Resolution: Maps issuer URI (iss) against a strict allowlist of trusted Keycloak realms, caching each realm's JWKS keys independently.
  • On-Behalf-Of Delegation: When an agent exchanges a user token via OAuth 2.1 Token Exchange (RFC 8693), the act (actor) claim chain is recorded in SecurityExecutionContext.DelegationChain for monotonic attenuation checks.

Environment Variables, Ports & Diagnostics Cheat Sheet

Variable / Setting Default Purpose
ASPNETCORE_URLS / SERVER_PORT http://localhost:8080 Host HTTP listener exposing /graphql, /mcp, and /health/*.
FOUNDGINE_MCP_PATH /mcp (disabled by default in Spring Boot) Streamable HTTP endpoint path for MCP JSON-RPC 2.0 & SSE sessions.
FOUNDGINE_PARADEDB_BM25 0 (unset) Enables ParadeDB pg_search BM25 approximate candidate retrieval tests.
FOUNDGINE_POSTGRES_AGE 0 (unset) Enables Apache AGE openCypher graph similarity retrieval tests.
OTEL_EXPORTER_OTLP_ENDPOINT Unset Exports ActivitySource("Foundgine") traces and security denial metrics via OTLP.

Granular Modular Package & Assembly Topology (.NET 10 & Java 27)

Beneath the four top-level NuGet and Maven distribution packages, Foundgine decomposes responsibilities into tightly scoped internal modules so core contracts remain dependency-free while storage, ORM, AOT, GraphQL, MCP, and control-plane modules stay cleanly isolated:

Architectural Layer .NET 10 Module / Assembly Java 27 Maven Module (io.github.cristianbarragan) Responsibility
Core Abstractions & Metadata Core.Abstractions, Core.Semantic.Metadata foundgine-core (.abstractions, .metadata) Stable identifiers, contract fingerprints, fluent model builder, and frozen MetadataRegistry.
Semantic Meaning & Planning Core.Semantic, Core.Semantic.Planning, Core.Serialization foundgine-core (.semantic, .planning, .serialization) Intent normalization, lexical grounding, operation graph expansion, logical planning, and JSON intent adapters.
Execution IR & Boundary Core.Execution foundgine-core (.execution) ExecutionIR algebraic nodes, provider security proof gates, results, and signed ExecutionReceipt evidence.
Runtime & Control Plane Foundgine, Foundgine.Runtime, Runtime.ControlPlane foundgine-runtime (.controlplane) Application orchestration, authorization enforcement, dry-run/approve/execute mutations, warrant verification, and recovery/authority control-plane state.
SQL, InMemory & ORM Providers Providers.Storage.Sql, Providers.Storage.InMemory, Providers.Orm, Providers.EntityFrameworkCore foundgine-providers (storage/sql, storage/inmemory, storage/orm, storage/orm/jpa) Parameterized SQL/PostgreSQL lowering, deterministic in-memory execution, and EF Core / JPA ORM adapters.
Compile-Time AOT & Generators Providers.Aot, Providers.Aot.Generator foundgine-aot-generator Zero-reflection C# Roslyn source generator and Java annotation processor emitting SES-018 compliant metadata builders.
MCP, AI Models & GraphQL Providers.Tools.MCP, Providers.Models, Extensions.GraphQL.HotChocolate* foundgine-providers (mcp, langchain4j), foundgine-extensions (graphql, keycloak, temporal) MCP 2025-06-18 server/tools, Microsoft.Extensions.AI / MAF / LangChain4j adapters, and Hot Chocolate / GraphQL Java execution boundaries.

Java 27 Advanced Reactor Setup, Maven AOT Processor & PostgreSQL Compose

Complete Maven pom.xml and docker-compose.yml setup from src/java/samples/foundgine-supply-chain-advanced/ showing how to wire foundgine-core, foundgine-runtime, and compile-time foundgine-aot-generator annotation processing against PostgreSQL:

Java 27 — pom.xml with foundgine-aot-generator Annotation Processor
<dependencies>
  <dependency>
    <groupId>io.github.cristianbarragan</groupId>
    <artifactId>foundgine-core</artifactId>
    <version>3.4.2</version>
  </dependency>
  <dependency>
    <groupId>io.github.cristianbarragan</groupId>
    <artifactId>foundgine-runtime</artifactId>
    <version>3.4.2</version>
  </dependency>
  <dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
  </dependency>
</dependencies>

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
        <annotationProcessorPaths>
          <path>
            <groupId>io.github.cristianbarragan</groupId>
            <artifactId>foundgine-aot-generator</artifactId>
            <version>3.4.2</version>
          </path>
        </annotationProcessorPaths>
        <compilerArgs>
          <arg>-Afoundgine.generated.package=com.foundgine.samples.supplychain.advanced.generated</arg>
        </compilerArgs>
      </configuration>
    </plugin>
  </plugins>
</build>
docker-compose.yml — Local PostgreSQL Persistence for Supply Chain E2E
services:
  postgres:
    image: postgres:16
    environment:
      POSTGRES_DB: foundgine_supply_chain
      POSTGRES_USER: foundgine
      POSTGRES_PASSWORD: foundgine
    ports:
      - "4429:5432"
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U foundgine -d foundgine_supply_chain"]
      interval: 2s
      timeout: 3s
      retries: 20

# Start database and verify health before running E2E / PenTest suites:
# docker compose up -d postgres

Normative Vocabulary & Architectural Glossary

Foundgine enforces strict separation of concerns across seven normative concepts so retrieval, model output, and transport framing can never be conflated with domain authority:

Term Normative Definition & Boundary Rule
Intent What the caller requests (SemanticOperation / SemanticMutationIntent), expressed independently of physical SQL tables, ORM entities, or transport wire formats.
Retrieval Approximate candidate discovery plus evidence scores (e.g., BM25, pg_trgm, pgvector, or Apache AGE). Retrieval only ever proposes candidates—it never decides meaning or grants authorization.
Resolution (Grounding) Evaluates lexical candidates against the frozen MetadataRegistry and relationship graph; commits only when a single canonical semantic signature clears threshold, otherwise fails closed with RequiresClarification.
Authorization Evaluates host-verified SecurityExecutionContext, cryptographic warrants, and domain policies to determine permitted entities, fields, traversal hops, and mandatory row-level predicates.
Plan Provider-independent logical execution plan (SemanticPlan) cryptographically bound via SemanticPlanAuthorizationBinding to the contract and authorization decision digests.
ExecutionIR Controlled algebraic intermediate representation at the storage provider boundary; providers translate bound ExecutionIR mechanically without re-interpreting caller authority.
Evidence Structured audit record (ExecutionReceipt / ExecutionEvidence) capturing what was resolved, authorized, and executed—recorded for compliance without granting downstream authority.

Application Categories & Architectural Fit Matrix (docs/APPLICATION-CATEGORIES.md)

Foundgine centralizes semantic meaning, relationship traversal, and row-level authorization without making any single transport or database the center of your architecture. Use this matrix from docs/WHY-FOUNDGINE.md and docs/APPLICATION-CATEGORIES.md to evaluate architectural fit:

Application Category Architectural Problem Solved Recommended Foundgine Footprint
Multi-Surface Domain Backends
(REST + GraphQL + Internal Services)
Eliminates duplicated entity definitions, relationship traversal rules, filter validation, and authorization checks across separate transport layers. Foundgine.Core + Foundgine.Runtime + EF Core / JPA + GraphQL adapter.
AI-Enabled & MCP-Exposed Applications Lets AI agents express open intent while ensuring retrieval never grants authority and ambiguous phrasing fails closed (RequiresClarification). Full boundary + Providers.Tools.MCP (/mcp) + host-minted warrants + fgmcp1 write approvals.
Regulated Multi-Tenant SaaS Guarantees tenant isolation and property-level redaction by lowering host-verified predicates directly into SQL WHERE and recording immutable receipts. ISemanticAuthorizationPolicy + SQL/EF/JPA providers + BufferedDurableAuditLog.
Legacy Database Modernization Exposes clean domain entities and weighted aliases over legacy table/column schemas without rewriting existing databases or ORMs. Fluent FoundgineModel physical table/column mappings + compile-time AOT generators.
Simple Single-Endpoint CRUD / Public Read Minimal domain rules, single consumer surface, and no row/column security boundaries. Not required—plain ASP.NET Core / Spring Web + ORM is simpler and sufficient.

ControlPlane Architecture: .NET 10 vs. Java 27 Scope & Boundaries

Both runtimes include an optional ControlPlane module outside the core synchronous query execution path, intentionally scoped to distinct operational responsibilities in each ecosystem:

.NET 10 — Foundgine.Runtime.ControlPlane

Optional cluster recovery and high-availability coordination module remaining strictly outside the core semantic authorization path:

  • Witness Quorum: Distributed consensus checks for split-brain prevention across replicated authority nodes.
  • Credential Lifecycle & Promotion/Failover: Controlled rotation and primary-replica promotion workflows.
  • Journal Reconciliation & Recovery Evidence: Deterministic replay and cryptographic recovery receipts after node failover.

Java 27 — com.foundgine.runtime.controlplane

Optional governance and key-lifecycle module tailored for JVM enterprise hosts:

  • Tool Governance: Centralized allowlist and policy enforcement across exposed MCP and agent tools.
  • Approval & Audit Coordination: Lifecycle management for human-in-the-loop mutation approvals and durable audit records.
  • Authorization-Key Rotation: Signing key rollover and trust-root management for warrant and approval verification.

GraphQL Execution Boundary Internals (FoundgineGraphQLQueryExecutor & MutationExecutor)

GraphQL adapters never trust GraphQL query text, operation names, variables, or field arguments as sources of identity or tenant authority. Every GraphQL operation routes through dedicated boundary executors requiring a host-supplied ISecurityExecutionContextProvider:

C# (.NET 10) — FoundgineGraphQLQueryExecutor & FoundgineGraphQLMutationExecutor Boundary
using Foundgine.Extensions.GraphQL;
using Foundgine.Core.Security;

// GraphQL variables & arguments are parsed strictly as untrusted intent/filter values.
// Identity, TenantId, and Roles are resolved exclusively by host ISecurityExecutionContextProvider.
public sealed class OrderGraphQlEndpoint(
    FoundgineGraphQLQueryExecutor queryExecutor,
    FoundgineGraphQLMutationExecutor mutationExecutor,
    ISecurityExecutionContextProvider hostSecurityProvider)
{
    public async ValueTask<GraphQlExecutionResponse> ExecuteQueryAsync(
        GraphQlExecutionRequest request,
        CancellationToken ct)
    {
        SecurityExecutionContext trustedContext =
            await hostSecurityProvider.GetCurrentContextAsync(ct);

        // Enforces QueryRootRoles, SecurityResourceLimits, OperationGraph traversal auth,
        // and SQL-lowered row/column predicates identically to MCP and C# callers.
        return await queryExecutor.ExecuteAsync(request, trustedContext, ct);
    }
}

Advanced Graph Traversals, Aggregates & Subquery Quantification

Beyond flat single-table reads, SemanticQuery and ExecutionIRCompiler support multi-hop relationship traversals, relational quantifiers (Some, Every, None), and bounded scalar aggregations—all subject to per-hop authorization and row-level predicate injection:

C# (.NET 10) — Multi-Hop Traversal + Relational Quantifiers (Some / None)
// Find customers with at least one overdue order over $1,000 AND no open compliance holds.
// SemanticOperationGraph expands Customer -> SalesOrder and Customer -> ComplianceHold
// so both target entities and intermediate FK edges are authorized before SQL lowering.
var query = SemanticQuery.From(metadata, "Customer")
    .Select("Id", "Name", "AccountTier")
    .WhereRelatedSome("orders", order =>
        order.WhereEq("Status", "OVERDUE")
             .WhereGt("Total", 1000m))
    .WhereRelatedNone("complianceHolds", hold =>
        hold.WhereEq("Resolved", false))
    .OrderByAsc("Name")
    .Take(50)
    .Build();
Lowered Parameterized SQL (EXISTS / NOT EXISTS with Injected Tenant Predicates)
SELECT c.cust_id, c.cust_name, c.account_tier
FROM erp.tbl_customer c
WHERE c.tenant_id = @p_auth_tenant
  AND EXISTS (
      SELECT 1 FROM erp.tbl_order o
      WHERE o.cust_id = c.cust_id
        AND o.tenant_id = @p_auth_tenant
        AND o.ord_status = @p_0
        AND o.ord_total > @p_1
  )
  AND NOT EXISTS (
      SELECT 1 FROM erp.tbl_compliance_hold h
      WHERE h.cust_id = c.cust_id
        AND h.tenant_id = @p_auth_tenant
        AND h.is_resolved = @p_2
  )
ORDER BY c.cust_name ASC, c.cust_id ASC
LIMIT @p_take;

Canonical JSON Intent AST & Cross-Language Serialization Spec

Foundgine.Core.Serialization (.NET 10) and com.foundgine.core.serialization (Java 27) define a deterministic, schema-validated JSON wire representation for SemanticOperation and SemanticMutationIntent. Both runtimes produce identical canonical JSON bytes and SHA-256 digests for equivalent queries:

Canonical JSON Intent AST (Shared Across .NET 10, Java 27 & Conformance Vectors)
{
  "schemaVersion": "3.4",
  "kind": "Query",
  "rootEntity": "SalesOrder",
  "selections": ["Id", "OrderNumber", "Status", "Total"],
  "filter": {
    "op": "And",
    "clauses": [
      { "field": "Status", "op": "In", "values": ["PENDING", "APPROVED"] },
      { "field": "Total", "op": "Between", "min": 100.00, "max": 25000.00 }
    ]
  },
  "includes": [
    {
      "relationship": "lines",
      "selections": ["Sku", "Quantity"],
      "take": 20
    }
  ],
  "orderBy": [
    { "field": "Total", "direction": "Desc" }
  ],
  "take": 50
}

Security Vulnerability Disclosure, Supply-Chain Provenance & Governance

Foundgine's security posture covers both runtime execution invariants and software supply-chain integrity (SECURITY.md):

Coordinated Vulnerability Disclosure (SECURITY.md)

  • Security issues affecting warrant verification, row-level predicate lowering, replay/revocation stores, or GraphQL/MCP authorization boundaries are reported privately via GitHub Security Advisories rather than public issues.
  • Security fixes ship with deterministic regression vectors added directly to Foundgine.RedTeam and src/conformance/.

Artifact Provenance & Minimal Dependency Footprint

  • Zero Bloat Core: Foundgine.Core and foundgine-core maintain minimal external dependencies to minimize transitive CVE exposure.
  • Deterministic Builds: NuGet packages (dero), Maven Central artifacts (io.github.cristianbarragan), npm packages (@foundgine/*), and PyPI releases (foundgine) are built from tagged releases in CI with reproducible SourceLink / GPG signatures.

Multi-Step Mutation Graph Internals & Topological Write Ordering

Complex business mutations rarely touch a single row. SemanticMutationGraph models multi-entity writes as a directed acyclic graph (DAG) of dependent operations—such as inserting a parent PurchaseOrder, capturing its generated primary key, inserting child PurchaseOrderLine rows, updating inventory reservations, and appending a transactional outbox event inside one atomic database transaction:

Topological Execution & Key Propagation

  • Dependency Resolution: Sorts mutation nodes topologically so parent inserts execute before dependent foreign-key child inserts, and child deletes execute before parent deletes.
  • Output-to-Input Binding: Binds generated primary keys (UUID / BIGINT) from parent mutation nodes into child foreign-key slots without exposing intermediate SQL to the caller.

Optimistic Concurrency & Per-Node Authorization

  • Per-Node Policy Check: Every target entity and mutated field in the graph is authorized independently by ISemanticAuthorizationPolicy, with row-level predicates injected into UPDATE/DELETE WHERE clauses.
  • Optimistic Concurrency: Supports expected version / concurrency token assertions so stale writes abort cleanly and roll back the entire transaction.
C# (.NET 10) — Multi-Entity Transactional Mutation Graph (Dry-Run → Approve → Commit)
using Foundgine.Core.Mutations;
using Foundgine.Runtime.Mutations;

// Build a two-step transactional mutation graph: PurchaseOrder + PurchaseOrderLine
var orderId = Guid.NewGuid();
var mutationGraph = SemanticMutationGraphBuilder.Create(metadata)
    .Insert("PurchaseOrder", nodeKey: "order", values: new Dictionary<string, object?>
    {
        ["Id"] = orderId,
        ["CustomerId"] = customerId,
        ["Status"] = "SUBMITTED",
        ["Total"] = 2450.00m
    })
    .Insert("PurchaseOrderLine", nodeKey: "line1", values: new Dictionary<string, object?>
    {
        ["Id"] = Guid.NewGuid(),
        ["PurchaseOrderId"] = orderId,
        ["Sku"] = "SKU-9001",
        ["Quantity"] = 5,
        ["UnitPrice"] = 490.00m
    })
    .Build();

// 1. Dry-Run authorizes every node/field & computes deterministic SHA-256 PlanFingerprint
MutationDryRunResult preview = await mutations.DryRunAsync(mutationGraph, hostContext, ct);

// 2. Host governance signs fgmcp1 approval token bound to preview.PlanFingerprint
SignedMutationApproval approval = await hostApprover.SignApprovalAsync(preview, hostContext, ct);

// 3. Atomic commit executes both inserts + outbox + durable audit receipt in one DB transaction
MutationExecutionResult committed = await mutations.ExecuteApprovedAsync(approval, hostContext, ct);

Distributed Revocation & Replay Store Internals (Redis Lua + PostgreSQL Anchor)

In horizontally scaled clusters, single-use warrant replay defense and instant revocation require atomic check-and-set semantics across all replicas without split-brain race conditions. AnchoredSecurityWarrantRevocationStore pairs an atomic Redis Lua evaluation script with PostgreSQL's durable GREATEST epoch anchor:

Atomic Redis Lua Check-and-Consume Script (Replay + Revocation + Epoch Floor)
-- KEYS[1] = "fg:warrant:jti:<jti>"          (single-use replay key)
-- KEYS[2] = "fg:warrant:revoked:<warrantId>" (explicit warrant revocation key)
-- KEYS[3] = "fg:issuer:epoch:<issuerId>"     (cached monotonic revocation epoch)
-- ARGV[1] = ttl_seconds, ARGV[2] = token_rev_seq, ARGV[3] = pg_anchor_epoch

if redis.call("EXISTS", KEYS[2]) == 1 then
    return {0, "WARRANT_REVOKED"}
end

local cached_epoch = tonumber(redis.call("GET", KEYS[3]) or "0")
local effective_epoch = math.max(cached_epoch, tonumber(ARGV[3]))
if tonumber(ARGV[2]) < effective_epoch then
    return {0, "EPOCH_SUPERSEDED"}
end

if redis.call("SET", KEYS[1], "1", "NX", "EX", tonumber(ARGV[1])) == false then
    return {0, "REPLAY_DETECTED"}
end

return {1, "OK"}

Architectural Invariant to Codebase Cross-Reference Index

Direct traceability matrix mapping each core Foundgine security and execution invariant to its normative specification, `.NET 10` assembly, `Java 27` package, and automated verification suite:

Invariant SES Spec .NET 10 Location Java 27 Location Verification Suite
Frozen Contract Fingerprint SES-001..004 Core.Semantic.Metadata com.foundgine.core.metadata src/conformance/ + AOT parity tests
Fail-Closed Ambiguity Gate SES-011..017 Core.Semantic.Grounding com.foundgine.core.grounding lexical-grounding-vectors.json
Compile-Time AOT Parity SES-018 Providers.Aot.Generator foundgine-aot-generator SupplyChain.Advanced AOT parity tests
Host Context & Warrant Chain SES-019..024 Runtime.Security com.foundgine.runtime.security Foundgine.RedTeam + SupplyChain.PenTest
Bound ExecutionIR & Plan Cache SES-025 Core.Execution + Storage.Sql com.foundgine.core.execution ExecutionIR proof & cache isolation tests

Hybrid Retrieval & Approximate Candidate Fusion Architecture

Foundgine supports hybrid lexical, full-text, BM25, dense vector, and graph-neighborhood retrieval while strictly enforcing the invariant that retrieval never decides meaning or grants authority. All candidate sources implement ISemanticLexicalCandidateSource or IApproximateCandidateSource and feed normalized evidence scores into SemanticLexicalResolver:

Candidate Source Adapter Storage / Engine Scoring Mechanism Boundary Guardrail
In-Memory Exact & Weighted Alias Index MetadataRegistry (lock-free) Declared entity/field names + explicit WithAlias(..., weight) weights (1..100). Zero external I/O; deterministic sub-millisecond baseline.
PostgreSQL Trigram & FTS pg_trgm + tsvector Trigram similarity & ts_rank_cd normalized onto 0..100 scale. Capped by RetrievalTimeout = 2s; unknown tokens still fail closed.
ParadeDB BM25 Search pg_search (FOUNDGINE_PARADEDB_BM25=1) BM25 lexical relevance scoring over domain catalog terms and descriptions. Scores serve strictly as candidate proposals; multi-signature ties trigger RequiresClarification.
PostgreSQL Dense Vector (pgvector) pgvector HNSW / IVFFlat Cosine similarity against pre-embedded schema/alias descriptions. Vector similarity alone cannot override minimumAliasWeight or bypass row predicates.
Apache AGE Graph Similarity age openCypher (FOUNDGINE_POSTGRES_AGE=1) Structural neighborhood proximity across domain entity graphs. Every traversed edge must still exist in frozen MetadataRegistry and pass policy authorization.

Audit Receipt Verification & Tamper-Detection

Every committed read and mutation emits an immutable ExecutionReceipt / ExecutionEvidence record binding the frozen contract fingerprint, authorization decision digest, logical plan digest, and lowered ExecutionIR digest. Compliance auditors and automated verification jobs can validate historical receipts against the active MetadataRegistry and policy engine:

C# (.NET 10) — Verifying Stored ExecutionReceipt Provenance Digests
using Foundgine.Runtime.Audit;

// Verify that a persisted ExecutionReceipt matches the expected frozen contract fingerprint
// and carries non-empty cryptographic provenance hashes across all four pipeline boundaries.
public static bool VerifyReceiptIntegrity(
    ExecutionReceipt receipt,
    MetadataRegistry expectedRegistry)
{
    if (!string.Equals(receipt.ContractFingerprint, expectedRegistry.ContractFingerprint, StringComparison.Ordinal))
        return false;

    return !string.IsNullOrWhiteSpace(receipt.AuthorizationDecisionFingerprint)
        && !string.IsNullOrWhiteSpace(receipt.PlanFingerprint)
        && !string.IsNullOrWhiteSpace(receipt.ExecutionIrFingerprint)
        && receipt.ExecutedAtUtc <= DateTimeOffset.UtcNow;
}

Complete Multi-Ecosystem Package & Artifact Directory (v3.4.2)

Ecosystem Registry / Publisher Published Artifacts
.NET 10 (C#) NuGet (dero) Foundgine.Core, Foundgine.Runtime, Foundgine.Providers, Foundgine.Extensions, Foundgine.Aot
Java 27 Maven Central (io.github.cristianbarragan) foundgine-core, foundgine-runtime, foundgine-providers, foundgine-extensions, foundgine-aot-generator
TypeScript / JS npm (@foundgine) @foundgine/typescript, @foundgine/wasm
Python PyPI foundgine

End-to-End LLM Agent Tool-Calling & Clarification Loop Walkthrough

When an LLM agent (via Microsoft Agent Framework in .NET 10 or LangChain4j in Java 27) interacts with Foundgine over MCP, the boundary prevents prompt-injected guesses and unapproved writes through a deterministic multi-turn protocol:

Turn Agent / User Action Foundgine Boundary Execution Returned Structured Response
Turn 1 Agent calls foundgine_discover Verifies host JWT/warrant and filters MetadataRegistry entities/fields visible to caller's role. Returns allowed entity schemas, weighted aliases, and relationship hops (sensitive fields omitted).
Turn 2 Agent calls foundgine_query with "active customers" SemanticLexicalResolver detects 2 competing semantic signatures above threshold. Fails closed with RequiresClarification and lists both competing signatures for user disambiguation.
Turn 3 User clarifies; Agent calls foundgine_query_semantic Authorizes graph traversal, injects tenant row predicate, lowers to parameterized SQL, records receipt. Returns strictly authorized tenant rows + ExecutionReceipt provenance ID.
Turn 4 Agent proposes order escalation via foundgine_mutate_dry_run Authorizes target entity/fields, simulates mutation graph, computes SHA-256 PlanFingerprint. Returns deterministic dry-run preview + PlanFingerprint (zero DB rows modified).
Turn 5 Host governance signs fgmcp1; Agent calls foundgine_mutate_execute Verifies RSA-2048+ signature, exact PlanFingerprint match, consumes Redis jti nonce, commits tx. Commits business write + outbox event + durable audit receipt atomically.

SQL Dialect Lowering Comparison Matrix (PostgreSQL vs. SQLite vs. SQL Server)

ExecutionIRCompiler and the dialect emitters (PostgresSqlDialect, SqliteSqlDialect, SqlServerSqlDialect) preserve identical semantic ordering, null handling, and parameterization across database engines:

SQL Construct PostgreSQL SQLite SQL Server (T-SQL)
Identifier Quoting "schema"."table" "table" [schema].[table]
Parameter Syntax @p_0 / $1 @p_0 @p_0
Pagination & Tie-Breaker ORDER BY ... , pk ASC LIMIT @take OFFSET @skip ORDER BY ... , pk ASC LIMIT @take OFFSET @skip ORDER BY ... , pk ASC OFFSET @skip ROWS FETCH NEXT @take ROWS ONLY
Case-Insensitive String Match col ILIKE @pattern ESCAPE '\' LOWER(col) LIKE LOWER(@pattern) ESCAPE '\' LOWER(col) LIKE LOWER(@pattern) ESCAPE '\'
Outbox Concurrent Claiming FOR UPDATE SKIP LOCKED Single-writer serialized transaction WITH (UPDLOCK, READPAST, ROWLOCK)

Production Incident Response & Security Forensics Runbook

Immediate Warrant & Session Containment

  1. Revoke compromised warrant IDs or advance the issuer's monotonic revocation epoch in PostgreSQL (foundgine_warrant_revocation_anchor) and Redis—invalidating all active leaf warrants and delegation chains immediately.
  2. Rotate signing keys by publishing the new public key kid in JWKS/trust-roots and retiring the compromised kid.

Forensic Receipt & Event Stream Replay

  1. Query foundgine_audit_receipts by tenant_id, subject_id, or warrant_id to reconstruct every executed read/write, its contract_fp, plan_fp, and execution_ir_fp.
  2. Correlate correlation_id across foundgine_events and foundgine_outbox to trace downstream Temporal workflows and external side effects.

Deterministic Clock, Nonce Generation & Chaos Testing Harness

Time-dependent security invariants (warrant exp / nbf windows, fgmcp1 approval TTLs, outbox exponential retry backoff, and SSE session replay retention) are decoupled from system wall-clock time via injectable TimeProvider (.NET 10) and java.time.Clock (Java 27) abstractions:

Time-Travel Expiration & Skew Tests

  • Tests advance synthetic clocks across token TTL boundaries (e.g., +61s on a 60s activity warrant) to deterministically assert SecurityAuthorizationException without Thread.Sleep delays.
  • Configurable AllowedClockSkew (default 30s) bounds NTP drift across distributed nodes without permitting expired replay windows.

Fault-Injection & Fail-Closed Chaos Matrix

  • Simulated Redis Partition: Forces AnchoredSecurityWarrantRevocationStore to verify against PostgreSQL's durable GREATEST epoch anchor and deny ambiguous state.
  • Simulated Audit Sink Saturation: Verifies FailClosedOnAuditBackpressure = true aborts uncommitted mutations rather than silently dropping compliance receipts.

Complete DI Lifetimes & Thread-Safety Reference (.NET 10 & Java 27)

Correct service lifetimes prevent accidental cross-request state leakage of caller identity or tenant predicates:

Component Recommended Lifetime Thread-Safety & Isolation Guarantee
MetadataRegistry Singleton Deeply immutable after Build() / build(); lock-free concurrent reads across all threads.
ISemanticAuthorizationPolicy Singleton (stateless) Pure evaluation over SecurityExecutionContext and SemanticAuthorizationRequest; never caches per-user state on fields.
SqlExecutionProvider / Plan Cache Singleton Concurrent dictionary keyed by full SHA-256 SemanticPlanAuthorizationBinding digest + dialect.
SecurityExecutionContext Per-Request / Scoped Immutable record/class created fresh per HTTP/GraphQL/MCP call or Temporal activity; never stored in static fields.
FoundgineEfReader / EntityManager Scoped (Per-Unit-of-Work) Bound to the active request/transaction unit-of-work; disposed cleanly at request completion.

Multi-Region Active-Active & Disaster Recovery Architecture

Global Read Replicas & Deterministic Keyset Pagination

  • Read queries route to regional PostgreSQL read replicas while preserving identical row-level authorization predicates and deterministic primary-key tie-breaker ordering.
  • Because MetadataRegistry contract fingerprints and SQL plan caches are deterministic, regional nodes compute identical digests independently without cross-region coordination.

Regional Revocation & Outbox Failover

  • Primary-region writes commit business rows, foundgine_outbox entries, and foundgine_audit_receipts in one local ACID transaction; outbox workers replicate downstream events idempotently via idempotency_key.
  • Issuing short-lived warrants (TTL ≤ 5m) bounds exposure during cross-region revocation replication windows.

Zero-Downtime Schema & Semantic Contract Evolution Playbook

Because MetadataRegistry computes a deterministic SHA-256 ContractFingerprint at freeze time and binds that digest into active warrants and dry-run mutation approvals, rolling deployments follow a strict Expand → Migrate → Contract lifecycle to eliminate PlanBindingTamperedException errors during canary rollouts:

Rollout Phase Database & Model Change Warrant & Approval Behavior
1. Expand (Additive) Add nullable columns or new tables in PostgreSQL; register new entities, fields, and weighted aliases in FoundgineModel. Existing read queries continue uninterrupted; plan caches automatically partition by the new ContractFingerprint.
2. Dual-Version Canary Drain Route traffic across vN and vN+1 pods; issue short-lived dry-run approvals (TTL ≤ 60s) pinned to the serving node's contract version. If an approval created on vN lands on vN+1, PlanBindingTamperedException fails closed cleanly and triggers an immediate client dry-run refresh.
3. Contract (Deprecation) Remove deprecated aliases/fields from FoundgineModel only after 100% of nodes run vN+1, then drop legacy physical columns. Compile-time AOT source generators validate zero dangling references at build time before deployment.

Keyset Cursor Pagination & Deterministic Tuple Ordering Internals

Offset pagination (OFFSET N) degrades linearly on large tables and skips or duplicates rows when concurrent writes occur. Foundgine's cursor pagination compiles CursorSliceNode into parameterized lexicographic tuple comparisons anchored by the entity's primary key tie-breaker:

C# (.NET 10) — Keyset Cursor Query Across High-Volume Ledger
// Deterministic ordering: Total DESC, Id ASC (primary key tie-breaker injected automatically)
var page1 = await executor.ExecuteAsync(
    SemanticQuery.From(metadata, "SalesOrder")
        .Select("Id", "OrderNumber", "Total")
        .OrderByDesc("Total")
        .Take(50)
        .Build(),
    hostContext, ct);

// Resume deterministically from page1.NextCursor without OFFSET drift
var page2 = await executor.ExecuteAsync(
    SemanticQuery.From(metadata, "SalesOrder")
        .Select("Id", "OrderNumber", "Total")
        .OrderByDesc("Total")
        .AfterCursor(page1.NextCursor!)
        .Take(50)
        .Build(),
    hostContext, ct);
Lowered Parameterized SQL Tuple Comparison (PostgreSQL)
-- Cursor encodes { "sort": [2450.00, "0193a8f1-..."], "dir": ["DESC", "ASC"], "fp": "sha256:..." }
-- Cursor fingerprint is verified against the active query shape before binding!
SELECT o.ord_id, o.ord_number, o.ord_total
FROM erp.tbl_order o
WHERE o.tenant_id = @p_auth_tenant
  AND (
      o.ord_total < @p_cursor_0
      OR (o.ord_total = @p_cursor_0 AND o.ord_id > @p_cursor_1)
  )
ORDER BY o.ord_total DESC, o.ord_id ASC
LIMIT @p_take;

Complete Monorepo Build & Quality Gate Matrix

Workspace Root Entry Manifest Automated Verification Gate
src/csharp/ Foundgine.sln Unit, SQL/EF Core integration, Roslyn AOT parity, RedTeam (18 vectors), and PenTest (14 vectors).
src/java/ pom.xml JUnit 5 core/runtime/JPA/MCP/GraphQL/Keycloak/Temporal suites + annotation processor AOT parity.
src/conformance/ *.json vectors Cross-language semantic query, lexical grounding, and structural resource-limit equivalence checks.
src/typescript/ package.json TypeScript strict typecheck + MCP client & Temporal workflow runner tests.
src/python/ pyproject.toml pytest async MCP transport, clarification handling, and error taxonomy tests.
src/wasm/ Cargo.toml cargo test & wasm-bindgen parity checks against TypeScript/Python SDK contracts.

Custom Value Converters, Domain Value Objects & Null Semantics

Domain-driven codebases wrap primitives in strongly typed value objects (OrderId, TenantSlug, IsoCurrencyCode). ISemanticValueConverter<TDomain, TCanonical> (.NET 10) and SemanticValueConverter<D, C> (Java 27) translate domain value objects at the boundary so ExecutionIR and SQL parameter binders operate strictly on validated canonical scalars:

C# (.NET 10) — Strongly Typed Value Object Converter
using Foundgine.Core.Metadata;

public readonly record struct OrderId(Guid Value);

public sealed class OrderIdConverter : ISemanticValueConverter<OrderId, Guid>
{
    public Guid ToCanonical(OrderId domainValue) => domainValue.Value;
    public OrderId FromCanonical(Guid canonicalValue) => new(canonicalValue);
}

// Registered once in FoundgineModel:
// entity.Property(x => x.Id).HasColumn("ord_id").HasConverter<OrderIdConverter>();

Three-Valued Logic & Edge-Case Filter Semantics

  • Explicit Null Operators: Eq(field, null) is rejected at validation time; callers must use explicit IsNull(field) or IsNotNull(field) operators, which compile to IS NULL / IS NOT NULL.
  • Empty In(...) Sets: An empty collection passed to WhereIn(field, []) compiles deterministically to a false predicate (1 = 0) rather than invalid SQL IN () syntax.
  • LIKE Wildcard Escaping: User-supplied strings in Contains, StartsWith, and EndsWith automatically escape %, _, and \ before parameter binding.

Server-Side Cursor Streaming & Bounded Memory Backpressure

For regulated data exports, ledger reconciliation, and large batch inspections where buffering 100,000+ rows in heap memory would risk GC pauses or OOM kills, IFoundgineStreamingExecutor (.NET 10 IAsyncEnumerable<T>) and FoundgineStreamExecutor (Java 27 Stream<T>) stream rows over server-side forward-only database cursors under the exact same authorization and receipt guarantees:

C# (.NET 10) — Forward-Only Authorized Row Streaming (IAsyncEnumerable)
// Streams rows with constant O(1) fetch-buffer memory while enforcing tenant/column policy.
// ExecutionReceipt is finalized and flushed to BufferedDurableAuditLog upon stream completion or cancellation.
await foreach (var row in streamingExecutor.StreamAsync(exportQuery, hostContext, ct))
{
    await ndjsonWriter.WriteRowAsync(row, ct);
}

Architecture Decision Record (ADR) Catalog

ADR ID & Title Architectural Decision Trade-Off Accepted
ADR-001 · Frozen Semantic Contract Freeze MetadataRegistry at startup with an immutable SHA-256 fingerprint rather than mutating schema metadata dynamically per request. Schema updates require a rolling deployment or explicit registry reload, in exchange for lock-free concurrency and tamper-proof plan binding.
ADR-002 · Non-Authoritative Retrieval Forbid BM25, vector, and graph retrieval adapters from executing queries or resolving ambiguity autonomously. Ambiguous prompts require an extra clarification round-trip (RequiresClarification), eliminating silent misinterpretation of user intent.
ADR-003 · Host-Owned Security Context Require host middleware/adapters to construct SecurityExecutionContext exclusively from verified tokens/warrants. Transport adapters cannot accept convenience tenantId query parameters, guaranteeing immunity to payload identity spoofing.
ADR-004 · Two-Phase Signed Mutations Separate mutation dry-run planning from execution via a host-signed fgmcp1 token bound to the SHA-256 PlanFingerprint. Writes require a dry-run preview step, preventing unapproved or drifted LLM/client mutations from reaching storage.
ADR-005 · Algebraic ExecutionIR Boundary Lower logical plans into a closed ExecutionIR AST rather than passing raw SQL strings or unvalidated ORM expressions to providers. New storage backends implement a small algebraic translator, ensuring uniform predicate pushdown and plan-cache isolation across SQL, EF Core, and JPA.

Computed Virtual Fields, Derived Projections & Expression AST

Domain models frequently expose calculated attributes—such as LineTotal (Quantity * UnitPrice), IsOverdue (DueDate < CurrentUtc && Status != "PAID"), or DisplayLabel—that do not correspond 1:1 to a single physical column. FoundgineModel allows declaring read-only computed semantic fields using a closed, deterministic expression AST that lowers cleanly into SQL across PostgreSQL, SQLite, and SQL Server:

C# (.NET 10) — Declaring & Authorizing Computed Semantic Fields
// Declare a read-only derived field in FoundgineModel:
entity.ComputedProperty("LineTotal", SemanticType.Decimal, expr =>
    expr.Multiply(expr.Field("Quantity"), expr.Field("UnitPrice")));

// Policy benefit: A caller can be granted read access to 'LineTotal'
// while raw 'UnitPrice' or 'UnitCost' remains denied at the field projection gate!
var query = SemanticQuery.From(metadata, "PurchaseOrderLine")
    .Select("Sku", "Quantity", "LineTotal")
    .WhereGt("LineTotal", 500.00m)
    .Build();
Lowered Parameterized SQL (PostgreSQL)
SELECT l.sku,
       l.qty,
       (l.qty * l.unit_price) AS "LineTotal"
FROM erp.tbl_po_line l
WHERE l.tenant_id = @p_auth_tenant
  AND (l.qty * l.unit_price) > @p_0
ORDER BY l.po_line_id ASC
LIMIT @p_take;

Hierarchical & Self-Referential Traversals (Recursive CTE Lowering)

Manufacturing Bill-of-Materials (BOM), organizational reporting trees, and nested category graphs require bounded self-referential traversal. Foundgine compiles bounded hierarchical includes into parameterized WITH RECURSIVE common table expressions while enforcing SecurityResourceLimits.MaxSelectionDepth and injecting mandatory tenant predicates into both the anchor and recursive terms:

Lowered Parameterized PostgreSQL Recursive CTE (Tenant-Isolated & Depth-Bounded)
WITH RECURSIVE bom_tree AS (
    -- Anchor member (depth = 1) with mandatory tenant predicate
    SELECT p.part_id, p.parent_part_id, p.sku, 1 AS depth
    FROM erp.tbl_part p
    WHERE p.tenant_id = @p_auth_tenant
      AND p.part_id = @p_root_id
    UNION ALL
    -- Recursive member bounded by SecurityResourceLimits & tenant predicate at every hop
    SELECT c.part_id, c.parent_part_id, c.sku, t.depth + 1
    FROM erp.tbl_part c
    INNER JOIN bom_tree t ON c.parent_part_id = t.part_id
    WHERE c.tenant_id = @p_auth_tenant
      AND t.depth < @p_max_depth
)
SELECT part_id, parent_part_id, sku, depth
FROM bom_tree
ORDER BY depth ASC, part_id ASC;

End-to-End Integration Testing with Testcontainers (PostgreSQL + Redis + Keycloak)

For full-stack verification in CI without shared staging environments, Foundgine's integration suites spin up ephemeral PostgreSQL, Redis, and Keycloak containers via Testcontainers to validate real OIDC JWT verification, Redis Lua + PostgreSQL anchor revocation, SQL lowering, and transactional outbox delivery:

Java 27 (JUnit 5 + Testcontainers) — Ephemeral PostgreSQL & Redis Verification
@Testcontainers
class AnchoredRevocationIntegrationTest {

    @Container
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17-alpine");

    @Container
    static GenericContainer<?> redis = new GenericContainer<>("redis:7-alpine").withExposedPorts(6379);

    @Test
    void advancingPostgresAnchorEpoch_BlocksStaleWarrantsEvenIfRedisFlushes() {
        var store = AnchoredRevocationFactory.create(
            postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(),
            redis.getHost(), redis.getMappedPort(6379));

        store.advanceIssuerEpoch("https://auth.acme.example", 42L);
        redis.execInContainer("redis-cli", "FLUSHALL"); // Simulate cold Redis failover

        var decision = store.verifyAndConsume("https://auth.acme.example", "warrant-1", "jti-99", 41L, 300);
        assertFalse(decision.isAllowed());
        assertEquals("EPOCH_SUPERSEDED", decision.rejectionCode());
    }
}

Bounded Scalar Aggregations, Grouping & HAVING Lowering

Reporting dashboards and operational summaries require grouped aggregates (Count, Sum, Avg, Min, Max) without sacrificing row-level tenant isolation or exposing restricted columns. Foundgine lowers SemanticAggregateQuery into parameterized GROUP BY / HAVING SQL where mandatory authorization predicates execute in the pre-aggregation WHERE clause:

C# (.NET 10) — Policy-Governed Grouped Aggregation Query
// Policy verifies caller has read access to SalesOrder.Status and SalesOrder.Total
// and injects TenantId == @p_auth_tenant into the pre-aggregation WHERE clause.
var summaryQuery = SemanticAggregateQuery.From(metadata, "SalesOrder")
    .GroupBy("Status")
    .SelectCount("OrderCount")
    .SelectSum("Total", alias: "TotalRevenue")
    .HavingGt("TotalRevenue", 10000.00m)
    .OrderByDesc("TotalRevenue")
    .Build();
Lowered Parameterized SQL (PostgreSQL)
SELECT o.status AS "Status",
       COUNT(*) AS "OrderCount",
       SUM(o.ord_total) AS "TotalRevenue"
FROM erp.tbl_order o
WHERE o.tenant_id = @p_auth_tenant
GROUP BY o.status
HAVING SUM(o.ord_total) > @p_having_0
ORDER BY "TotalRevenue" DESC, o.status ASC;

Native AOT Source Generator & Annotation Processor Diagnostics (SES-018)

Foundgine.Providers.Aot.Generator (C# Roslyn incremental source generator) and foundgine-aot-generator (Java 27 JSR-269 annotation processor) validate domain annotations at compile time and emit reflection-free metadata builders that produce byte-for-byte identical ContractFingerprint digests to runtime fluent models:

Diagnostic ID Severity Compile-Time Check & Remediation
FG001 Error [FoundgineEntity] / @FoundgineEntity lacks a declared primary key ([FoundgineKey]); add a key property before building.
FG002 Error Duplicate entity name, physical table collision, or duplicate weighted alias declared across entities in the same model.
FG003 Error [FoundgineRelationship] references an undeclared target entity or mismatched foreign-key scalar type.
FG004 Error Alias weight outside valid inclusive range 1..100; adjust weight to a deterministic integer bound.
FG005 Info Emits deterministic GeneratedFoundgineMetadata builder and verifies zero reflection fallback paths for Native AOT / GraalVM.

Release Verification & Multi-Registry Publishing Checklist (v3.4.2)

Release Gate Verification Command / Artifact Pass Criterion
1. Cross-Language Conformance src/conformance/*.json across .NET 10 & Java 27 100% identical ASTs, contract fingerprints, and grounding/limit outcomes.
2. Adversarial Red-Team & PenTest Foundgine.RedTeam + SupplyChain.PenTest 32/32 adversarial probes fail closed with zero cross-tenant or unapproved writes.
3. Native AOT & Zero-Reflection dotnet publish -p:PublishAot=true + Maven AP build Zero trim/AOT warnings; SES-018 fingerprint matches fluent runtime builder.
4. Docs, SEO & Discovery Sync docs-site/foundgine-overview.html, sitemap.xml, robots.txt, llms.txt Valid XML sitemap, canonical URLs, Schema.org JSON-LD, and synchronized repo index.

Idempotency Keys, Retry Semantics & Exactly-Once Mutation Guarantees

Network timeouts between an MCP client, Temporal worker, or API gateway and the database can cause callers to retry a mutation whose initial commit already succeeded. Foundgine enforces deterministic idempotency across both synchronous mutations and asynchronous outbox dispatch:

1. Single-Use fgmcp1 Nonce + Idempotency Key

  • Every signed fgmcp1 approval carries a unique jti nonce consumed atomically in Redis/PostgreSQL on first execution; blind replays fail closed with WarrantReplayDetectedException.
  • Callers can supply an explicit business IdempotencyKey (e.g., order-req-98412) stored in the same ACID transaction so idempotent retries return the original committed ExecutionReceipt without re-executing side effects.

2. Outbox & Downstream Consumer Deduplication

  • foundgine_outbox.idempotency_key carries a UNIQUE database constraint derived from (tenant_id, receipt_id, topic, step_index).
  • At-least-once outbox workers pair exponential backoff + jitter with consumer-side deduplication so downstream Temporal workflows and webhooks achieve effective exactly-once state transitions.

Field-Level Masking & Dynamic Redaction Projections

In addition to binary column allow/deny pruning, SemanticAuthorizationDecision supports declarative field redaction transforms (MaskLast4, RedactEmail, Nullify) applied deterministically before rows leave the execution boundary:

C# (.NET 10) — Policy-Driven Partial Field Masking Without Breaking Row Queries
// Support agents can inspect Customer records and verify the last 4 digits of TaxId,
// while full TaxId values remain accessible only to 'compliance-officer' principals.
var decision = SemanticAuthorizationDecision.Allow(
    allowedFields: ["Id", "Name", "Email", "TaxId"],
    rowPredicate: SemanticFilter.Eq("TenantId", ctx.TenantId),
    fieldTransforms: new Dictionary<string, FieldRedactionMode>
    {
        ["TaxId"] = ctx.Roles.Contains("compliance-officer")
            ? FieldRedactionMode.None
            : FieldRedactionMode.MaskLast4,
        ["Email"] = ctx.Roles.Contains("compliance-officer")
            ? FieldRedactionMode.None
            : FieldRedactionMode.MaskLocalPart
    });

Cross-Runtime Footprint Profiles (.NET 10 JIT vs. Native AOT vs. Java 27)

Deployment Profile Cold Start Idle RSS Memory Metadata Initialization
.NET 10 Native AOT (PublishAot=true + Roslyn Generator) ~15 – 25 ms ~28 – 42 MB Zero reflection; compile-time static metadata graph.
.NET 10 Server JIT (Chiseled Container) ~85 – 140 ms ~65 – 95 MB Single startup freeze of MetadataRegistry; dynamic PGO warm-up.
Java 27 HotSpot JVM (foundgine-aot-generator) ~280 – 450 ms ~140 – 210 MB Annotation-processor generated builder; zero runtime reflection.

RFC 9457 Problem Details Mapping & Client Retry Matrix

HTTP, GraphQL, and MCP transport adapters translate internal Foundgine rejections into deterministic, non-leaky error envelopes (application/problem+json per RFC 9457 over HTTP, and structured JSON-RPC 2.0 error objects over /mcp) so clients never receive raw stack traces or database schema leaks:

Problem Type URN HTTP Status Retryable? Diagnostic Extension Fields
urn:foundgine:problem:clarification-required 422 Unprocessable Content Only after user disambiguation competingSignatures[], tokensExplored, pathsExplored
urn:foundgine:problem:authorization-denied 403 Forbidden No (fail-closed) contractFingerprint, correlationId (never leaks restricted field names)
urn:foundgine:problem:warrant-replay-or-revoked 403 Forbidden No (mint fresh warrant/approval) rejectionCode (REPLAY_DETECTED, WARRANT_REVOKED, EPOCH_SUPERSEDED)
urn:foundgine:problem:plan-binding-drift 409 Conflict Re-run dry-run & re-approve expectedContractFingerprint, actualContractFingerprint
urn:foundgine:problem:resource-limit-exceeded 400 Bad Request No (reduce depth/nodes/page size) limitKind (MaxSelectionDepth, MaxNodes, MaxPageSize), limitValue

Change Data Capture (CDC) & Asynchronous Retrieval Index Sync

When applications pair Foundgine with approximate candidate retrieval (ParadeDB BM25, PostgreSQL pg_trgm, pgvector, or Apache AGE), domain catalog updates flow out of foundgine_outbox or PostgreSQL logical replication slots to update search indexes asynchronously:

  • Zero Write-Path Coupling: Business transactions commit without waiting on external vector embedding or BM25 indexers.
  • Invariant Preservation: Even while an asynchronous index lags behind primary PostgreSQL state, SemanticLexicalResolver validates every candidate against the frozen MetadataRegistry and enforces current SQL-lowered row/column policies at execution time.

Multi-Language SDK Wire Protocol & Rust/WASM FFI Framing

SDK Package Transport & Serialization Engine Key Runtime Guarantees
@foundgine/typescript Fetch / HTTP/2 + SSE parser + strict TypeScript discriminated unions Zero runtime dependencies; native AbortSignal cancellation and automatic Last-Event-ID stream resumption.
foundgine (PyPI) httpx async/sync client + typed dataclasses / Pydantic-compatible models Supports both async with AsyncFoundgineClient(...) and synchronous workflows with structured clarification objects.
@foundgine/wasm Rust serde_json + wasm-bindgen WebAssembly core Identical JSON-RPC framing, retry backoff, and Temporal workflow helpers compiled to browser and edge-worker Wasm modules.

Multi-Service Federation & Delegated Warrant Topology

In microservice and federated architectures, independent bounded contexts (such as Orders, Inventory, and Billing) each maintain their own frozen MetadataRegistry and isolated database while honoring a single end-to-end user identity and tenant boundary:

1. Per-Service Frozen Domain Ownership

  • Each bounded-context service compiles and freezes its own domain MetadataRegistry, preventing monolithic schema coupling across teams.
  • An Apollo Federation Gateway or MCP orchestrator routes sub-requests to each service's /graphql or /mcp endpoint while forwarding the caller's verified bearer token or attenuated child warrant.

2. Monotonic Cross-Service Attenuation

  • When the Orders service calls the Inventory service on behalf of user:alice in tenant-alpha, it mints an attenuated child warrant scoped strictly to InventoryLot read operations with a 30-second TTL.
  • The Inventory service independently verifies the warrant's issuer trust root, delegation chain, Redis/PostgreSQL revocation epoch, and enforces its own SQL-lowered tenant-alpha predicate.

Composable Policy Combinators & Predicate Algebra

Rather than writing monolithic conditional branches inside a single authorization class, teams compose small, unit-testable policy rules using Foundgine's deterministic policy combinators (CompositeAuthorizationPolicy.AllOf(...)). Conjunction combines row-level predicates via logical AND and intersects allowed field projections:

C# (.NET 10) — Composing Tenant Isolation, Region Fencing & Role Field Gates
using Foundgine.Runtime.Authorization;

// Combine independent, single-responsibility authorization policies:
// 1. TenantIsolationPolicy   -> injects TenantId == ctx.TenantId
// 2. RegionFencingPolicy     -> injects RegionCode IN ctx.AllowedRegions
// 3. FinanceFieldGatePolicy  -> intersects AllowedFields, stripping UnitCost unless role == "finance"
var composedPolicy = CompositeAuthorizationPolicy.AllOf(
    new TenantIsolationPolicy(),
    new RegionFencingPolicy(),
    new FinanceFieldGatePolicy());

// Result:
// - RowPredicate   = (TenantId == @p_tenant) AND (RegionCode IN (@p_reg_0, @p_reg_1))
// - AllowedFields  = Intersection of all three policies' allowed field sets (fails closed if empty)

Capacity Sizing, Connection Pool Math & Latency SLO Reference

Subsystem Resource Recommended Sizing Formula Operational Rationale
PostgreSQL Pool (MaxPoolSize / HikariCP) (CPU_cores * 2) + effective_spindle_count (typically 16–32 per pod) Prevents PostgreSQL lock contention and context-switch thrashing under high concurrency (c=32+) while keeping warm plan-cache queries sub-15 ms.
BufferedDurableAuditLog Ring Buffer Peak_Write_RPS * Max_Flush_Latency_Sec * 4 (e.g., 8,192 slots) Absorbs transient PostgreSQL commit spikes without blocking writers; triggers fail-closed backpressure only if durable persistence stalls completely.
Outbox Worker Concurrency 2–4 concurrent FOR UPDATE SKIP LOCKED workers per replica, batch size 64 Sustains >2,500 outbox dispatches/sec per pod with negligible lock contention on ix_foundgine_outbox_pending.
Plan Cache Capacity Distinct_Shapes * Distinct_Role_Predicate_Signatures (typically < 2,000 entries) Bounded LRU/concurrent map (~15–30 MB RAM) guarantees >99.5% warm SQL template hit rate in steady state.

Binary Attachment Governance & Content-Addressed Object Storage

Enterprise entities (such as PurchaseOrder, ShipmentManifest, or ComplianceCertificate) frequently reference binary documents (PDF invoices, signed manifests, CAD drawings). Rather than streaming multi-megabyte blobs through ExecutionIR or LLM tool payloads, Foundgine stores immutable SHA-256 content digests and object keys in relational columns and mints short-lived, scope-bound pre-signed URIs only after row-level and field-level policy authorization succeeds:

1. Content-Addressed Digest & Integrity Binding

  • Binary uploads compute a SHA-256 content digest before commit; the digest and object key are written inside the same ACID mutation transaction as the parent business record.
  • Callers cannot forge or substitute object storage paths because physical storage keys are resolved strictly from authorized entity rows.

2. Policy-Gated Pre-Signed URI Minting

  • When a caller selects the virtual DownloadUri field, a post-authorization projection hook mints a 60s read-only S3 / Azure Blob / GCS URL bound to the verified TenantId and records the access in ExecutionReceipt.

Multi-Tier Rate Limiting, Quotas & Tenant Fairness Isolation

To protect downstream databases and lexical candidate sources from noisy-neighbor tenants or runaway agent loops, Foundgine pairs structural SecurityResourceLimits with multi-tier sliding-window token-bucket quotas evaluated immediately after host context verification:

Quota Dimension Keying Granularity Rejected Response
Read Execution Quota (TenantId, SubjectId) sliding window 429 Too Many Requests + Retry-After header + urn:foundgine:problem:quota-exceeded
Lexical Grounding Budget (TenantId, GroundingCallsPerMin) + LexicalBudget Caps BM25 / pgvector / Apache AGE retrieval fan-out before database saturation.
Mutation & Dry-Run Quota (TenantId, WriteOpsPerMin) Prevents runaway agent mutation proposal loops from flooding approval stores or outbox tables.

15-Minute Developer Onboarding Checklist (.NET 10 & Java 27)

Phase 1 · Model & Freeze (Minutes 1–5)

  1. Install Foundgine.Core + Foundgine.Runtime (.NET 10) or foundgine-core + foundgine-runtime (Java 27).
  2. Define your entities, weighted aliases, primary keys, and relationships in a FoundgineModel subclass and freeze MetadataRegistry as a singleton.

Phase 2 · Authorize & Verify (Minutes 6–10)

  1. Implement ISemanticAuthorizationPolicy / SemanticAuthorizationPolicy returning mandatory tenant row predicates and column allowlists.
  2. Run unit and adversarial cross-tenant tests in milliseconds using InMemoryExecutionProvider.

Phase 3 · Connect Storage & Surfaces (Minutes 11–15)

  1. Bind PostgreSQL / SQLite / SQL Server or your existing EF Core DbContext / JPA EntityManagerFactory.
  2. Mount /graphql and/or /mcp behind host OIDC/Keycloak authentication and inspect ExecutionReceipt logs.

Declarative Domain Invariants & Pre-Mutation Validation Hooks

Beyond structural schema types and row-level authorization, enterprise writes enforce domain invariants (such as Quantity > 0, ShipDate >= OrderDate, or external credit-limit checks) before any database transaction commits. Foundgine evaluates both declarative property constraints from MetadataRegistry and async domain validators (ISemanticMutationValidator / SemanticMutationValidator) during DryRunAsync and re-verifies them inside ExecuteApprovedAsync:

C# (.NET 10) — Declarative Constraints & Async Pre-Commit Mutation Validator
using Foundgine.Runtime.Mutations;

public sealed class PurchaseOrderInvariantValidator : ISemanticMutationValidator
{
    public ValueTask<MutationValidationResult> ValidateAsync(
        MutationValidationContext context,
        CancellationToken ct)
    {
        if (context.TargetEntity != "PurchaseOrder")
            return ValueTask.FromResult(MutationValidationResult.Valid());

        if (context.TryGetDecimal("Total", out var total) && total <= 0m)
            return ValueTask.FromResult(
                MutationValidationResult.Invalid("Total", "Order total must be strictly positive."));

        return ValueTask.FromResult(MutationValidationResult.Valid());
    }
}

Read-Your-Writes Consistency & Causal Session Tokens

When read queries are offloaded to asynchronous PostgreSQL read replicas, a user or agent reading immediately after committing a mutation could observe stale replica state unless causal ordering is preserved:

  • Causal Watermark Emission: MutationExecutionResult and ExecutionReceipt record the committed PostgreSQL Write-Ahead Log position (pg_current_wal_insert_lsn()) or monotonic stream version.
  • Replica Lag Routing: When a caller passes that causal token on a subsequent read, the host connection router compares pg_last_wal_replay_lsn() on replicas and automatically routes the query to the primary node until replicas catch up—preserving full tenant/column authorization transparently.

Production Troubleshooting & Diagnostic Decision Tree

Observed Symptom Root Cause Deterministic Resolution
PlanBindingTamperedException on ExecuteApprovedAsync Dry-run approval was minted against an older pod's ContractFingerprint during a rolling deploy, or payload fields were altered post-dry-run. Ensure MetadataRegistry is frozen identically across replicas; have client re-run DryRunAsync and obtain a fresh approval.
Frequent GroundingOutcome.RequiresClarification on known terms Two entities declare overlapping aliases with equal weights, or MinimumAliasWeight is set higher than candidate scores. Disambiguate alias weights in FoundgineModel (e.g., 95 vs 60) or use structured SemanticQuery / foundgine_query_semantic.
403 Forbidden despite valid JWT authentication ISemanticAuthorizationPolicy pruned all requested fields (empty projection set) or caller lacked an intermediate traversal hop permission. Inspect foundgine.security.denials_total tags and verify role permissions across every entity hop in SemanticOperationGraph.
EPOCH_SUPERSEDED after Redis restart Expected fail-closed protection: PostgreSQL's foundgine_warrant_revocation_anchor holds a higher monotonic epoch than the warrant's rev_seq. Mint a fresh warrant from the trusted root issuer reflecting the current revocation epoch.

Cryptographic Agility, KMS Key Rotation & Envelope Encryption

Long-lived enterprise platforms must rotate signing keys on schedule and respond to key compromise without breaking in-flight requests or invalidating historical compliance evidence:

1. Overlapping kid Rollover for Warrants & fgmcp1 Approvals

  • Trust roots publish active verification keys keyed by immutable Key ID (kid) via JWKS or KMS key rings.
  • During scheduled rotation, the new kid is added to verifiers before issuers switch signing to the new key, ensuring zero dropped validations while retaining instant single-kid revocation on compromise.

2. Tenant-Scoped Envelope Encryption (DEK / KEK)

  • Sensitive PII fields can be wrapped with tenant-specific Data Encryption Keys (DEKs) protected by a cloud KMS Key Encryption Key (KEK), ensuring crypto-shredding capability per tenant without altering ExecutionIR query semantics.

Custom Storage Provider SPI Implementation Guide

While Foundgine ships built-in providers for PostgreSQL, SQLite, SQL Server, EF Core, JPA/Hibernate, and InMemory testing, teams can bind bespoke datastores (such as ClickHouse, DuckDB, or internal RPC data services) by implementing IExecutionProvider (.NET 10) or ExecutionProvider (Java 27). Every custom provider must verify the SemanticPlanAuthorizationBinding proof before lowering ExecutionIR:

C# (.NET 10) — Custom ExecutionIR Provider Boundary Skeleton
using Foundgine.Core.Execution;

public sealed class CustomAnalyticsExecutionProvider : IExecutionProvider
{
    public async ValueTask<ExecutionResult> ExecuteAsync(
        BoundExecutionPlan boundPlan,
        CancellationToken ct)
    {
        // 1. Mandatory fail-closed gate: reject any IR lacking a valid authorization binding proof
        boundPlan.EnsureAuthorizedAndBound();

        // 2. Translate closed ExecutionIR AST (Scan, Filter, Join, Project, Sort, Slice)
        //    including all policy-injected row predicates and pruned field projections
        var translated = AnalyticsDialectLowerer.Lower(boundPlan.Ir);
        var rows = await ExecuteParameterisedAsync(translated, ct);

        return new ExecutionResult(rows, boundPlan.Binding.PlanFingerprint);
    }
}

Production Go-Live & Security Audit Sign-Off Matrix

Domain Production Requirement Verification Evidence
Identity & Transport Strict OIDC issuer/audience validation; explicit AllowedOrigins on /mcp; zero payload-derived identity claims. Integration tests rejecting untrusted Origin, wrong aud, and spoofed TenantId arguments.
Semantic Contract MetadataRegistry frozen once at startup; identical ContractFingerprint across all active pods. Startup readiness probe asserting expected contract digest and zero AOT drift (SES-018).
Authorization & Writes Mandatory row predicates lowered to SQL; dry-run PlanFingerprint + host-signed fgmcp1 required for all mutations. 32/32 passing adversarial vectors in Foundgine.RedTeam and SupplyChain.PenTest.
Revocation & Audit Redis Lua + PostgreSQL GREATEST revocation anchor active; FailClosedOnAuditBackpressure = true. Chaos test confirming stale warrants fail closed after Redis flush and audit receipts persist atomically.

Outbox & Webhook Payload Signing (HMAC-SHA256 & Ed25519)

When PostgresOutboxWorker dispatches committed domain events to external webhooks, partner APIs, or cross-cluster event buses, each outbound payload carries cryptographic authenticity and replay-prevention headers derived from the persisted foundgine_outbox record:

Canonical Outbound Signature Headers

  • X-Foundgine-Event-Id: <outbox_event_uuid>
  • X-Foundgine-Timestamp: <unix_epoch_seconds>
  • X-Foundgine-Key-Id: <active_signing_kid>
  • X-Foundgine-Signature: v1=<hex_hmac_or_ed25519>

Consumer Replay & Provenance Verification

  • Consumers verify the signature over "{timestamp}.{eventId}.{canonicalJsonBody}" using constant-time comparison and reject timestamps outside a 300s tolerance window.
  • Each event payload embeds receiptId and contractFingerprint so downstream services can trace every asynchronous side effect back to its originating ExecutionReceipt.

GraphQL Schema Stitching & Custom Federation Directives

In federated GraphQL gateways (Hot Chocolate Fusion, Apollo Router, or GraphQL Java Federation), Foundgine projects frozen MetadataRegistry entities into federated subgraphs with explicit @key entity resolvers and role-gated query roots:

C# (.NET 10) — Configuring Federated Entity Keys & Role-Gated GraphQL Roots
builder.Services.AddFoundgineGraphQL(gql =>
{
    // Enforce explicit role allowlists per exposed GraphQL root entity
    gql.QueryRootRoles["SalesOrder"] = ["sales", "finance", "support"];
    gql.QueryRootRoles["Customer"] = ["sales", "support"];

    // Enable @key entity reference resolution for GraphQL Federation gateways;
    // Reference resolvers still execute through FoundgineGraphQLQueryExecutor
    // with mandatory host-verified SecurityExecutionContext!
    gql.EnableFederationReferenceResolvers = true;
    gql.MaxSelectionDepth = 12;
});

Single-Command Cross-Ecosystem CI Smoke & Release Script

Run this unified verification script before tagging any Foundgine release to validate .NET 10, Java 27, TypeScript, Python, Rust/WASM, and SEO/Documentation assets in one deterministic pass:

Bash — Complete Multi-Language Release & Conformance Smoke Gate
#!/usr/bin/env bash
set -euo pipefail

# 1. .NET 10 Release Test Suite & Native AOT Publish Check
dotnet test src/csharp/Foundgine.sln -c Release
dotnet publish src/csharp/samples/Foundgine.SupplyChain -c Release -p:PublishAot=true

# 2. Java 27 Maven Reactor Build & Conformance / Security Verification
mvn -f src/java/pom.xml -B verify

# 3. Client SDKs (TypeScript, Python, Rust/WASM)
npm --prefix src/typescript ci && npm --prefix src/typescript test
pytest src/python/tests
cargo test --manifest-path src/wasm/Cargo.toml

# 4. Validate Documentation Sitemap XML & Robots.txt Integrity
xmllint --noout docs-site/sitemap.xml
grep -q "Sitemap: https://cristianbarragan.github.io/foundgine/sitemap.xml" docs-site/robots.txt
echo "All Foundgine v3.4.2 release gates passed."

OpenTelemetry Semantic Conventions & Distributed Trace Propagation

Foundgine instruments every boundary transition using W3C traceparent / tracestate propagation and deterministic ActivitySource("Foundgine") spans without leaking sensitive parameter values or restricted field names into telemetry attributes:

Span / Metric Name Kind Safe Cardinality Attributes
foundgine.semantic.resolve Span foundgine.contract.fingerprint, foundgine.grounding.outcome, foundgine.grounding.paths_explored
foundgine.security.authorize Span foundgine.entity, foundgine.operation.kind, foundgine.auth.decision
foundgine.execution.ir_run Span foundgine.provider (postgres, efcore, jpa), foundgine.plan.cache_hit, foundgine.rows.returned
foundgine.security.denials_total Counter foundgine.denial.category (tenant, field, warrant, replay, limit)

Soft-Delete Governance, Data Retention & GDPR Crypto-Shredding

Regulated enterprise domains require logical soft-deletion (DeletedAtUtc IS NULL) during active retention windows alongside verifiable erasure under GDPR / CCPA right-to-erasure mandates:

1. Automatic Soft-Delete Predicate Injection

  • Entities marked with .HasSoftDelete("deleted_at_utc") automatically inject deleted_at_utc IS NULL into every standard read query and relationship join unless a principal holds explicit IncludeDeleted policy authority.
  • Delete mutations on soft-deletable entities lower into parameterized UPDATE ... SET deleted_at_utc = @now statements while recording full ExecutionReceipt provenance.

2. Tenant & Subject Crypto-Shredding

  • PII columns wrapped with subject-scoped Data Encryption Keys (DEKs) can be irreversibly erased by destroying the subject's DEK in KMS while preserving non-PII financial ledger totals and tamper-evident audit hashes.

Active-Active Multi-Region Conflict Resolution & Deterministic Merge

For globally distributed deployments accepting writes in multiple regions, Foundgine pairs optimistic concurrency tokens (RowVersion / xmin) with deterministic conflict resolution policies declared per entity:

  • Strict Optimistic Abort (Financial & Inventory Ledgers): Concurrent updates targeting the same entity version fail closed with ConcurrencyConflictException (409 Conflict) so callers re-read authoritative state before retrying.
  • Monotonic State-Machine Lattice (Order & Fulfillment Status): Status transitions follow an explicit directed acyclic state lattice (e.g., DRAFT → SUBMITTED → APPROVED → SHIPPED), rejecting out-of-order regressions automatically during regional reconciliation.

Temporal Durable Workflow Determinism & Saga Compensation Playbook

Long-running multi-system processes (such as order fulfillment, credit reservation, and warehouse dispatch) use Foundgine.Extensions.Temporal (.NET 10) or com.foundgine.extensions.temporal (Java 27) to combine Temporal's deterministic workflow replay with Foundgine's short-lived activity warrants:

1. Deterministic Workflow vs. Side-Effecting Activity Split

  • Workflow Thread (Pure & Deterministic): Constructs serializable SemanticOperation / SemanticMutationIntent ASTs and forwards workflow-propagated identity headers—never performing direct database I/O or non-deterministic clock reads.
  • Activity Worker (Authorized Execution): Mints or verifies a short-lived activity warrant (TTL ≤ 60s), executes the dry-run/signed mutation inside an ACID database transaction, and returns the immutable ExecutionReceipt ID as the activity result.

2. Saga Compensation with Reverse Mutation Graphs

  • If step 3 (carrier label booking) fails permanently after step 1 (inventory reservation) and step 2 (ledger hold) committed, the Temporal saga executes pre-authorized compensating mutations referencing the original ExecutionReceipt correlation IDs.

Custom MCP Resources & Governed Prompt Templates (MCP 2025-06-18)

Alongside the core MCP tools (foundgine_discover, foundgine_query, foundgine_query_semantic, foundgine_mutate_dry_run, foundgine_mutate_execute), hosts can expose read-only MCP resources and parameterized prompt templates over /mcp—all gated by the caller's verified SecurityExecutionContext:

MCP Surface URI / Identifier Security & Boundary Enforcement
Resource foundgine://schema/authorized-catalog Returns only entities, relationships, and fields permitted for the caller's verified roles (restricted fields omitted).
Resource foundgine://audit/receipts/{receiptId} Enforces tenant_id == ctx.TenantId before returning provenance digests so tenants cannot inspect peer receipts.
Prompt reconcile-overdue-invoices Injects structured disambiguation hints and tenant-scoped filter parameters without bypassing RequiresClarification gates.

Database Index Tuning & Query Plan Optimization Guide (PostgreSQL)

Because Foundgine systematically injects tenant_id = @p_auth_tenant predicates and appends , pk ASC tie-breakers to every sorted query, aligning PostgreSQL composite indexes with these patterns yields single-index-scan execution plans:

PostgreSQL DDL — Tenant-Prefixed Keyset & Outbox Index Patterns
-- 1. Covering composite B-tree for tenant-scoped keyset pagination (Total DESC, Id ASC):
CREATE INDEX CONCURRENTLY ix_orders_tenant_total_id
    ON erp.tbl_order (tenant_id, ord_total DESC, ord_id ASC)
    INCLUDE (ord_number, ord_status)
    WHERE deleted_at_utc IS NULL;

-- 2. Partial index for FOR UPDATE SKIP LOCKED outbox workers:
CREATE INDEX CONCURRENTLY ix_foundgine_outbox_ready
    ON foundgine_outbox (next_attempt_at_utc, created_at_utc)
    WHERE status = 'PENDING';

Batch & Bulk Mutation Pipelines, Chunked Transactions & Failure Policies

High-throughput ingestion jobs, catalog imports, and scheduled reconciliations often submit hundreds or thousands of mutations rather than a single row write. Foundgine governs bulk operations through explicit chunk sizing, per-chunk dry-run authorization, and configurable atomicity policies:

1. Chunked Transaction vs. Atomic Batch Modes

  • All-or-Nothing Batch (AtomicityMode.StrictAllOrNothing): Executes all items in the mutation graph inside a single database transaction; if any item fails policy, invariant validation, or optimistic concurrency, the entire batch rolls back.
  • Bounded Chunked Batch (ChunkSize = N): Splits large mutation sets into fixed-size transactional chunks (e.g., 250 items per commit) so lock durations stay bounded and partial progress is recorded with per-chunk ExecutionReceipt IDs.

2. Deterministic Retry & Dead-Letter Handling

  • Transient deadlocks or serialization failures retry within the active chunk budget, while deterministic policy or validation rejections fail immediately without wasting retries.
  • Rejected items in partial-tolerant batch workflows emit structured rejection receipts rather than silently disappearing.

Zero-Trust Service Mesh, mTLS & SPIFFE/SPIRE Identity Integration

In zero-trust Kubernetes or service-mesh environments (Envoy, Istio, Linkerd with SPIFFE/SPIRE workload identities), network transport authentication and semantic execution authority reinforce one another without conflating workload identity with end-user or delegated agent authority:

Security Layer Mechanism Role in Foundgine Defense-in-Depth
Transport Identity SPIFFE SVIDs (spiffe://...) over mTLS Authenticates pod-to-pod and gateway-to-service channels at the network edge.
Caller & Tenant Context Verified OIDC / Keycloak JWT + Host Context Establishes immutable SubjectId, TenantId, Roles, and DelegationChain—never inferred from raw network IP or spoofable headers.
Action & Plan Binding Cryptographic Warrants + fgmcp1 + PlanFingerprint Binds high-impact writes and delegated sub-calls to exact operations, TTLs, and SHA-256 plan digests.

Compliance & Regulatory Control Mapping (SOC 2, ISO 27001, GDPR)

Because Foundgine enforces authorization, row-level predicate lowering, signed mutation approval, and immutable receipt recording at architectural boundaries rather than ad-hoc application code, engineering teams can map runtime primitives directly to compliance controls:

Compliance Concern Foundgine Control Mechanism Audit Artifact / Evidence
Least Privilege & Access Control Role- and policy-gated field projections + fail-closed grounding (RequiresClarification). SemanticAuthorizationDecision + foundgine.security.denials_total
Tenant & Data Segregation Mandatory host-verified row predicates lowered into parameterized SQL WHERE / WITH RECURSIVE. ExecutionIR + ExecutionIrFingerprint in foundgine_audit_receipts
Change & Write Integrity Two-phase dry-run (PlanFingerprint) + host-signed fgmcp1 + atomic outbox commit. Signed approval provenance + foundgine_outbox & foundgine_audit_receipts
Data Erasure & Retention Soft-delete predicates (deleted_at_utc) + tenant/subject DEK crypto-shredding. KMS key-destruction event + preserved non-PII receipt ledger

Incremental Adoption Playbooks, FAQ & Complete Site Map

Teams adopt Foundgine incrementally without rewriting existing databases, ORMs, or API gateways. Below are the three standard adoption paths, answers to common architectural questions, and a complete HTML site map of all documentation and machine-readable artifacts.

Three Incremental Adoption Playbooks

Playbook A · Existing EF Core / JPA Service

  1. Keep your existing DbContext / EntityManager and PostgreSQL/SQL Server/SQLite schema untouched.
  2. Author a FoundgineModel mapping your business entities and legacy table/column names.
  3. Route sensitive read/write paths through FoundgineEfReader or JpaEntities so tenant and role predicates enforce uniformly in SQL.

Playbook B · Hardening GraphQL & Adding MCP

  1. Mount MapFoundgineGraphQL (/graphql) with explicit QueryRootRoles allowlists.
  2. Enable /mcp alongside GraphQL—reusing the exact same MetadataRegistry, warrant verification, and row-level predicates in ~15 lines of wiring.

Playbook C · Native AOT & Zero-Reflection Builds

  1. Annotate domain records with [FoundgineEntity] (.NET) or @FoundgineModel (Java).
  2. Let Foundgine.Providers.Aot.Generator or FoundgineAotProcessor emit compile-time metadata builders with zero runtime reflection.

Frequently Asked Architectural Questions

Does Foundgine replace Hot Chocolate, GraphQL Java, EF Core, or JPA?

No. Foundgine complements them. Hot Chocolate and GraphQL Java act as thin transport adapters while Foundgine centralizes semantic modeling, lexical grounding, warrant verification, and row-level authorization—executing through SQL or your existing EF Core / JPA persistence layer.

Does Foundgine require AI, LLMs, or an MCP server?

No. Foundgine is designed for conventional .NET 10 and Java 27 backend systems first. AI agents, MCP, GraphQL, and Temporal workflows are optional consumer adapters over the same configured semantic capabilities.

How does Foundgine prevent LLM prompt injection from escalating privileges?

Caller input, capability discovery, retrieval scores, and model output are never treated as authority. Identity and tenant claims come strictly from host-verified tokens/warrants, ambiguous phrases fail closed with RequiresClarification, and write execution requires a host-signed fgmcp1 approval bound to the exact plan fingerprint.

How is cross-language parity between .NET 10 and Java 27 guaranteed?

Both runtimes share the five-concern fluent model, identical structural SecurityResourceLimits, and shared JSON conformance suites (src/conformance/) validated in CI on every change.

HTML Site Map & Machine-Readable Discovery Index