gnomonlearn
Docs/Algebra/RFC-0050

RFC-0050 · Template-Mediated Creation Contract

Versioned draft snapshot

RFCs, reference catalogs, and evidence reflect Spec 3b2e3e7a114fb826b1445d39a48756b8fff629cd. Counts and pending/status notes belong to that snapshot. Read the dated project update for later progress.

Source repositories are private during staging. Links marked “repository access required” need access to the linked repository.

Status Draft corpus. Reference catalogs and RDF projections have generation drift checks; Gnomon proofs and projection semantics remain unverified for release.

View the generated reference catalog →

Read design questions and decisions →


Reference catalog: the diagnostics, linked-RFC graph, defined terms, and normative-rule index for this RFC are in the reference catalog, generated from the structured Lean module. This document carries the prose: design rationale, entity-shape definitions in context, and migration notes.


1. Purpose

In Gnomon, the goal is everything is a template instantiation. A graph gnomon’s existence is the result of a template, invoked with arguments, by a principal, in a transaction. This produces strong, queryable provenance: given any gnomon, the framework can answer “what template instantiated me, with what arguments, in what transaction, by which principal, as a descendant of which calling template” — entirely from the graph itself.

This RFC formalizes that invariant. It specifies:

  • The single rule: gnomon creation is template-mediated. Direct writes to graph.resource and graph.statement are reserved to db.graph’s own intrinsic procedures and a small, audited set of system bootstrap paths. All other gnomon creation MUST go through a template.
  • The provenance statement schema attached to every template-instantiated gnomon.
  • The cross-template-call lineage rule: when template A invokes template B, B’s outputs carry a lineage chain ending at A’s invocation.
  • The core.provenance(a) projection (already named in RFC-0049 §13) — a queryable lineage subgraph for any gnomon.
  • The exception surface: bootstrap, system principal, and explicit elevation paths.

Together with RFC-0049 (projection algebra for reads), this RFC closes the write side of the algebraic story: every gnomon has provenance; every projection of an gnomon can include its lineage.


2. Definitions

TermMeaning
Template-mediated creationAn gnomon is created exclusively as the result of a template instantiation; never via direct DB write from outside db.graph.
Provenance statementAn edge-gnomon that records one fact about a created gnomon’s origin. There are six provenance predicates (§4).
Lineage subgraphThe closure of provenance statements rooted at any gnomon: the template, its arguments, the calling template (if any), the module, the principal.
Template invocation contextThe runtime context active during a template execution: the calling principal, the active transaction, the parent invocation (if nested), the input arguments.
Privileged write pathA small, named set of paths permitted to write graph.resource/graph.statement directly: the bootstrap loader (bootstrap.sql), the system installer principal during install (RFC-0041), and the db.graph.unrestricted capability (rare, audited).

3. The Single Rule

3.1 Statement

Every gnomon in the graph is the output of either:

  1. A template instantiation (RFC-0039 execution), OR
  2. A privileged-write path (§7).

Direct writes to graph.resource or graph.statement from anywhere else are prohibited.

3.2 Enforcement layers

The rule is enforced at three layers:

LayerMechanismDiagnostic
Compile timeMutation declarations (RFC-0049 §12) cannot reference graph.resource or graph.statement writes directlyM49090
Runtime APIThe graph client (RFC-0038) write methods (resources.create, statements.create, etc.) check the active execution context for a template invocation marker; absence is rejectedM50010
DatabaseRLS policies on graph.resource and graph.statement reject INSERT/UPDATE/DELETE from any role except the system installer or roles holding db.graph.unrestrictedM50011

3.3 The template invocation marker

The runtime maintains a per-request stack of template invocation frames. When the graph client receives a write call, it inspects the stack:

  • Stack non-empty → frame’s templateName, templateArgs, parentFrame, principalId are read; provenance statements are emitted.
  • Stack empty → the call is rejected (M50010) unless the caller carries explicit db.graph.unrestricted capability (§7.3).

The stack is pushed by the template executor (RFC-0039 §6) on entry and popped on exit. Nested template calls (RFC-0039 §6.1 Pass 1.5) push additional frames. The stack is bound to the request’s session context (RFC-0048).


4. Provenance Schema

Every template-instantiated gnomon carries provenance via six edge-gnomon predicates. These are reserved predicates registered by the db.graph module at bootstrap.

PredicateSubjectObjectCardinalityMeaning
template.instance_ofthe created gnomonthe template gnomon (kind core.template)1 outbound“I was created by this template”
template.instantiated_fromthe created gnomonthe template-call frame’s parent template (if nested)0..1 outbound“I was created within a call from this calling template”
template.withthe created gnomona hash-keyed argument record1 outbound“These were the arguments at instantiation time”
module.installed_bythe created gnomonthe module gnomon (kind core.module)1 outbound“This module’s invocation produced me”
principal.created_bythe created gnomonthe principal gnomon (RFC-0048 §3.6)1 outbound“This principal triggered my creation”
transaction.created_inthe created gnomonthe transaction gnomon (kind core.transaction)1 outbound“I was committed in this transaction”

4.1 Provenance statement timing

Provenance statements are emitted inside the same transaction as the created gnomon. They are committed atomically with the gnomon they describe. If the transaction rolls back, the gnomon and its provenance both vanish.

The statements are not visible to projection queries until commit (RFC-0036 §8 transactional semantics).

4.2 Argument record (template.with)

The template.with predicate’s object is an gnomon of kind core.template-args whose data carries the hashed and indexed argument shape:

core.template-args {
  templateName:  Text                  // FQN of the template
  argHash:       Text                  // SHA-256 of canonical-sorted-JSON of args (post-redaction)
  argRefs:       Map<String, Bigint>   // for resource-typed args, the resource id
}

Sensitive fields in arguments (RFC-0008 §6.3a sensitive) are redacted before hashing per RFC-0047 §6. The actual argument values are NOT stored in the graph — only their hash and resource references. Audit log emission (RFC-0047 §3) carries the full pre-redaction argument set.

4.3 Bootstrap exception predicates

Gnomons created by the privileged-write path (§7) get reduced provenance:

  • template.instance_of → omitted (no template)
  • template.instantiated_from → omitted
  • template.with → omitted
  • module.installed_by → present (the module that bootstrapped)
  • principal.created_by → system.bootstrap (the well-known bootstrap principal)
  • transaction.created_in → present

These gnomons are identifiable by absence of template.instance_of. Tooling MAY flag them.


5. The Provenance Projection

5.1 Built-in normative form

core.provenance(gnomonId) is a built-in projection (declared in core.template):

projection provenance {
  meaning: "Template-instantiation lineage of an gnomon."
  params { gnomonId: Identifier }
  returns: Subgraph

  body:
    byId(params.gnomonId)
      | union ( byId(params.gnomonId) | traverse [template.instance_of] )
      | union ( byId(params.gnomonId) | traverse [template.with] )
      | union ( byId(params.gnomonId) | closure(template.instantiated_from) )
      | union ( byId(params.gnomonId) | traverse [module.installed_by] )
      | union ( byId(params.gnomonId) | traverse [principal.created_by] )
      | union ( byId(params.gnomonId) | traverse [transaction.created_in] )
}

The output subgraph contains the gnomon itself, its template, its arguments record, the chain of calling templates back to the root invocation, the originating module, the principal, and the transaction.

5.2 Lineage projection (transitive)

core.lineage(gnomonId) extends provenance one level: it includes the provenance of every gnomon in the lineage subgraph, recursively. This produces a complete causal history.

Lineage projection has bounded depth (default 32; configurable via defaultConfig.lineage-max-depth per RFC-0046). Depth-bounded to prevent runaway closure on cyclic data.

5.3 Audit consumption

Audit log entries (RFC-0047 §3.1) include the operation’s primary gnomon id. Auditors retrieve full lineage by invoking core.lineage(id). This makes the audit trail self-describing inside the graph itself, complementing the externalized audit log.


6. Cross-Template-Call Lineage

When template A invokes template B (RFC-0039 §4.3 nested template calls), B’s outputs carry lineage that points back through both:

A's output ─[template.instance_of]──→ A
   │
   └─[template.instantiated_from]──→ (no parent — A is root)

B's output ─[template.instance_of]──→ B
   │
   └─[template.instantiated_from]──→ A

Following template.instantiated_from walks the call stack at instantiation time. The full chain is queryable via closure(template.instantiated_from) (§5.1).

6.1 Argument record sharing

A template’s argument record (core.template-args) is created once per top-level invocation. Gnomons produced in nested template calls reuse the parent’s record by adding their own template.with edge to it (with the nested template’s argHash overriding for that level).

This means a single core.template-args gnomon can be the object of multiple template.with edges in a single execution — auditors can identify the topmost call and walk down.

6.2 Sub-session attenuation interaction

Sub-sessions (RFC-0048 §4.5) created within a template execution inherit the template invocation marker. Gnomons created in the sub-session carry the same transaction.created_in, principal.created_by (the original session’s principal — sub-sessions do not change principal), and the sub-session’s frame in the lineage stack.


7. The Privileged-Write Path

The single rule (§3.1) admits three exceptions, all narrowly scoped and audited.

7.1 Bootstrap loader (bootstrap.sql)

The committed bootstrap.sql artifact (KP24, kernel-primitives.md §Physical Bootstrap Contract) writes the initial set of gnomons: the predicate registry, the kind-definition registry, the bootstrap module record, the system principal. These writes use direct INSERT against graph.resource and graph.statement.

The bootstrap loader runs as the studio_migrator role and is the only path that bypasses both the runtime template-marker check (§3.2) and the database RLS check.

After bootstrap, the db.graph module’s normal install path runs through the template engine like any other module — adding non-bootstrap state via templates.

7.2 System installer principal

During module install (RFC-0041), the system installer principal (principal.id = system.installer) holds db.graph.unrestricted capability and may write directly to graph.resource/graph.statement for module bootstrap rows (the module record, install-time predicates, the owns/module.depends_on/module.provides/module.installed_by ownership edges per RFC-0041 §11.2).

These writes carry provenance with template.instance_of omitted (§4.3) but module.installed_by and principal.created_by present. They are flagged in audit (RFC-0047 §3.1 includes the principalId).

7.3 Explicit elevation: db.graph.unrestricted

A capability scope (RFC-0040 §5.1.1) named db.graph.unrestricted permits direct writes from outside template invocations. It MUST be:

  • Reserved to the core capability scope (resolvable only from system contexts).
  • Granted via explicit provider declaration on the calling module.
  • Audited at every invocation: an audit log entry with unrestrictedCapability: true is mandatory (M50020).

Application modules MUST NOT request this capability. Any module manifest (RFC-0040) that declares db.graph.unrestricted in tokens: MUST be reviewed manually before approval; CI MAY block automatically (M50021).

The capability exists for genuine edge cases (cross-module garbage collection, schema introspection that creates cache entries, planner work) — not as an escape hatch for ordinary application logic.


8. Compile-Time Validation

The compiler enforces template-mediated creation at several points:

8.1 Mutation body validation (existing)

RFC-0049 §12.2 already requires mutations to express their work as template invocations. M49090 fires when a mutation body attempts a direct resources.create/statements.create call.

8.2 Operation body validation

For operation declarations (RFC-0043) — the lower-level form — the compiler checks the effects block:

  • Effect kinds resource.create, resource.update, resource.delete, statement.upsert, statement.remove MUST be wrapped in a template.compose step (RFC-0043 §5.1) or appear in a system-level operation in the db.graph namespace.
  • A user-namespace operation that emits direct resource/statement effects without template.compose MUST produce M50012.

8.3 Module manifest validation

Module manifests (RFC-0040) that declare objects of type resource or statement are creating gnomons via the install engine, not at runtime — this is the install-time privileged path (§7.2). The compiler MAY emit M50030 (info) noting that these objects will get reduced provenance.

8.4 Linker phase

During linker pass (RFC-0041 §9), every emitted gnomon is checked for required provenance statements (§4). Missing required statements (template.instance_of for non-bootstrap gnomons; module.installed_by and principal.created_by always) produce M50040.


9. Runtime Validation

The runtime enforces the rule at the graph client write boundary.

9.1 The marker check

TransactionalGraphClient.resources.create(input) (RFC-0038 §4.1) and equivalent methods inspect the request context for a template invocation marker:

function checkTemplateMarker(context):
  if context.templateFrames is empty:
    if not context.session.hasCapability("db.graph.unrestricted"):
      raise M50010

Statement creation, update, and invalidate paths perform the same check.

9.2 The database boundary

PostgreSQL RLS policies on graph.resource and graph.statement enforce a defense-in-depth check. The INSERT policy:

CREATE POLICY resource_insert ON graph.resource
FOR INSERT
WITH CHECK (
    graph.is_admin_session()
    OR current_setting('gnomon.template_marker', true) IS NOT NULL
    OR (NOT (kind <@ 'graph'::ltree) AND NOT (kind <@ 'core'::ltree))
);

The gnomon.template_marker GUC is set by the runtime when entering a template execution and cleared on exit. A direct INSERT without an admin session, without a template marker, and against a structural-meta kind (graph.* or core.*) is rejected (M50011).

This is the same SH2 trigger from kernel-primitives.md §SH2, refined to tie the structural-meta gate to the template-marker presence.


10. Invariants

  1. Every gnomon in the graph satisfies one of: (a) has template.instance_of outbound, or (b) was created by a privileged-write path with module.installed_by and principal.created_by present (§3.1, §4.3).
  2. template.instance_of, module.installed_by, principal.created_by, and transaction.created_in are mandatory on every gnomon (with the bootstrap exception of §4.3); missing any is a defect (M50040).
  3. Provenance statements are emitted in the same transaction as the created gnomon (§4.1).
  4. Sensitive arguments are redacted before hashing in template.with records (§4.2).
  5. core.provenance(gnomonId) returns a complete provenance subgraph for any gnomon (§5.1).
  6. Cross-template-call lineage is captured via template.instantiated_from chains (§6).
  7. The privileged-write path is restricted to bootstrap, system installer, and db.graph.unrestricted capability holders (§7).
  8. db.graph.unrestricted capability MUST be reserved to system contexts; application modules MUST NOT request it (§7.3, M50021).
  9. Direct INSERT into graph.resource/graph.statement outside a template marker or admin session is rejected by RLS (§9.2, M50011).
  10. The runtime template marker stack mirrors the template executor’s call stack (§3.3).

11. Compatibility and Migration

11.1 From legacy direct writes

The legacy graph client (@savvi-studio/graph-client) permits direct client.resources.create() calls without a template wrapper. Migration:

  1. Detection phase: enable M50010 as warning. Catalog all call sites; tag each as either “should be template-wrapped” or “needs db.graph.unrestricted capability.”
  2. Refactor phase: convert call sites to template invocations. The template engine (RFC-0039) MAY emit a “wrapper template” auto-derived for simple single-resource creations, easing migration.
  3. Strict phase: M50010 escalates from warning to error. New code cannot write directly.

The migration is per-module: a module with no remaining direct calls passes the strict gate; modules still in detection phase compile with warnings.

11.2 From legacy install paths

The legacy install engine writes module-bootstrap gnomons (owns, module.depends_on, etc.) via direct INSERT. After this RFC, the system installer principal continues to hold db.graph.unrestricted for these writes (§7.2) — no behavioral change. The provenance schema (§4.3) IS new; the install engine MUST be updated to emit module.installed_by and principal.created_by for every install-time gnomon.

11.3 From legacy gnomons without provenance

Gnomons in an existing graph that pre-date this RFC have no provenance statements. The framework MUST tolerate them:

  • core.provenance(legacyGnomon) returns the gnomon alone (no edges).
  • A core.lineage walk that reaches a legacy gnomon stops there (with a flag indicating “legacy origin”).
  • A future migration MAY back-fill best-effort provenance from audit.events — this is out of scope for this RFC.

The compiler emits M50050 (info) listing the legacy-gnomon count at install time so operators can plan back-fill.


Diagnostics

The diagnostic catalog for this RFC is authored in the structured Lean module and rendered in reference catalog § Diagnostics. Inline mentions in the prose above (e.g., “rejected with MNNxxx”) cross-link to the catalog at render time.

Linked References

The cross-RFC dependency graph is rendered in reference catalog § Linked References. Out-of-KG pointers to legacy code or external resources, when present, remain in this document under “Source-tree references” below.