[MACHINE-SPIRIT 1/8] Knowledge-representation foundations: logic, frames, DL/Datalog, events, typed open vocabularies #400

Closed
opened 2026-09-08 01:29:19 +00:00 by nsaspy · 4 comments
Owner

Parent: #397
Related: #388 #392
Downstream: lost-rob0t/symbolic-memory#4

Distinct research mandate

Study classical and modern knowledge-representation foundations as an independent design track: first-order/Horn/Datalog variants, frames/semantic networks, description logics/OWL-style modeling, conceptual graphs, event/state representations, typed feature structures, reification and provenance-aware knowledge graphs.

Required output

  • current primary/authoritative sources and implementations;
  • capability matrix versus #392;
  • at least three materially different candidate IR designs;
  • treatment of n-ary relations, quantification, identity, scope, reification, events and meta-knowledge;
  • extension mechanism for unfamiliar domains without a giant universal ontology;
  • safe Prolog lowering boundary;
  • adversarial analysis of expressiveness vs decidability/performance;
  • concrete recommendations/issue changes, preserving rejected alternatives.

Do not optimize for NLP extraction in this pass; assume semantics are already available and ask how they should be represented.

Parent: #397 Related: #388 #392 Downstream: lost-rob0t/symbolic-memory#4 ## Distinct research mandate Study classical and modern knowledge-representation foundations as an independent design track: first-order/Horn/Datalog variants, frames/semantic networks, description logics/OWL-style modeling, conceptual graphs, event/state representations, typed feature structures, reification and provenance-aware knowledge graphs. ## Required output - current primary/authoritative sources and implementations; - capability matrix versus #392; - at least three materially different candidate IR designs; - treatment of n-ary relations, quantification, identity, scope, reification, events and meta-knowledge; - extension mechanism for unfamiliar domains without a giant universal ontology; - safe Prolog lowering boundary; - adversarial analysis of expressiveness vs decidability/performance; - concrete recommendations/issue changes, preserving rejected alternatives. Do not optimize for NLP extraction in this pass; assume semantics are already available and ask how they should be represented.
Author
Owner

Auto-Research pass 1/8 — knowledge-representation foundations

Scope / research questions

This pass intentionally ignores NLP extraction quality and asks a narrower question: assuming the semantics are already known, what symbolic substrate should Machine Spirit use so that arbitrary knowledge is representable, inspectable, efficiently reasoned over, safely lowered into Prolog, and extensible without one giant ontology?

Questions investigated:

  1. Should the canonical IR be a graph/triple model, a first-order AST, a Datalog/Horn model, a frame/object model, or a hybrid?
  2. How should n-ary relations, quantification, proposition identity, context/scope, events, time, provenance, and meta-knowledge be represented without flattening meaning?
  3. What does the IR promise to reason about directly, versus merely preserve for another reasoner/profile?
  4. How do we keep open domain vocabulary while retaining decidable/tractable subsets and preventing generated terms from becoming host predicates?
  5. What representation best matches downstream Symbolic Memory’s append-only, provenance-rich world model?

Primary / authoritative sources inspected

  • W3C RIF Overview / Core / BLD: https://www.w3.org/TR/rif-overview/ , https://www.w3.org/TR/rif-core/ , https://www.w3.org/TR/rif-bld/ . Key lesson: W3C explicitly did not try to force all rules into one semantics. RIF uses a common core plus dialects; RIF-Core is essentially function-free Horn/Datalog with frame/object extensions, while BLD/PRD cover different rule paradigms.
  • W3C OWL 2 Profiles: https://www.w3.org/TR/owl2-profiles/ . EL, QL and RL make different expressiveness/performance trades. EL supports polynomial-time standard reasoning; QL is designed for query answering over large instance data through relational systems; RL is rule-friendly.
  • W3C RDF 1.2 Concepts / Semantics (Candidate Recommendation, 7 Apr 2026): https://www.w3.org/TR/rdf12-concepts/ and https://www.w3.org/TR/rdf12-semantics/ . RDF 1.2 triple terms/reifiers finally provide a standard distinction between a proposition and an assertion about that proposition; the same proposition can have multiple reifiers/sources and can remain unasserted.
  • W3C PROV-O Recommendation: https://www.w3.org/TR/prov-o/ . Separates Entity / Activity / Agent and models derivation/attribution as first-class provenance; it is deliberately extensible and mostly compatible with OWL-RL.
  • ISO/IEC 24707:2018 Common Logic: https://www.iso.org/standard/66249.html . Provides an abstract syntax/model-theoretic semantics for first-order information interchange and demonstrates that a broad logical interchange layer can remain independent of proof procedure.
  • Raymond Reiter, Knowledge in Action (MIT Press, 2001): https://mitpress.mit.edu/9780262527002/knowledge-in-action/ . Situation calculus gives a first-order account of actions, situations, change, sensing and knowledge.
  • Kowalski & Sergot, A Logic-Based Calculus of Events (New Generation Computing 4, 1986; DOI 10.1007/BF03037383). Event Calculus represents events, fluents and explicit time in logic-programming form and is especially relevant to append-only histories where later evidence may concern earlier events.
  • James Allen, Maintaining Knowledge about Temporal Intervals, CACM 26(11), 1983, DOI 10.1145/182.358434. The 13 interval relations remain a useful qualitative time algebra and have mechanically checked formalizations.
  • Marvin Minsky, A Framework for Representing Knowledge, MIT AI Memo 306 (1974): https://dspace.mit.edu/handle/1721.1/6089 . Frames remain useful as object/situation-centered views, especially for defaults/slots, but procedural attachments are dangerous as a primitive runtime semantics.

What current #392 gets right

The existing design already makes several strong calls:

  • immutable/versioned IR;
  • closed semantic kernel + open typed domain vocabulary;
  • normalized ground records instead of model-generated callable Prolog;
  • explicit identity, rules, procedures, events, temporal/modal/constraint knowledge;
  • provenance on material records;
  • strict distinction between semantic actions and executable capabilities;
  • explicit unknown/negation/scenario distinctions.

Those are correct and should survive.

Where #392 is currently too loose

The current conceptual forms (sem_relation, sem_rule, sem_event, sem_modal, etc.) are semantic categories and storage constructors at the same time. That risks building an ever-growing list of special-case record types.

The deeper issue is that the IR does not yet declare its logic profiles / entailment contracts. A record may contain universal variables, defaults, temporal qualification, modal attribution, or an OWL-like taxonomy, but a consumer cannot yet tell whether that package belongs to a tractable Horn fragment, a DL fragment, a temporal fragment, a constraint fragment, or a preservation-only fragment.

Without this, “general IR” can quietly become “arbitrary FOL plus Prolog implementation accidents.”

Candidate architecture A — proposition graph / RDF-1.2-inspired core

Everything important becomes a first-class proposition node plus assertion/context records.

Conceptually:

term(e1, entity).
proposition(p1, relation(maintains, [alice, project_x])).
assertion(a1, p1, asserted).
scope(a1, valid_interval(t1, t2)).
provenance(a1, source_span(src7, 100, 142)).

Rules/procedures are graphs over proposition nodes.

Strengths

  • excellent provenance, statement identity, attribution and conflict handling;
  • append-only persistence is natural;
  • interoperability with RDF 1.2 / PROV-O is straightforward;
  • n-ary relations can be native internally and exported through relation/event nodes.

Weaknesses

  • triples alone are not a satisfactory internal logic language for quantifier scope, defaults, rule variables or procedural structure;
  • reasoning requires a second layer anyway;
  • naive graph traversal can become expensive and semantically vague.

Decision: useful as persistence/interchange inspiration, insufficient as the whole semantic IR.

Candidate architecture B — Common-Logic-style universal formula AST

Represent arbitrary first-order formulas directly:

formula(f1,
  forall([x],
    implies(
      atom(instance_of,[x,bird]),
      atom(can_fly,[x])))).

Context/provenance wraps formula IDs.

Strengths

  • maximum semantic fidelity for quantifiers, variables, identity and nesting;
  • conceptually clean; Common Logic demonstrates a standardized abstract-semantics route;
  • easy to preserve statements even when no local reasoner supports them.

Weaknesses

  • unrestricted FOL loses the computational discipline we want;
  • easy to accidentally imply that every preserved formula is executable/queryable;
  • indexing and incremental materialization are harder;
  • defaults, epistemic modality and procedures still need explicit extra semantics.

Decision: retain a formula AST as a preservation/interchange capability, but do not make unrestricted FOL the default execution semantics.

Candidate architecture C — layered semantic kernel + declared reasoning profiles (preferred)

Use a tiny common algebra, then attach an explicit semantic profile to each theory/package/record set. This follows the strongest lesson from RIF and OWL profiles: shared syntax/identity does not imply one universal reasoning semantics.

Layer 1 — terms and vocabulary

sem_symbol(person, type).
sem_symbol(maintains, relation).
sem_signature(maintains, [person, project], boolean).
sem_subtype(maintainer, person).

Open domain vocabulary is data. Signatures/typing are validated but never converted to host predicates by name.

Layer 2 — propositions as first-class values

sem_prop(p17, atom(maintains, [alice, project_x])).
sem_prop(p18, atom(status, [project_x, healthy])).

N-ary relations are native. Proposition identity is separate from assertion. This directly adopts the useful RDF 1.2 distinction: a proposition can exist without being asserted, and multiple source/assertion objects may refer to the same proposition.

Layer 3 — sentence / logical structure

Use a closed ground AST:

sem_expr(e1, var(x)).
sem_expr(e2, atom(instance_of, [var(x), bird])).
sem_expr(e3, atom(can_fly, [var(x)])).
sem_expr(e4, implies(e2, e3)).
sem_expr(e5, forall([x], e4)).

Only closed constructors (atom, and, or, explicit_not, implies, forall, exists, equality, comparison...) are allowed. Domain relation symbols inside atom remain inert.

Layer 4 — assertion / stance / context envelope

sem_assertion(a9, p17,
              stance(asserted),
              context([world(actual), valid(t1,t2)]),
              provenance(prov42)).

sem_assertion(a10, p17,
              stance(claimed_by(source_b)),
              context([world(actual)]),
              provenance(prov51)).

Assertion identity is not proposition identity. This solves repeated sources, conflict, attribution, confidence and history cleanly.

Layer 5 — event/state/change vocabulary

Make events and fluents first-class semantic objects rather than only arbitrary relations:

sem_event(ev12, restart, [agent(system), object(service_x)]).
sem_occurs(ev12, t7).
sem_initiates(ev12, running(service_x), t7).
sem_terminates(ev12, stuck(service_x), t7).

Event-Calculus-style occurs/initiates/terminates should be the canonical change vocabulary because it maps naturally onto append-only memory and supports late-arriving historical evidence. Allen interval relations can be an optional standard temporal vocabulary for interval reasoning.

This does not require all world state to be recomputed through Event Calculus. Materialized holds_at/current views may be caches downstream.

Layer 6 — semantic profiles / dialects

Every theory/package declares what semantics it expects:

kernel_ground      ground propositions + contexts only
horn_safe          function-free Horn / Datalog-style rules
owl_rl_like        taxonomy/property fragment compatible with rule materialization
fol_preserve       arbitrary quantified formula, preserve/query structurally, no generic execution promise
temporal_event     event/fluent/change semantics
temporal_interval  Allen-style interval constraints
constraint_fd      trusted CLP(FD)-lowerable constraints
constraint_qr      trusted CLP(Q/R)-lowerable constraints
procedural         procedure/step/branch graph semantics
defeasible         default/exception semantics (defined separately by #394)

A package can compose several profiles only through explicit compatibility rules.

This gives semantic_capability/2 real teeth: the runtime can say represented != locally entailed != safely lowerable.

Safe lowering boundary

Recommended contract:

semantic_lower(+ValidatedPackage, +RequestedProfile, +Options, -Outcome).

Lower only if:

  1. the package declares the profile;
  2. every constructor belongs to that profile;
  3. all domain symbols are treated as data and mapped through trusted generic predicates;
  4. variables/quantifiers satisfy the profile’s safety/range restrictions;
  5. built-ins come from an allowlisted semantic builtin registry;
  6. the lowering target is a known trusted module/solver.

Example: horn_safe can become internal generic indexed facts/rules; constraint_fd may invoke validated CLP(FD); fol_preserve must not become arbitrary call/1.

Frames: projection, not primitive semantics

Minsky/F-logic-style frames are valuable for ergonomics:

service_x:
  type: service
  status: running
  owner: team_a

But a frame should be a materialized/object-centered view over canonical proposition/assertion records. Defaults and procedural attachments inside frames should lower into explicit default/procedure records, never implicit callbacks. This preserves frame ergonomics without hidden execution semantics.

Capability matrix versus #392

Concern Current #392 Preferred refinement
Open vocabulary yes keep, with versioned signatures
N-ary relations yes native atom args; never force triples internally
Proposition identity implicit make explicit and separate from assertion identity
Quantification planned closed formula AST + profile declaration
Scope/context metadata-ish first-class assertion context envelope
Attribution modal/claim forms stance on assertion over proposition
Provenance per record PROV-like derivation graph + assertion linkage
Events/change event record add explicit event/fluent/initiates/terminates semantics
Time generic temporal instant/interval core + event calculus + optional Allen algebra
Frames absent as primitive add object-centered projection only
DL/taxonomy generic type/subtype optional profile; do not impose OWL semantics globally
Rules generic sem_rule declare Horn/FOL/defeasible/etc. profile explicitly
Safe execution closed lowering additionally gate by profile capability
Unsupported semantics unclear preserve structurally with represented, not entailed

Complexity / scaling implications

  • Ground/kernel queries: indexed relation/entity lookup should be near database-style lookup cost.
  • Horn/Datalog profile: function-free rules give a finite Herbrand base; evaluation can use tabling/semi-naive materialization. This is the main zero-LLM reasoning workhorse.
  • OWL-style profiles: use only deliberately chosen fragments. OWL 2’s own profile split is proof that taxonomy reasoning needs explicit computational contracts; do not promise full OWL-DL behavior in generic Prolog.
  • Unrestricted quantified FOL: store/preserve, but no generic termination/decidability guarantee.
  • Temporal Event Calculus: append-only events are a good fit, but unrestricted abduction/default reasoning can become expensive; require bounded/query-directed reasoning or materialized current-state views.
  • Allen interval algebra: qualitative interval consistency can be useful, but complete networks can grow quadratically in interval pairs; keep query/projection bounded.
  • Provenance: store derivation edges separately and index by proposition/assertion/source. Do not duplicate the whole proof tree inside each fact.

Epistemic / provenance implications

The most important change is proposition != assertion.

P                         abstract proposition
A1 asserts P              source 1 / time 1 / confidence x
A2 claims P               source 2 / time 2
A3 explicitly denies P    source 3
D1 derives P              rule set r / premises ...

This structure makes contradiction, corroboration, supersession and model-vs-source provenance downstream operations over assertion objects instead of mutating the proposition itself.

PROV-O’s Entity/Activity/Agent model is a good interoperability vocabulary, but the internal provenance model should remain smaller and domain-neutral; map to PROV-O at export boundaries.

Safety / authority implications

  • A semantic symbol called shell, restart, delete, or call remains a domain symbol.
  • No open-vocabulary symbol resolves by name to a Prolog predicate.
  • Profile selection itself is not authority; it only selects a trusted semantic interpreter/lowerer.
  • fol_preserve and unknown extension profiles are inert except for inspection/retrieval/export.
  • Frame procedural attachments are forbidden as callbacks; procedures remain symbolic until a trusted host separately maps admitted actions to capabilities.
  • Importing OWL/RDF/RIF data does not import host authority.

Adversarial review

Attack: “One universal AST is cleaner”

It is cleaner syntactically but dangerously vague operationally. If everything can express everything, callers start assuming the Prolog runtime can reason soundly/terminatingly over everything. Profiles prevent that semantic lie.

Attack: “Just use RDF 1.2”

RDF 1.2 substantially improves statement-level metadata, but triple graphs still do not natively express the full scoped quantified/default/procedural semantics Machine Spirit needs. RDF should be an interchange projection, not the canonical internal model.

Attack: “Just use OWL”

OWL is excellent for ontology/class/property semantics, but procedures, event dynamics, defaults, arbitrary rules and attributed/conflicting claims are outside its core sweet spot. Even OWL itself uses profiles because expressiveness changes computational properties.

Attack: “Just use Prolog terms directly”

That collapses data and execution and makes persistence/versioning/security harder. The repo’s existing authority rules already reject this direction.

Attack: “Every record gets a unique proposition ID, easy”

Bad: semantically identical propositions from multiple sources would never corroborate. Proposition canonicalization needs deterministic structural fingerprints within a declared vocabulary/schema version, while assertion IDs remain source/run-specific. Cross-memory identity reconciliation must remain reversible downstream.

Attack: “Canonicalize everything globally”

Also bad: local symbols, time-varying names, hypothetical entities and versioned ontologies make global same-as unsafe. Canonicalization should be syntactic/structural; semantic identity links remain explicit knowledge.

Rejected alternatives

  1. Pure RDF/triple store as canonical IR — loses too much rule/quantifier/procedure structure or requires elaborate ad-hoc reification.
  2. Unrestricted Common Logic/FOL as executable core — expressive but gives the runtime no tractability/termination contract.
  3. Frame system as canonical semantics — object ergonomics are good, but defaults/procedural attachments create hidden semantics and authority hazards.
  4. One enormous fixed predicate ontology — incompatible with unfamiliar domains and guarantees core churn.
  5. One monolithic sem_record(Type, Payload, Meta) blob — easy persistence, terrible invariant enforcement and reasoning guarantees.

Concrete recommendations to canonical issues

#392 — change required

Add these design invariants:

  1. explicit proposition identity separate from assertion identity;
  2. closed ground formula AST for variables/quantifiers/composition;
  3. versioned semantic profile/dialect declaration for reasoning guarantees;
  4. native n-ary atoms; RDF/triple is export/interchange, not mandatory internal shape;
  5. explicit event/fluent/change vocabulary inspired by Event Calculus;
  6. instant + interval temporal vocabulary, with Allen relations as an optional profile;
  7. frames as derived/materialized views only;
  8. distinguish represented, validated, entailed/queryable, and safely_lowerable support levels;
  9. structural proposition fingerprinting separated from source-specific assertion IDs;
  10. extension profiles must declare signatures + supported semantic operators, not just relation names.

#394 — later reasoning pass dependency

#394 should consume the profile/dialect declaration instead of implementing one global evaluator over every semantic constructor. Default/exception/paraconsistency semantics should be a distinct profile and not silently contaminate strict Horn inference.

symbolic-memory#4/#6

Persist proposition records and assertion/context/provenance records separately enough that many assertions may reference the same proposition. Current/history views operate over assertions, not by mutating proposition payloads. Materialized frame/current-state views remain rebuildable indexes.

symbolic-memory#10

Identity reconciliation should not rewrite proposition structural IDs. Entity same-as/likely-same-as/renaming remains explicit reversible semantic knowledge; proposition equivalence can be a separate derived relation.

Preferred design summary

Machine Spirit should not have one universal logic. It should have one universal symbolic interchange kernel with explicit, composable reasoning profiles.

The canonical substrate is:

terms + signatures
      ↓
first-class propositions / formula AST
      ↓
assertion + stance + context + provenance
      ↓
event/state/change objects where applicable
      ↓
profile declaration
      ↓
trusted profile-specific reasoners/lowerers
      ↓
materialized views / export adapters

That keeps arbitrary knowledge representable while making computational promises honest.

Unresolved questions to preserve for later passes

  • Exact canonicalization rules for formulas with alpha-renamed variables and commutative conjunctions.
  • Whether proposition identity should include ontology/vocabulary version or carry it only in context; current recommendation is include semantic vocabulary version in structural fingerprint.
  • How multiple reasoning profiles compose without semantic incoherence.
  • Whether event-calculus fluents are kernel constructs or the first standard extension profile.
  • Exact relationship between strict negation, default negation and paraconsistent conflict; defer to pass 3/#400.
  • Query-planning/materialization policy for huge Horn + temporal datasets; defer to passes 5/6.
  • Whether OWL-RL-compatible import/export deserves a standard profile in v1 or only a mapper.

Pass conclusion

#398 is design-complete from the KR-foundations perspective. It does not prove implementation or Machine Spirit acceptance. The next pass should be #399 semantic compilation and should treat this representation as a target contract to attack, not as unquestionable truth.

## Auto-Research pass 1/8 — knowledge-representation foundations ### Scope / research questions This pass intentionally ignores NLP extraction quality and asks a narrower question: **assuming the semantics are already known, what symbolic substrate should Machine Spirit use so that arbitrary knowledge is representable, inspectable, efficiently reasoned over, safely lowered into Prolog, and extensible without one giant ontology?** Questions investigated: 1. Should the canonical IR be a graph/triple model, a first-order AST, a Datalog/Horn model, a frame/object model, or a hybrid? 2. How should n-ary relations, quantification, proposition identity, context/scope, events, time, provenance, and meta-knowledge be represented without flattening meaning? 3. What does the IR promise to reason about directly, versus merely preserve for another reasoner/profile? 4. How do we keep open domain vocabulary while retaining decidable/tractable subsets and preventing generated terms from becoming host predicates? 5. What representation best matches downstream Symbolic Memory’s append-only, provenance-rich world model? ### Primary / authoritative sources inspected - W3C **RIF Overview / Core / BLD**: https://www.w3.org/TR/rif-overview/ , https://www.w3.org/TR/rif-core/ , https://www.w3.org/TR/rif-bld/ . Key lesson: W3C explicitly did **not** try to force all rules into one semantics. RIF uses a common core plus dialects; RIF-Core is essentially function-free Horn/Datalog with frame/object extensions, while BLD/PRD cover different rule paradigms. - W3C **OWL 2 Profiles**: https://www.w3.org/TR/owl2-profiles/ . EL, QL and RL make different expressiveness/performance trades. EL supports polynomial-time standard reasoning; QL is designed for query answering over large instance data through relational systems; RL is rule-friendly. - W3C **RDF 1.2 Concepts / Semantics** (Candidate Recommendation, 7 Apr 2026): https://www.w3.org/TR/rdf12-concepts/ and https://www.w3.org/TR/rdf12-semantics/ . RDF 1.2 triple terms/reifiers finally provide a standard distinction between a proposition and an assertion about that proposition; the same proposition can have multiple reifiers/sources and can remain unasserted. - W3C **PROV-O** Recommendation: https://www.w3.org/TR/prov-o/ . Separates Entity / Activity / Agent and models derivation/attribution as first-class provenance; it is deliberately extensible and mostly compatible with OWL-RL. - ISO/IEC **24707:2018 Common Logic**: https://www.iso.org/standard/66249.html . Provides an abstract syntax/model-theoretic semantics for first-order information interchange and demonstrates that a broad logical interchange layer can remain independent of proof procedure. - Raymond Reiter, **Knowledge in Action** (MIT Press, 2001): https://mitpress.mit.edu/9780262527002/knowledge-in-action/ . Situation calculus gives a first-order account of actions, situations, change, sensing and knowledge. - Kowalski & Sergot, **A Logic-Based Calculus of Events** (New Generation Computing 4, 1986; DOI 10.1007/BF03037383). Event Calculus represents events, fluents and explicit time in logic-programming form and is especially relevant to append-only histories where later evidence may concern earlier events. - James Allen, **Maintaining Knowledge about Temporal Intervals**, CACM 26(11), 1983, DOI 10.1145/182.358434. The 13 interval relations remain a useful qualitative time algebra and have mechanically checked formalizations. - Marvin Minsky, **A Framework for Representing Knowledge**, MIT AI Memo 306 (1974): https://dspace.mit.edu/handle/1721.1/6089 . Frames remain useful as object/situation-centered *views*, especially for defaults/slots, but procedural attachments are dangerous as a primitive runtime semantics. ### What current #392 gets right The existing design already makes several strong calls: - immutable/versioned IR; - closed semantic kernel + open typed domain vocabulary; - normalized ground records instead of model-generated callable Prolog; - explicit identity, rules, procedures, events, temporal/modal/constraint knowledge; - provenance on material records; - strict distinction between semantic actions and executable capabilities; - explicit unknown/negation/scenario distinctions. Those are correct and should survive. ### Where #392 is currently too loose The current conceptual forms (`sem_relation`, `sem_rule`, `sem_event`, `sem_modal`, etc.) are **semantic categories and storage constructors at the same time**. That risks building an ever-growing list of special-case record types. The deeper issue is that the IR does not yet declare its **logic profiles / entailment contracts**. A record may contain universal variables, defaults, temporal qualification, modal attribution, or an OWL-like taxonomy, but a consumer cannot yet tell whether that package belongs to a tractable Horn fragment, a DL fragment, a temporal fragment, a constraint fragment, or a preservation-only fragment. Without this, “general IR” can quietly become “arbitrary FOL plus Prolog implementation accidents.” ## Candidate architecture A — proposition graph / RDF-1.2-inspired core Everything important becomes a first-class proposition node plus assertion/context records. Conceptually: ```prolog term(e1, entity). proposition(p1, relation(maintains, [alice, project_x])). assertion(a1, p1, asserted). scope(a1, valid_interval(t1, t2)). provenance(a1, source_span(src7, 100, 142)). ``` Rules/procedures are graphs over proposition nodes. **Strengths** - excellent provenance, statement identity, attribution and conflict handling; - append-only persistence is natural; - interoperability with RDF 1.2 / PROV-O is straightforward; - n-ary relations can be native internally and exported through relation/event nodes. **Weaknesses** - triples alone are not a satisfactory internal logic language for quantifier scope, defaults, rule variables or procedural structure; - reasoning requires a second layer anyway; - naive graph traversal can become expensive and semantically vague. **Decision:** useful as persistence/interchange inspiration, insufficient as the whole semantic IR. ## Candidate architecture B — Common-Logic-style universal formula AST Represent arbitrary first-order formulas directly: ```prolog formula(f1, forall([x], implies( atom(instance_of,[x,bird]), atom(can_fly,[x])))). ``` Context/provenance wraps formula IDs. **Strengths** - maximum semantic fidelity for quantifiers, variables, identity and nesting; - conceptually clean; Common Logic demonstrates a standardized abstract-semantics route; - easy to preserve statements even when no local reasoner supports them. **Weaknesses** - unrestricted FOL loses the computational discipline we want; - easy to accidentally imply that every preserved formula is executable/queryable; - indexing and incremental materialization are harder; - defaults, epistemic modality and procedures still need explicit extra semantics. **Decision:** retain a formula AST as a preservation/interchange capability, but do not make unrestricted FOL the default execution semantics. ## Candidate architecture C — layered semantic kernel + declared reasoning profiles **(preferred)** Use a tiny common algebra, then attach an explicit **semantic profile** to each theory/package/record set. This follows the strongest lesson from RIF and OWL profiles: shared syntax/identity does not imply one universal reasoning semantics. ### Layer 1 — terms and vocabulary ```prolog sem_symbol(person, type). sem_symbol(maintains, relation). sem_signature(maintains, [person, project], boolean). sem_subtype(maintainer, person). ``` Open domain vocabulary is data. Signatures/typing are validated but never converted to host predicates by name. ### Layer 2 — propositions as first-class values ```prolog sem_prop(p17, atom(maintains, [alice, project_x])). sem_prop(p18, atom(status, [project_x, healthy])). ``` N-ary relations are native. Proposition identity is separate from assertion. This directly adopts the useful RDF 1.2 distinction: a proposition can exist without being asserted, and multiple source/assertion objects may refer to the same proposition. ### Layer 3 — sentence / logical structure Use a closed ground AST: ```prolog sem_expr(e1, var(x)). sem_expr(e2, atom(instance_of, [var(x), bird])). sem_expr(e3, atom(can_fly, [var(x)])). sem_expr(e4, implies(e2, e3)). sem_expr(e5, forall([x], e4)). ``` Only closed constructors (`atom`, `and`, `or`, `explicit_not`, `implies`, `forall`, `exists`, equality, comparison...) are allowed. Domain relation symbols inside `atom` remain inert. ### Layer 4 — assertion / stance / context envelope ```prolog sem_assertion(a9, p17, stance(asserted), context([world(actual), valid(t1,t2)]), provenance(prov42)). sem_assertion(a10, p17, stance(claimed_by(source_b)), context([world(actual)]), provenance(prov51)). ``` Assertion identity is **not** proposition identity. This solves repeated sources, conflict, attribution, confidence and history cleanly. ### Layer 5 — event/state/change vocabulary Make events and fluents first-class semantic objects rather than only arbitrary relations: ```prolog sem_event(ev12, restart, [agent(system), object(service_x)]). sem_occurs(ev12, t7). sem_initiates(ev12, running(service_x), t7). sem_terminates(ev12, stuck(service_x), t7). ``` Event-Calculus-style `occurs/initiates/terminates` should be the canonical *change* vocabulary because it maps naturally onto append-only memory and supports late-arriving historical evidence. Allen interval relations can be an optional standard temporal vocabulary for interval reasoning. This does **not** require all world state to be recomputed through Event Calculus. Materialized `holds_at`/current views may be caches downstream. ### Layer 6 — semantic profiles / dialects Every theory/package declares what semantics it expects: ```text kernel_ground ground propositions + contexts only horn_safe function-free Horn / Datalog-style rules owl_rl_like taxonomy/property fragment compatible with rule materialization fol_preserve arbitrary quantified formula, preserve/query structurally, no generic execution promise temporal_event event/fluent/change semantics temporal_interval Allen-style interval constraints constraint_fd trusted CLP(FD)-lowerable constraints constraint_qr trusted CLP(Q/R)-lowerable constraints procedural procedure/step/branch graph semantics defeasible default/exception semantics (defined separately by #394) ``` A package can compose several profiles only through explicit compatibility rules. This gives `semantic_capability/2` real teeth: the runtime can say **represented != locally entailed != safely lowerable**. ### Safe lowering boundary Recommended contract: ```prolog semantic_lower(+ValidatedPackage, +RequestedProfile, +Options, -Outcome). ``` Lower only if: 1. the package declares the profile; 2. every constructor belongs to that profile; 3. all domain symbols are treated as data and mapped through trusted generic predicates; 4. variables/quantifiers satisfy the profile’s safety/range restrictions; 5. built-ins come from an allowlisted semantic builtin registry; 6. the lowering target is a known trusted module/solver. Example: `horn_safe` can become internal generic indexed facts/rules; `constraint_fd` may invoke validated CLP(FD); `fol_preserve` **must not** become arbitrary `call/1`. ### Frames: projection, not primitive semantics Minsky/F-logic-style frames are valuable for ergonomics: ```text service_x: type: service status: running owner: team_a ``` But a frame should be a **materialized/object-centered view** over canonical proposition/assertion records. Defaults and procedural attachments inside frames should lower into explicit default/procedure records, never implicit callbacks. This preserves frame ergonomics without hidden execution semantics. ## Capability matrix versus #392 | Concern | Current #392 | Preferred refinement | |---|---|---| | Open vocabulary | yes | keep, with versioned signatures | | N-ary relations | yes | native atom args; never force triples internally | | Proposition identity | implicit | make explicit and separate from assertion identity | | Quantification | planned | closed formula AST + profile declaration | | Scope/context | metadata-ish | first-class assertion context envelope | | Attribution | modal/claim forms | stance on assertion over proposition | | Provenance | per record | PROV-like derivation graph + assertion linkage | | Events/change | event record | add explicit event/fluent/initiates/terminates semantics | | Time | generic temporal | instant/interval core + event calculus + optional Allen algebra | | Frames | absent as primitive | add object-centered projection only | | DL/taxonomy | generic type/subtype | optional profile; do not impose OWL semantics globally | | Rules | generic `sem_rule` | declare Horn/FOL/defeasible/etc. profile explicitly | | Safe execution | closed lowering | additionally gate by profile capability | | Unsupported semantics | unclear | preserve structurally with `represented`, not `entailed` | ## Complexity / scaling implications - **Ground/kernel queries:** indexed relation/entity lookup should be near database-style lookup cost. - **Horn/Datalog profile:** function-free rules give a finite Herbrand base; evaluation can use tabling/semi-naive materialization. This is the main zero-LLM reasoning workhorse. - **OWL-style profiles:** use only deliberately chosen fragments. OWL 2’s own profile split is proof that taxonomy reasoning needs explicit computational contracts; do not promise full OWL-DL behavior in generic Prolog. - **Unrestricted quantified FOL:** store/preserve, but no generic termination/decidability guarantee. - **Temporal Event Calculus:** append-only events are a good fit, but unrestricted abduction/default reasoning can become expensive; require bounded/query-directed reasoning or materialized current-state views. - **Allen interval algebra:** qualitative interval consistency can be useful, but complete networks can grow quadratically in interval pairs; keep query/projection bounded. - **Provenance:** store derivation edges separately and index by proposition/assertion/source. Do not duplicate the whole proof tree inside each fact. ## Epistemic / provenance implications The most important change is **proposition != assertion**. ```text P abstract proposition A1 asserts P source 1 / time 1 / confidence x A2 claims P source 2 / time 2 A3 explicitly denies P source 3 D1 derives P rule set r / premises ... ``` This structure makes contradiction, corroboration, supersession and model-vs-source provenance downstream operations over assertion objects instead of mutating the proposition itself. PROV-O’s Entity/Activity/Agent model is a good interoperability vocabulary, but the internal provenance model should remain smaller and domain-neutral; map to PROV-O at export boundaries. ## Safety / authority implications - A semantic symbol called `shell`, `restart`, `delete`, or `call` remains a domain symbol. - No open-vocabulary symbol resolves by name to a Prolog predicate. - Profile selection itself is not authority; it only selects a trusted semantic interpreter/lowerer. - `fol_preserve` and unknown extension profiles are inert except for inspection/retrieval/export. - Frame procedural attachments are forbidden as callbacks; procedures remain symbolic until a trusted host separately maps admitted actions to capabilities. - Importing OWL/RDF/RIF data does not import host authority. ## Adversarial review ### Attack: “One universal AST is cleaner” It is cleaner syntactically but dangerously vague operationally. If everything can express everything, callers start assuming the Prolog runtime can reason soundly/terminatingly over everything. Profiles prevent that semantic lie. ### Attack: “Just use RDF 1.2” RDF 1.2 substantially improves statement-level metadata, but triple graphs still do not natively express the full scoped quantified/default/procedural semantics Machine Spirit needs. RDF should be an interchange projection, not the canonical internal model. ### Attack: “Just use OWL” OWL is excellent for ontology/class/property semantics, but procedures, event dynamics, defaults, arbitrary rules and attributed/conflicting claims are outside its core sweet spot. Even OWL itself uses profiles because expressiveness changes computational properties. ### Attack: “Just use Prolog terms directly” That collapses data and execution and makes persistence/versioning/security harder. The repo’s existing authority rules already reject this direction. ### Attack: “Every record gets a unique proposition ID, easy” Bad: semantically identical propositions from multiple sources would never corroborate. Proposition canonicalization needs deterministic structural fingerprints *within a declared vocabulary/schema version*, while assertion IDs remain source/run-specific. Cross-memory identity reconciliation must remain reversible downstream. ### Attack: “Canonicalize everything globally” Also bad: local symbols, time-varying names, hypothetical entities and versioned ontologies make global same-as unsafe. Canonicalization should be syntactic/structural; semantic identity links remain explicit knowledge. ## Rejected alternatives 1. **Pure RDF/triple store as canonical IR** — loses too much rule/quantifier/procedure structure or requires elaborate ad-hoc reification. 2. **Unrestricted Common Logic/FOL as executable core** — expressive but gives the runtime no tractability/termination contract. 3. **Frame system as canonical semantics** — object ergonomics are good, but defaults/procedural attachments create hidden semantics and authority hazards. 4. **One enormous fixed predicate ontology** — incompatible with unfamiliar domains and guarantees core churn. 5. **One monolithic `sem_record(Type, Payload, Meta)` blob** — easy persistence, terrible invariant enforcement and reasoning guarantees. ## Concrete recommendations to canonical issues ### #392 — change required Add these design invariants: 1. explicit **proposition identity separate from assertion identity**; 2. closed ground **formula AST** for variables/quantifiers/composition; 3. versioned **semantic profile/dialect declaration** for reasoning guarantees; 4. native n-ary atoms; RDF/triple is export/interchange, not mandatory internal shape; 5. explicit event/fluent/change vocabulary inspired by Event Calculus; 6. instant + interval temporal vocabulary, with Allen relations as an optional profile; 7. frames as derived/materialized views only; 8. distinguish `represented`, `validated`, `entailed/queryable`, and `safely_lowerable` support levels; 9. structural proposition fingerprinting separated from source-specific assertion IDs; 10. extension profiles must declare signatures + supported semantic operators, not just relation names. ### #394 — later reasoning pass dependency #394 should consume the profile/dialect declaration instead of implementing one global evaluator over every semantic constructor. Default/exception/paraconsistency semantics should be a distinct profile and not silently contaminate strict Horn inference. ### symbolic-memory#4/#6 Persist proposition records and assertion/context/provenance records separately enough that many assertions may reference the same proposition. Current/history views operate over assertions, not by mutating proposition payloads. Materialized frame/current-state views remain rebuildable indexes. ### symbolic-memory#10 Identity reconciliation should not rewrite proposition structural IDs. Entity same-as/likely-same-as/renaming remains explicit reversible semantic knowledge; proposition equivalence can be a separate derived relation. ## Preferred design summary **Machine Spirit should not have one universal logic. It should have one universal symbolic interchange kernel with explicit, composable reasoning profiles.** The canonical substrate is: ```text terms + signatures ↓ first-class propositions / formula AST ↓ assertion + stance + context + provenance ↓ event/state/change objects where applicable ↓ profile declaration ↓ trusted profile-specific reasoners/lowerers ↓ materialized views / export adapters ``` That keeps arbitrary knowledge representable while making computational promises honest. ## Unresolved questions to preserve for later passes - Exact canonicalization rules for formulas with alpha-renamed variables and commutative conjunctions. - Whether proposition identity should include ontology/vocabulary version or carry it only in context; current recommendation is **include semantic vocabulary version in structural fingerprint**. - How multiple reasoning profiles compose without semantic incoherence. - Whether event-calculus fluents are kernel constructs or the first standard extension profile. - Exact relationship between strict negation, default negation and paraconsistent conflict; defer to pass 3/#400. - Query-planning/materialization policy for huge Horn + temporal datasets; defer to passes 5/6. - Whether OWL-RL-compatible import/export deserves a standard profile in v1 or only a mapper. ### Pass conclusion `#398` is **design-complete** from the KR-foundations perspective. It does not prove implementation or Machine Spirit acceptance. The next pass should be #399 semantic compilation and should treat this representation as a target contract to attack, not as unquestionable truth.
Author
Owner

Deepening pass #398B — contextual theories, existential knowledge, justification graphs, and reasoning contracts

This is an additional depth pass on completed Machine Spirit pass #398, not a new numbered pass. It does not consume #399. The first #398 pass established a strong base — proposition/assertion separation, a closed semantic kernel, open vocabularies, and explicit reasoning profiles — but it was still too representation-format centric. This pass asks the harder question:

If Machine Spirit is expected to ingest LLM logs, Wikipedia text, news, manuals, scientific material, issue histories and arbitrary prose into one durable symbolic world model, what additional representation machinery is required so those semantics remain context-correct, existentially correct, incrementally maintainable, provenance-complete, and computationally honest?

Research questions

  1. Is proposition + assertion + profile enough, or do contexts/theories/microtheories need to be first-class objects?
  2. How should the system represent statements such as “some X exists”, anonymous participants, unknown witnesses, and existential rule conclusions without inventing global entities?
  3. How should derivations and explanations be represented so append-only source history can coexist with changing current conclusions?
  4. What should happen when two sources support opposite propositions? Must conflict handling be a later application feature, or does the core IR need enough structure to support paraconsistent query states?
  5. Can one provenance mechanism serve source lineage, rule derivation, explanation, incremental invalidation and later confidence/probability extensions?
  6. Which reasoning fragments can remain fast at millions/billions of records, and which must be bounded/preservation-only?
  7. What are the correct boundaries between canonical semantic data, derived/materialized state and executable Prolog?

Additional primary/authoritative research

Contexts and microtheories

McCarthy's key move is to make context itself a formal object and reason about propositions in a context rather than forcing all assertions into a single flat theory. Guha applied this direction to Cyc-style microtheories. This is directly relevant to Machine Spirit because source, time, scenario, speaker, ontology version and task frame are not cosmetic metadata — they change what a proposition means or whether it may be used.

Truth maintenance / assumptions / multiple contexts

A TMS records reasons for beliefs, not just conclusions. The ATMS goes further by associating conclusions with assumption sets; one important architectural consequence is that multiple mutually inconsistent solution/context sets can coexist rather than forcing destructive retraction/backtracking. Machine Spirit should not copy ATMS wholesale here — pass #400 owns epistemics/non-monotonic reasoning — but #398 must leave room for first-class justifications, assumptions and context-dependent support.

Four-valued/paraconsistent information states

Belnap's motivating problem is almost exactly the corpus-ingestion problem: a question-answering machine receives information from fallible sources and must not explode when both P and not-P are present. The useful information-state distinction is true/support only, false/refutation only, both, and neither. I do not recommend making Belnap-Dunn logic the universal logic of Machine Spirit, but the canonical representation must make this information state computable without loss.

Existential rules / unknown witnesses

Existential rules (forall x: P(x) -> exists y: R(x,y)) are materially important for text-derived knowledge. A source may say “every project has a maintainer” without identifying one, or “an official said...” without identifying the official. Plain Datalog cannot express this faithfully. Datalog±/TGDs use labelled nulls/witnesses and syntactic restrictions such as guardedness/wardedness/acyclicity to regain decidability. Vadalog is important implementation evidence that this is not merely theoretical: Warded Datalog± targets tractable data complexity while allowing recursion and existentially introduced unknowns.

Provenance as algebra / derivation structure

Semiring provenance demonstrates that derivation annotations can be composed algebraically: conjunction and alternative derivations can preserve how an answer depends on source tuples rather than reducing provenance to a string. Algebraic model counting/semiring programming show that similar algebraic abstraction can support probability, soft constraints and other inference tasks. This suggests Machine Spirit should preserve a generic derivation/support graph and leave quantitative interpretation to an explicit profile rather than hard-code one universal confidence arithmetic.

Non-monotonic logic-programming semantics and tabled execution

The representation must not silently identify Prolog negation-as-failure with semantic negation. Well-founded semantics is especially relevant because a tabled logic-programming engine can explicitly represent unknown rather than forcing two-valued answers. SWI's current incremental tabling can maintain dependencies across dynamic predicates by invalidating dependent tables after updates and lazily recomputing them. This is useful implementation evidence for making canonical knowledge immutable while treating derived tables as rebuildable state.

Current standards revisited

Two standards details strengthen this pass:

  1. RDF 1.2 datasets deliberately do not assign a universal semantic meaning to graph names. Therefore named graph = context is not a sufficient canonical context semantics for Machine Spirit.
  2. SHACL is a useful precedent for separating graph/data representation from structural validation. Machine Spirit's semantic signatures/shapes should likewise validate data without becoming the reasoning semantics themselves.

Stress test against real Machine Spirit inputs

The architecture should survive all of these without special-case schema redesign.

A. LLM logs

Source:

User: nix build is failing with a hash mismatch.
Assistant: The lock file may be stale. Update the lock file and rebuild.
Later: That fixed it.

There are several different semantic objects here:

  • user-observed failure event;
  • assistant hypothesis (possible_cause), not fact;
  • assistant proposed procedure;
  • later outcome evidence;
  • a candidate generalized rule induced from one case;
  • speaker roles/session/time;
  • exact source spans.

The generalized rule must not masquerade as something explicitly stated by a trusted manual.

B. Wikipedia / encyclopedia text

Source:

The Moon orbits Earth.

Compiler output should initially mean:

revision R of source S contains/asserts proposition P

not automatically:

P is an eternal unqualified trusted world fact

A separate trusted source-promotion/context bridge policy may make P available in a general astronomy theory while preserving the original assertion/revision provenance.

C. News

Source:

Company A said the outage was caused by a routing error.
Investigators have not independently confirmed the cause.

Must preserve:

A claims P
independent-confirmation(P) = absent/unknown

and must not assert P merely because a sentence contains it.

D. Manual / policy

Source:

If status is FAILED, retry twice. Do not retry authentication failures.

Contains:

  • a conditional procedure/default;
  • bounded iteration/cardinality;
  • explicit exception/prohibition;
  • a document/version context;
  • possibly a host capability description, but no execution authority.

E. Scientific prose

Source:

Every sample in group A expressed marker M. Some samples also expressed N.

The existential some samples must not create a fake globally identified sample. The IR needs a scoped existential witness/variable and quantifier structure.

These examples strongly argue that source context and semantic world context must be distinct first-class objects.


Candidate architecture D — flat global proposition graph + annotations

Extend the first pass's proposition graph and attach every qualifier as annotation.

prop(P, Atom).
ann(P, source, S).
ann(P, time, T).
ann(P, confidence, C).

Good

  • simple storage/indexing;
  • easy graph export;
  • fast for ground lookups.

Fatal weakness

It conflates several fundamentally different things:

metadata about a proposition
metadata about an assertion event
semantic scope of a proposition
which theory contains the assertion
which assumptions were required to derive it

source_claims(P) and P become dangerously easy to mix. It also has no principled home for existential scope or bridge rules between theories.

Reject as canonical architecture. Keep it only as an optimized projection.


Candidate architecture E — context/microtheory-first logic

Make every assertion belong to an explicit theory/context.

Conceptually:

sem_context(ctx_wiki_r42,
            kind(source_revision),
            dimensions([source(wiki), revision(42), world(actual)]),
            parent([])).

sem_context(ctx_general_astronomy,
            kind(domain_theory),
            dimensions([domain(astronomy), world(actual)]),
            parent([])).

sem_assertion(a1, p_orbits,
              context(ctx_wiki_r42),
              stance(asserted_by_source),
              provenance(pr1)).

sem_bridge(b1,
           from(ctx_wiki_r42),
           to(ctx_general_astronomy),
           pattern(P),
           policy(trusted_reference_source),
           status(active)).

Queries are evaluated against an explicit context closure, not an implicit union of the entire store.

Strengths

  • excellent source/hypothetical/time/viewpoint separation;
  • explains exactly why LLM logs/news/manuals need not become world truth;
  • supports local ontologies and different versions simultaneously;
  • context imports/bridges provide controlled reuse;
  • aligns with McCarthy/Guha microtheory reasoning.

Weaknesses

  • naive context cross-products can explode;
  • bridge-rule semantics can become a second rule language;
  • difficult questions arise when a proposition spans several orthogonal dimensions (time, speaker, source, scenario, jurisdiction, ontology version).

Refinement

Do not create one context for every Cartesian combination of dimensions. Use an opaque context/theory ID plus normalized context facets and explicit parent/import/bridge links. Context composition is query-time/reasoner policy, not uncontrolled object multiplication.

Strongly adopt as part of preferred design.


Candidate architecture F — existential-rule / deductive-database core

Make the executable kernel primarily a Datalog±-style theory:

forall([X],
  rule(
    body([project(X)]),
    exists([Y], head([maintainer(Y), maintains(Y,X)])))).

Reasoning creates scoped labelled nulls/witnesses rather than invented real-world IDs.

Strengths

  • directly handles unknown entities/participants;
  • strong database theory around query answering and decidable fragments;
  • natural fit for huge relational corpora;
  • Vadalog demonstrates practical high-performance existential-rule systems;
  • functions as a powerful bridge between ontology/KG and rule reasoning.

Weaknesses

  • still not enough for arbitrary modality, procedure structures, quotations or nonmonotonic semantics;
  • unrestricted existential recursion can generate infinite chase structures and make query answering undecidable;
  • labelled nulls can be mistaken for real entity identity if the storage layer is careless.

Recommendation

Add a guarded/warded existential semantic profile rather than make existential Datalog the universal IR.

Required invariant:

existential witness != globally identified entity

Witness IDs are scoped to a formula/assertion/derivation context and carry constraints/provenance. Identity reconciliation may later conclude that a witness equals a known entity, but that is new append-only knowledge, not mutation of the original existential statement.


Candidate architecture G — justification/support graph as canonical reasoning substrate

Represent not only facts and rules but the proof/support dependency graph:

sem_justification(j42,
                  conclusion(a_derived),
                  rule(r17),
                  premises([a1,a7]),
                  assumptions([h2]),
                  context(ctx1),
                  profile(horn_safe)).

Alternative justifications are separate hyperedges.

Strengths

  • exact explanations;
  • incremental invalidation when premises become inactive;
  • can preserve multiple derivations/corroboration;
  • ATMS-like assumption environments become possible later;
  • provenance semiring annotations can be computed over the same dependency graph;
  • makes VERIFY/Review experts much more capable.

Weaknesses

  • eagerly materializing every proof can be enormous;
  • recursive rules may generate cyclic/infinite derivation structures;
  • provenance polynomials can grow exponentially;
  • storing derivations as canonical source truth would conflate observations with caches.

Recommendation

Make the justification schema canonical, but treat many derived justification instances/materializations as rebuildable/indexed derived state. Preserve durable derivation receipts for material promoted conclusions/actions and externally visible explanations; allow low-value intermediate derivations to remain cacheable.

Strongly adopt as part of preferred design.


Candidate architecture H — universal weighted/algebraic logic

Use a generic logic theory plus an annotation semiring so provenance, probability, cost, confidence and optimization are all instances of one algebra.

Strengths

  • mathematically elegant;
  • provenance semirings and algebraic model counting demonstrate real unification;
  • potentially valuable for future probabilistic/soft reasoning.

Weaknesses

  • different annotations have materially different semantics; multiplying provenance tokens is not the same thing as multiplying independent probabilities;
  • model confidence is not calibrated probability;
  • provenance/trust/authority/cost must not be casually collapsed into one number;
  • forcing every profile into weighted-model semantics would complicate deterministic KR unnecessarily.

Recommendation

Preserve an optional versioned annotation-algebra interface, but do not make a universal semiring mandatory in IR v1. Provenance should have a structured derivation representation first; probabilistic/soft profiles may interpret annotations separately.


Preferred #398B architecture — Contextual Theory Graph + Formula Algebra + Justification Hypergraph

The first pass's layered-profile architecture survives, but needs two new first-class layers and one major quantifier refinement.

immutable source / source spans
          ↓
versioned vocabulary + signatures
          ↓
term + formula algebra
          ↓
first-class proposition identity
          ↓
ASSERTION TOKEN
  polarity / stance / temporal validity
  source / explicit-vs-inferred status
          ↓
CONTEXT / THEORY
  source revision
  domain microtheory
  scenario / viewpoint / ontology version
  imports + explicit bridge rules
          ↓
JUSTIFICATION HYPERGRAPH
  premises + assumptions + rule + profile
  derivation/provenance dependencies
          ↓
DECLARED REASONING PROFILES
  ground / horn / existential / DL / event /
  constraint / procedural / defeasible / etc.
          ↓
profile-specific trusted reasoners
          ↓
materialized current views / indexes / exports

Proposed normalized kernel direction

Conceptual only; exact names remain a design/implementation decision.

% Vocabulary
sem_symbol(SymbolId, Namespace, LocalName, Kind, SignatureRef, VersionRef).
sem_signature(SignatureId, ArgRolesAndTypes, ResultType, Constraints).

% Terms and formulae
sem_term(TermId, TermKind, Payload).
sem_formula(FormulaId, Constructor, ArgRefs, BinderInfo).
sem_proposition(PropId, FormulaId, StructuralFingerprint, VocabularyVersion).

% Context/theory
sem_context(ContextId, Kind, Facets, ParentRefs, VocabularyVersion, Meta).
sem_theory(TheoryId, ContextId, ProfileRefs, ImportRefs, Meta).
sem_bridge(BridgeId, FromTheory, ToTheory, PatternRef, ConditionsRef,
           SemanticsProfile, Status, Provenance).

% Assertion episode
sem_assertion(AssertionId,
              PropositionId,
              ContextId,
              Polarity,
              Stance,
              ValidityRef,
              ProvenanceRef,
              DerivationClass).

% Existential witness
sem_witness(WitnessId,
            ScopeFormulaOrAssertion,
            TypeConstraintRefs,
            OriginRef,
            IdentityStatus).

% Derivation / explanation
sem_justification(JustificationId,
                  ConclusionAssertion,
                  RuleRef,
                  PremiseAssertionRefs,
                  AssumptionRefs,
                  ContextId,
                  ProfileRef,
                  ProvenanceRef).

% Annotation is deliberately not truth
sem_annotation(TargetRef, AnnotationType, Value, SemanticsRef, ProvenanceRef).

Why a first-class theory in addition to context?

A context says where/from whose viewpoint/under which assumptions a semantic statement lives. A theory says which assertions/rules/vocabulary/profile set are considered together for inference.

Often one maps closely to the other, but they are not identical. Example:

source context: Wikipedia revision R
         ↓ trusted bridge
astronomy theory: selected assertions from many sources
         + ontology
         + Horn rules
         + temporal profile

This separation prevents a source document from becoming an executable global theory merely because it was parsed successfully.

Bridge rules are security-sensitive semantic infrastructure

Context/theory lifting must be explicit:

source says P
       !=
world theory asserts P

A bridge can express policies such as:

promote stable identifiers/definitions from source class X
retain attributed claims without promotion
promote only corroborated observations
map ontology-v1 concept to ontology-v2 concept under explicit alignment

Bridge rules themselves are trusted configuration / validated symbolic policy, not arbitrary model-generated active code. A model may propose a bridge candidate; activation requires the appropriate trusted boundary.

This is semantic trust management, not host execution authority.


Query semantics: evidence state should be computable without flattening

The core ledger need not adopt one universal paraconsistent logic, but a default query result should be able to distinguish support and refutation independently:

support(P)=no,  refute(P)=no   -> NEITHER / UNKNOWN
support(P)=yes, refute(P)=no   -> SUPPORTED
support(P)=no,  refute(P)=yes  -> REFUTED
support(P)=yes, refute(P)=yes  -> BOTH / CONFLICTED

This is Belnap-inspired information status, not necessarily the final consequence relation for every profile.

Why this belongs in the representation pass: if positive and negative source assertions have already been collapsed or one overwrote the other, pass #400 cannot recover the information later.

The query result should additionally retain:

profile used
context/theory closure
supporting assertion refs
refuting assertion refs
assumptions/defaults
validity/time
unresolved existential witnesses
justification refs

Existential semantics — important addition to #392

The current #392 mentions existential quantification but does not yet say enough about witness identity.

Required invariants:

  1. A text-derived existential does not automatically allocate a real globally named entity.
  2. Witnesses/labeled nulls are scoped and typed.
  3. Two existential witnesses from separate assertions are not assumed equal merely because their descriptions match.
  4. Equality/identity with a known entity is a separate derived/asserted record with provenance.
  5. Existential-rule execution must occur only under a decidable/bounded profile (e.g. warded/guarded/acyclic restrictions), or remain preservation-only.
  6. A reasoning-generated witness never gains host capability/authority.

Example:

Every project has a maintainer.
Project P exists.

may justify:

exists M: maintainer(M) and maintains(M,P)

but not:

maintainer(alice)

without additional identity evidence.

This matters constantly in news, reports and scientific prose.


Provenance design — separate five notions that are easy to conflate

Machine Spirit needs at least:

  1. source provenance — which immutable source/span stated something;
  2. interpretation provenance — which compiler/model/version produced the semantic interpretation;
  3. derivation provenance — which rules/premises produced a derived conclusion;
  4. lifecycle provenance — which append events superseded/retracted/corroborated records;
  5. execution evidence — which tools/tests/actions proved an operational result.

All five can point into a shared graph, but they must remain distinguishable.

For derivation provenance, use a hash-consed DAG/hypergraph representation rather than duplicating proof trees into every assertion. Provenance-semiring style annotations can be computed over that graph for supported profiles.

Avoid eagerly expanding polynomial provenance expressions for highly recursive derivations. Keep canonical dependency nodes and compute bounded human explanations on demand.


Materialization / truth maintenance architecture

Canonical durable knowledge should remain append-only; derived current truth should not.

Recommended separation:

APPEND-ONLY CANONICAL
  source objects
  semantic assertions
  rules/procedures/theories
  bridge decisions
  supersession/retraction/conflict events
  durable promoted derivation receipts when needed

REBUILDABLE DERIVED STATE
  current-active assertion indexes
  transitive closures
  materialized Horn consequences
  holds_at/current state
  query caches
  ranking/relevance indexes
  ordinary intermediate proof nodes

When canonical inputs change, dependency metadata invalidates affected derived tables/materializations. SWI incremental tabling provides one available implementation primitive today, although its documented strategy may invalidate and lazily recompute entire dependent tables rather than perform perfect delta maintenance. Therefore the public architecture should not depend on one Prolog engine's exact cache behavior.

This reconciles append-only history with efficient mutable runtime state.


Reasoning-profile refinement

The first pass introduced profiles. This pass suggests a more precise profile capability contract.

A profile should declare:

accepted semantic constructors
variable/quantifier restrictions
negation semantics
identity assumptions
world/context assumptions
termination/decidability class if known
supported query classes
incremental/materialization strategy
trusted lowerer/reasoner implementation
explanation capability
profile compatibility/import rules

Support status should be more explicit than represented/queryable/lowerable:

represented
schema_validated
profile_admitted
query_supported(QueryClass)
decidable_for(PackageClass,QueryClass)   % where known
lowerable(Target)
materializable
incremental_capability(add|retract|both|none)
explainable(Level)

A package should never imply stronger guarantees than its declared profile proves.

Suggested standard profile family after #398B

kernel_ground
horn_safe
datalog_wfs                % semantics finalized by #400
existential_warded          % guarded/warded existential rules
dl_rl_like
fol_preserve
contextual_theory
temporal_event
temporal_interval
constraint_fd
constraint_qr
procedural
defeasible                  % semantics finalized by #400
probabilistic_annotation    % preservation unless explicit probabilistic reasoner

contextual_theory may ultimately be a kernel capability rather than a separate profile; implementation research should decide after #400/#402.


Performance / scale implications

1. Do not query one universal union graph

At millions/billions of records, every task should compile to:

goal
 -> context/theory selection
 -> relevant vocabulary/profile selection
 -> indexed assertion/rule slice
 -> profile reasoner

This naturally aligns with #381 retrieval/projection.

2. Ground + Horn remains the hot path

Function-free Horn/Datalog should be the principal zero-LLM reasoning workhorse. Semi-naive evaluation, tabling and specialized relational representations are mature. Soufflé demonstrates that Datalog can handle large real-world analyses with compiled/specialized execution, and XSB/SWI provide tabled logic-programming paths.

3. Existential reasoning must be opt-in

General Datalog with existential heads is undecidable. Use warded/guarded/acyclic fragments and bounded chase/query-directed methods. Vadalog is strong evidence for Warded Datalog± as a serious candidate profile, not necessarily a dependency.

4. Context closure must be bounded

Recursive imports/bridges need cycle detection, memoization and explicit selection. Do not automatically union all ancestor microtheories.

5. Provenance can dominate storage

A conclusion can have combinatorially many derivations. Persist compact shared dependency structure and bounded material explanations; do not persist a complete expanded proof tree for every answer.

The semantic IR is an interchange/control plane. A query may dispatch to:

SWI/XSB tabling
compiled Datalog engine
CLP(FD/Q/R)
OWL/DL reasoner
existential-rule reasoner
future probabilistic reasoner

provided the profile mapping is trusted and semantics-preserving for the admitted subset. Prolog-RLM owns the semantic contract, not necessarily every low-level solver algorithm.


Adversarial review

Attack 1: contexts become an ontology-management nightmare

Correct risk. A system that creates a unique full context for every source × time × speaker × scenario × ontology version will explode.

Countermeasure: contexts have stable opaque identity plus facets; theory membership/imports/bridges are sparse explicit relations. Query context composition is computed, not eagerly cross-product materialized.

Attack 2: bridge rules are just hidden trust heuristics

They can be. Therefore bridge provenance/status must be explicit and inspectable, and compiler/model proposals cannot auto-activate trusted bridges.

Attack 3: proposition canonicalization breaks intensional meaning

Two syntactically similar formulas can differ by context, vocabulary version, quantifier binding or concept identity.

Countermeasure: proposition structural fingerprints are scoped to canonicalized formula + exact vocabulary/signature version. Assertion/context identity remains separate. Cross-vocabulary equivalence is explicit knowledge, never fingerprint magic.

Attack 4: existential witnesses pollute entity reconciliation

Very real. A labelled null is not an entity assertion.

Countermeasure: use a distinct witness semantic kind with scope/origin; reconciliation may link it later but cannot silently rewrite it into a global entity.

Attack 5: justification graph becomes larger than the KB

Likely for recursive rules.

Countermeasure: shared DAG/hyperedges, derivation-class retention policy, on-demand explanation, and derived-cache eviction. Durable source assertions remain enough to replay/rederive.

Attack 6: four-valued status conflicts with stable/well-founded/default semantics

It can if treated as the universal logic.

Countermeasure: use support/refutation pair as a query information summary over assertion evidence, while each reasoning profile defines its own consequence semantics. Pass #400 decides default/nonmonotonic semantics.

Attack 7: too many reasoning profiles fragment the system

Also real.

Countermeasure: profiles form a small versioned registry with explicit capability/compatibility declarations. Prefer a handful of standardized profiles; unknown domain vocabulary should not require a new profile. Profiles vary semantics, vocabularies vary domain concepts.

Attack 8: arbitrary web/LLM text can create rules that later execute

Still forbidden.

compiled procedure/rule
    != trusted runtime predicate
    != authority to perform action

A model can generate candidate semantic data. Validation can admit it as knowledge. Only separately trusted expert/tool/capability mapping can cause host effects.


Concrete canonical changes recommended

Update #392 semantic IR

Add explicit requirements for:

  1. first-class context and theory identities;
  2. sparse context facets + imports/bridge relations;
  3. source assertion context distinct from promoted/world theory membership;
  4. first-class scoped existential witnesses/labeled unknowns;
  5. explicit justification/derivation hypergraph schema;
  6. support/refutation-preserving assertion polarity sufficient to compute neither/supported/refuted/both information states;
  7. profile capability contracts including query class, decidability where known, lowerer and incremental/materialization behavior;
  8. versioned signature/vocabulary identity in proposition fingerprints;
  9. canonical vs rebuildable-derived-state separation;
  10. validation-shape/schema layer separate from inference semantics;
  11. optional annotation algebra interface without treating confidence/probability/trust/provenance as one number.

Downstream symbolic-memory #4/#6

Storage must preserve context/theory/witness/justification records and must not flatten them into generic triples. Current views should be theory/context aware and derived materializations must be explicitly rebuildable.

Pass #400 boundary

Do not prematurely settle:

  • stable vs well-founded semantics;
  • belief revision policy;
  • default specificity/priorities;
  • ATMS environment management;
  • paraconsistent consequence relation;
  • probabilistic confidence calculus.

#398B only ensures the representation does not destroy the information those later semantics need.


Revised north-star representation test

Compile a corpus containing all of:

  1. a Wikipedia revision making a declarative assertion;
  2. a news report quoting two conflicting sources;
  3. an LLM troubleshooting conversation that produces a successful repair outcome;
  4. a manual containing a conditional procedure and exception;
  5. scientific prose containing a universal and an existential claim;
  6. two ontology versions using different but alignable terms;
  7. a hypothetical scenario that contradicts current-world data.

With the original prose removed from reasoning context, the IR/world-model must be able to answer:

What is asserted in the general world theory?
What did each source separately claim?
Which conclusions are conflicted?
Which facts are only hypothetical?
Which anonymous/existential entities remain unresolved?
What rule/procedure applies to the failure?
Why does the system believe that procedure applies?
Which derivations depend on the old ontology mapping?
What would become invalid if source assertion A were retracted/superseded?

Every answer must return theory/context, profile, supporting/refuting assertion IDs and exact source/derivation provenance.

#398B conclusion

The original preferred design remains valid but is incomplete. Machine Spirit should be designed as a contextual theory system, not a flat knowledge graph.

The refined core is:

semantic formula/proposition
       +
assertion episode
       +
context / theory
       +
scoped existential witnesses
       +
justification dependencies
       +
declared reasoning profile

That combination is substantially better suited to the user's actual intended ingestion domain — arbitrary LLM logs, web/news/encyclopedia text, manuals and research — because it distinguishes meaning, who/what said it, under what assumptions/world/time it applies, what is still unknown, and why a derived conclusion follows.

The next numbered pass remains #399 semantic compilation from language. It should now target this richer context/theory/witness/justification IR and actively test whether language compilation can populate it without losing attribution, quantification, discourse scope or procedural semantics.

## Deepening pass #398B — contextual theories, existential knowledge, justification graphs, and reasoning contracts This is an **additional depth pass on completed Machine Spirit pass #398**, not a new numbered pass. It does **not** consume #399. The first #398 pass established a strong base — proposition/assertion separation, a closed semantic kernel, open vocabularies, and explicit reasoning profiles — but it was still too representation-format centric. This pass asks the harder question: > If Machine Spirit is expected to ingest LLM logs, Wikipedia text, news, manuals, scientific material, issue histories and arbitrary prose into one durable symbolic world model, what additional representation machinery is required so those semantics remain *context-correct, existentially correct, incrementally maintainable, provenance-complete, and computationally honest*? ### Research questions 1. Is `proposition + assertion + profile` enough, or do **contexts/theories/microtheories** need to be first-class objects? 2. How should the system represent statements such as “some X exists”, anonymous participants, unknown witnesses, and existential rule conclusions without inventing global entities? 3. How should derivations and explanations be represented so append-only source history can coexist with changing current conclusions? 4. What should happen when two sources support opposite propositions? Must conflict handling be a later application feature, or does the core IR need enough structure to support paraconsistent query states? 5. Can one provenance mechanism serve source lineage, rule derivation, explanation, incremental invalidation and later confidence/probability extensions? 6. Which reasoning fragments can remain fast at millions/billions of records, and which must be bounded/preservation-only? 7. What are the correct boundaries between canonical semantic data, derived/materialized state and executable Prolog? ## Additional primary/authoritative research ### Contexts and microtheories - John McCarthy, **Notes on Formalizing Context** / expanded notes, IJCAI 1993: https://jmc.stanford.edu/articles/context.html and https://jmc.stanford.edu/articles/formalizing-context/formalizing-context.pdf - R. V. Guha, **Contexts: A Formalization and Some Applications**, Stanford PhD thesis, 1991: https://dl.acm.org/doi/10.5555/142856 McCarthy's key move is to make context itself a formal object and reason about propositions *in* a context rather than forcing all assertions into a single flat theory. Guha applied this direction to Cyc-style microtheories. This is directly relevant to Machine Spirit because source, time, scenario, speaker, ontology version and task frame are not cosmetic metadata — they change what a proposition means or whether it may be used. ### Truth maintenance / assumptions / multiple contexts - Jon Doyle, **A Truth Maintenance System**, Artificial Intelligence 12(3), 1979: https://www.sciencedirect.com/science/article/pii/0004370279900080 - Johan de Kleer, **An assumption-based TMS**, Artificial Intelligence 28(2), 1986: https://www.sciencedirect.com/science/article/pii/0004370286900809 - Johan de Kleer, **Problem solving with the ATMS**, 1986: https://www.sciencedirect.com/science/article/pii/0004370286900822 A TMS records *reasons for beliefs*, not just conclusions. The ATMS goes further by associating conclusions with assumption sets; one important architectural consequence is that multiple mutually inconsistent solution/context sets can coexist rather than forcing destructive retraction/backtracking. Machine Spirit should not copy ATMS wholesale here — pass #400 owns epistemics/non-monotonic reasoning — but #398 must leave room for first-class justifications, assumptions and context-dependent support. ### Four-valued/paraconsistent information states - Nuel D. Belnap Jr., **A Useful Four-Valued Logic**, 1977: https://link.springer.com/chapter/10.1007/978-94-010-1161-7_2 Belnap's motivating problem is almost exactly the corpus-ingestion problem: a question-answering machine receives information from fallible sources and must not explode when both P and not-P are present. The useful information-state distinction is `true/support only`, `false/refutation only`, `both`, and `neither`. I do **not** recommend making Belnap-Dunn logic the universal logic of Machine Spirit, but the canonical representation must make this information state computable without loss. ### Existential rules / unknown witnesses - Andrea Calì, Georg Gottlob, Michael Kifer, **Taming the Infinite Chase: Query Answering under Expressive Relational Constraints**, JAIR 48 (2013): https://jair.org/index.php/jair/article/view/10837 - Gottlob, Manna, Pieris, **Combining decidability paradigms for existential rules**, TPLP 2013: https://www.cambridge.org/core/journals/theory-and-practice-of-logic-programming/article/abs/combining-decidability-paradigms-for-existential-rules/CD65908DA9B9D9AB3201E78007FD7499 - Bellomarini, Gottlob, Sallinger et al., **Vadalog: A modern architecture for automated reasoning with large knowledge graphs**: https://www.sciencedirect.com/science/article/pii/S0306437920300351 - Vadalog language handbook: https://vadalog.org/vadalog-handbook/latest/vadalog-language.html Existential rules (`forall x: P(x) -> exists y: R(x,y)`) are materially important for text-derived knowledge. A source may say “every project has a maintainer” without identifying one, or “an official said...” without identifying the official. Plain Datalog cannot express this faithfully. Datalog±/TGDs use labelled nulls/witnesses and syntactic restrictions such as guardedness/wardedness/acyclicity to regain decidability. Vadalog is important implementation evidence that this is not merely theoretical: Warded Datalog± targets tractable data complexity while allowing recursion and existentially introduced unknowns. ### Provenance as algebra / derivation structure - Green, Karvounarakis, Tannen, **Provenance Semirings**, PODS 2007: https://www.cs.ucdavis.edu/~green/papers/pods07.pdf - Kimmig, Van den Broeck, De Raedt, **Algebraic Model Counting**, Journal of Applied Logic 2017: https://doi.org/10.1016/j.jal.2016.11.031 - Belle & De Raedt, **Semiring programming**, IJAR 2020: https://doi.org/10.1016/j.ijar.2020.08.001 Semiring provenance demonstrates that derivation annotations can be composed algebraically: conjunction and alternative derivations can preserve *how* an answer depends on source tuples rather than reducing provenance to a string. Algebraic model counting/semiring programming show that similar algebraic abstraction can support probability, soft constraints and other inference tasks. This suggests Machine Spirit should preserve a generic derivation/support graph and leave quantitative interpretation to an explicit profile rather than hard-code one universal confidence arithmetic. ### Non-monotonic logic-programming semantics and tabled execution - Gelfond & Lifschitz, **The Stable Model Semantics for Logic Programming**, 1988: https://dblp.org/rec/conf/iclp/GelfondL88.html - Van Gelder, Ross, Schlipf, **The Well-Founded Semantics for General Logic Programs**, JACM 1991: https://dl.acm.org/doi/10.1145/116825.116838 - XSB tabling tutorial: https://xsb.sourceforge.net/shadow_site/manual1/node46.html - SWI-Prolog incremental tabling: https://www.swi-prolog.org/pldoc/man?section=tabling-incremental - SWI-Prolog monotonic tabling: https://www.swi-prolog.org/pldoc/man?section=tabling-monotonic The representation must not silently identify Prolog negation-as-failure with semantic negation. Well-founded semantics is especially relevant because a tabled logic-programming engine can explicitly represent unknown rather than forcing two-valued answers. SWI's current incremental tabling can maintain dependencies across dynamic predicates by invalidating dependent tables after updates and lazily recomputing them. This is useful implementation evidence for making canonical knowledge immutable while treating derived tables as rebuildable state. ### Current standards revisited - ISO/IEC 24707:2018 Common Logic: https://www.iso.org/standard/66249.html - W3C RIF BLD / Overview: https://www.w3.org/TR/rif-bld/ and https://www.w3.org/TR/rif-overview/ - W3C OWL 2 Profiles: https://www.w3.org/TR/owl2-profiles/ - W3C RDF 1.2 Semantics: https://www.w3.org/TR/rdf12-semantics/ - W3C RDF 1.2 Schema triple-term reification: https://www.w3.org/TR/2026/WD-rdf12-schema-20260320/ - W3C SHACL 1.2 Core WD (3 Aug 2026): https://www.w3.org/TR/shacl12-core/ Two standards details strengthen this pass: 1. RDF 1.2 datasets deliberately **do not assign a universal semantic meaning to graph names**. Therefore `named graph = context` is not a sufficient canonical context semantics for Machine Spirit. 2. SHACL is a useful precedent for separating graph/data representation from structural validation. Machine Spirit's semantic signatures/shapes should likewise validate data without becoming the reasoning semantics themselves. --- # Stress test against real Machine Spirit inputs The architecture should survive all of these without special-case schema redesign. ## A. LLM logs Source: ```text User: nix build is failing with a hash mismatch. Assistant: The lock file may be stale. Update the lock file and rebuild. Later: That fixed it. ``` There are several different semantic objects here: - user-observed failure event; - assistant hypothesis (`possible_cause`), **not fact**; - assistant proposed procedure; - later outcome evidence; - a candidate generalized rule induced from one case; - speaker roles/session/time; - exact source spans. The generalized rule must not masquerade as something explicitly stated by a trusted manual. ## B. Wikipedia / encyclopedia text Source: ```text The Moon orbits Earth. ``` Compiler output should initially mean: ```text revision R of source S contains/asserts proposition P ``` not automatically: ```text P is an eternal unqualified trusted world fact ``` A separate trusted source-promotion/context bridge policy may make P available in a general astronomy theory while preserving the original assertion/revision provenance. ## C. News Source: ```text Company A said the outage was caused by a routing error. Investigators have not independently confirmed the cause. ``` Must preserve: ```text A claims P independent-confirmation(P) = absent/unknown ``` and must **not** assert `P` merely because a sentence contains it. ## D. Manual / policy Source: ```text If status is FAILED, retry twice. Do not retry authentication failures. ``` Contains: - a conditional procedure/default; - bounded iteration/cardinality; - explicit exception/prohibition; - a document/version context; - possibly a host capability *description*, but no execution authority. ## E. Scientific prose Source: ```text Every sample in group A expressed marker M. Some samples also expressed N. ``` The existential `some samples` must not create a fake globally identified sample. The IR needs a scoped existential witness/variable and quantifier structure. These examples strongly argue that **source context and semantic world context must be distinct first-class objects**. --- # Candidate architecture D — flat global proposition graph + annotations Extend the first pass's proposition graph and attach every qualifier as annotation. ```prolog prop(P, Atom). ann(P, source, S). ann(P, time, T). ann(P, confidence, C). ``` ### Good - simple storage/indexing; - easy graph export; - fast for ground lookups. ### Fatal weakness It conflates several fundamentally different things: ```text metadata about a proposition metadata about an assertion event semantic scope of a proposition which theory contains the assertion which assumptions were required to derive it ``` `source_claims(P)` and `P` become dangerously easy to mix. It also has no principled home for existential scope or bridge rules between theories. **Reject as canonical architecture.** Keep it only as an optimized projection. --- # Candidate architecture E — context/microtheory-first logic Make every assertion belong to an explicit theory/context. Conceptually: ```prolog sem_context(ctx_wiki_r42, kind(source_revision), dimensions([source(wiki), revision(42), world(actual)]), parent([])). sem_context(ctx_general_astronomy, kind(domain_theory), dimensions([domain(astronomy), world(actual)]), parent([])). sem_assertion(a1, p_orbits, context(ctx_wiki_r42), stance(asserted_by_source), provenance(pr1)). sem_bridge(b1, from(ctx_wiki_r42), to(ctx_general_astronomy), pattern(P), policy(trusted_reference_source), status(active)). ``` Queries are evaluated against an explicit context closure, not an implicit union of the entire store. ### Strengths - excellent source/hypothetical/time/viewpoint separation; - explains exactly why LLM logs/news/manuals need not become world truth; - supports local ontologies and different versions simultaneously; - context imports/bridges provide controlled reuse; - aligns with McCarthy/Guha microtheory reasoning. ### Weaknesses - naive context cross-products can explode; - bridge-rule semantics can become a second rule language; - difficult questions arise when a proposition spans several orthogonal dimensions (time, speaker, source, scenario, jurisdiction, ontology version). ### Refinement Do **not** create one context for every Cartesian combination of dimensions. Use an opaque context/theory ID plus normalized context facets and explicit parent/import/bridge links. Context composition is query-time/reasoner policy, not uncontrolled object multiplication. **Strongly adopt as part of preferred design.** --- # Candidate architecture F — existential-rule / deductive-database core Make the executable kernel primarily a Datalog±-style theory: ```prolog forall([X], rule( body([project(X)]), exists([Y], head([maintainer(Y), maintains(Y,X)])))). ``` Reasoning creates scoped labelled nulls/witnesses rather than invented real-world IDs. ### Strengths - directly handles unknown entities/participants; - strong database theory around query answering and decidable fragments; - natural fit for huge relational corpora; - Vadalog demonstrates practical high-performance existential-rule systems; - functions as a powerful bridge between ontology/KG and rule reasoning. ### Weaknesses - still not enough for arbitrary modality, procedure structures, quotations or nonmonotonic semantics; - unrestricted existential recursion can generate infinite chase structures and make query answering undecidable; - labelled nulls can be mistaken for real entity identity if the storage layer is careless. ### Recommendation Add a **guarded/warded existential semantic profile** rather than make existential Datalog the universal IR. Required invariant: ```text existential witness != globally identified entity ``` Witness IDs are scoped to a formula/assertion/derivation context and carry constraints/provenance. Identity reconciliation may later conclude that a witness equals a known entity, but that is new append-only knowledge, not mutation of the original existential statement. --- # Candidate architecture G — justification/support graph as canonical reasoning substrate Represent not only facts and rules but the proof/support dependency graph: ```prolog sem_justification(j42, conclusion(a_derived), rule(r17), premises([a1,a7]), assumptions([h2]), context(ctx1), profile(horn_safe)). ``` Alternative justifications are separate hyperedges. ### Strengths - exact explanations; - incremental invalidation when premises become inactive; - can preserve multiple derivations/corroboration; - ATMS-like assumption environments become possible later; - provenance semiring annotations can be computed over the same dependency graph; - makes VERIFY/Review experts much more capable. ### Weaknesses - eagerly materializing every proof can be enormous; - recursive rules may generate cyclic/infinite derivation structures; - provenance polynomials can grow exponentially; - storing derivations as canonical source truth would conflate observations with caches. ### Recommendation Make the **justification schema canonical**, but treat many derived justification instances/materializations as rebuildable/indexed derived state. Preserve durable derivation receipts for material promoted conclusions/actions and externally visible explanations; allow low-value intermediate derivations to remain cacheable. **Strongly adopt as part of preferred design.** --- # Candidate architecture H — universal weighted/algebraic logic Use a generic logic theory plus an annotation semiring so provenance, probability, cost, confidence and optimization are all instances of one algebra. ### Strengths - mathematically elegant; - provenance semirings and algebraic model counting demonstrate real unification; - potentially valuable for future probabilistic/soft reasoning. ### Weaknesses - different annotations have materially different semantics; multiplying provenance tokens is not the same thing as multiplying independent probabilities; - model confidence is not calibrated probability; - provenance/trust/authority/cost must not be casually collapsed into one number; - forcing every profile into weighted-model semantics would complicate deterministic KR unnecessarily. ### Recommendation Preserve an **optional versioned annotation-algebra interface**, but do not make a universal semiring mandatory in IR v1. Provenance should have a structured derivation representation first; probabilistic/soft profiles may interpret annotations separately. --- # Preferred #398B architecture — Contextual Theory Graph + Formula Algebra + Justification Hypergraph The first pass's layered-profile architecture survives, but needs two new first-class layers and one major quantifier refinement. ```text immutable source / source spans ↓ versioned vocabulary + signatures ↓ term + formula algebra ↓ first-class proposition identity ↓ ASSERTION TOKEN polarity / stance / temporal validity source / explicit-vs-inferred status ↓ CONTEXT / THEORY source revision domain microtheory scenario / viewpoint / ontology version imports + explicit bridge rules ↓ JUSTIFICATION HYPERGRAPH premises + assumptions + rule + profile derivation/provenance dependencies ↓ DECLARED REASONING PROFILES ground / horn / existential / DL / event / constraint / procedural / defeasible / etc. ↓ profile-specific trusted reasoners ↓ materialized current views / indexes / exports ``` ## Proposed normalized kernel direction Conceptual only; exact names remain a design/implementation decision. ```prolog % Vocabulary sem_symbol(SymbolId, Namespace, LocalName, Kind, SignatureRef, VersionRef). sem_signature(SignatureId, ArgRolesAndTypes, ResultType, Constraints). % Terms and formulae sem_term(TermId, TermKind, Payload). sem_formula(FormulaId, Constructor, ArgRefs, BinderInfo). sem_proposition(PropId, FormulaId, StructuralFingerprint, VocabularyVersion). % Context/theory sem_context(ContextId, Kind, Facets, ParentRefs, VocabularyVersion, Meta). sem_theory(TheoryId, ContextId, ProfileRefs, ImportRefs, Meta). sem_bridge(BridgeId, FromTheory, ToTheory, PatternRef, ConditionsRef, SemanticsProfile, Status, Provenance). % Assertion episode sem_assertion(AssertionId, PropositionId, ContextId, Polarity, Stance, ValidityRef, ProvenanceRef, DerivationClass). % Existential witness sem_witness(WitnessId, ScopeFormulaOrAssertion, TypeConstraintRefs, OriginRef, IdentityStatus). % Derivation / explanation sem_justification(JustificationId, ConclusionAssertion, RuleRef, PremiseAssertionRefs, AssumptionRefs, ContextId, ProfileRef, ProvenanceRef). % Annotation is deliberately not truth sem_annotation(TargetRef, AnnotationType, Value, SemanticsRef, ProvenanceRef). ``` ## Why a first-class `theory` in addition to `context`? A context says **where/from whose viewpoint/under which assumptions** a semantic statement lives. A theory says **which assertions/rules/vocabulary/profile set are considered together for inference**. Often one maps closely to the other, but they are not identical. Example: ```text source context: Wikipedia revision R ↓ trusted bridge astronomy theory: selected assertions from many sources + ontology + Horn rules + temporal profile ``` This separation prevents a source document from becoming an executable global theory merely because it was parsed successfully. ## Bridge rules are security-sensitive semantic infrastructure Context/theory lifting must be explicit: ```text source says P != world theory asserts P ``` A bridge can express policies such as: ```text promote stable identifiers/definitions from source class X retain attributed claims without promotion promote only corroborated observations map ontology-v1 concept to ontology-v2 concept under explicit alignment ``` Bridge rules themselves are **trusted configuration / validated symbolic policy**, not arbitrary model-generated active code. A model may propose a bridge candidate; activation requires the appropriate trusted boundary. This is semantic trust management, **not host execution authority**. --- # Query semantics: evidence state should be computable without flattening The core ledger need not adopt one universal paraconsistent logic, but a default query result should be able to distinguish support and refutation independently: ```text support(P)=no, refute(P)=no -> NEITHER / UNKNOWN support(P)=yes, refute(P)=no -> SUPPORTED support(P)=no, refute(P)=yes -> REFUTED support(P)=yes, refute(P)=yes -> BOTH / CONFLICTED ``` This is Belnap-inspired **information status**, not necessarily the final consequence relation for every profile. Why this belongs in the representation pass: if positive and negative source assertions have already been collapsed or one overwrote the other, pass #400 cannot recover the information later. The query result should additionally retain: ```text profile used context/theory closure supporting assertion refs refuting assertion refs assumptions/defaults validity/time unresolved existential witnesses justification refs ``` --- # Existential semantics — important addition to #392 The current #392 mentions existential quantification but does not yet say enough about **witness identity**. Required invariants: 1. A text-derived existential does not automatically allocate a real globally named entity. 2. Witnesses/labeled nulls are scoped and typed. 3. Two existential witnesses from separate assertions are not assumed equal merely because their descriptions match. 4. Equality/identity with a known entity is a separate derived/asserted record with provenance. 5. Existential-rule execution must occur only under a decidable/bounded profile (e.g. warded/guarded/acyclic restrictions), or remain preservation-only. 6. A reasoning-generated witness never gains host capability/authority. Example: ```text Every project has a maintainer. Project P exists. ``` may justify: ```text exists M: maintainer(M) and maintains(M,P) ``` but **not**: ```text maintainer(alice) ``` without additional identity evidence. This matters constantly in news, reports and scientific prose. --- # Provenance design — separate five notions that are easy to conflate Machine Spirit needs at least: 1. **source provenance** — which immutable source/span stated something; 2. **interpretation provenance** — which compiler/model/version produced the semantic interpretation; 3. **derivation provenance** — which rules/premises produced a derived conclusion; 4. **lifecycle provenance** — which append events superseded/retracted/corroborated records; 5. **execution evidence** — which tools/tests/actions proved an operational result. All five can point into a shared graph, but they must remain distinguishable. For derivation provenance, use a hash-consed DAG/hypergraph representation rather than duplicating proof trees into every assertion. Provenance-semiring style annotations can be computed over that graph for supported profiles. Avoid eagerly expanding polynomial provenance expressions for highly recursive derivations. Keep canonical dependency nodes and compute bounded human explanations on demand. --- # Materialization / truth maintenance architecture Canonical durable knowledge should remain append-only; derived current truth should **not**. Recommended separation: ```text APPEND-ONLY CANONICAL source objects semantic assertions rules/procedures/theories bridge decisions supersession/retraction/conflict events durable promoted derivation receipts when needed REBUILDABLE DERIVED STATE current-active assertion indexes transitive closures materialized Horn consequences holds_at/current state query caches ranking/relevance indexes ordinary intermediate proof nodes ``` When canonical inputs change, dependency metadata invalidates affected derived tables/materializations. SWI incremental tabling provides one available implementation primitive today, although its documented strategy may invalidate and lazily recompute entire dependent tables rather than perform perfect delta maintenance. Therefore the public architecture should not depend on one Prolog engine's exact cache behavior. This reconciles append-only history with efficient mutable runtime state. --- # Reasoning-profile refinement The first pass introduced profiles. This pass suggests a more precise **profile capability contract**. A profile should declare: ```text accepted semantic constructors variable/quantifier restrictions negation semantics identity assumptions world/context assumptions termination/decidability class if known supported query classes incremental/materialization strategy trusted lowerer/reasoner implementation explanation capability profile compatibility/import rules ``` Support status should be more explicit than `represented/queryable/lowerable`: ```text represented schema_validated profile_admitted query_supported(QueryClass) decidable_for(PackageClass,QueryClass) % where known lowerable(Target) materializable incremental_capability(add|retract|both|none) explainable(Level) ``` A package should never imply stronger guarantees than its declared profile proves. ## Suggested standard profile family after #398B ```text kernel_ground horn_safe datalog_wfs % semantics finalized by #400 existential_warded % guarded/warded existential rules dl_rl_like fol_preserve contextual_theory temporal_event temporal_interval constraint_fd constraint_qr procedural defeasible % semantics finalized by #400 probabilistic_annotation % preservation unless explicit probabilistic reasoner ``` `contextual_theory` may ultimately be a kernel capability rather than a separate profile; implementation research should decide after #400/#402. --- # Performance / scale implications ## 1. Do not query one universal union graph At millions/billions of records, every task should compile to: ```text goal -> context/theory selection -> relevant vocabulary/profile selection -> indexed assertion/rule slice -> profile reasoner ``` This naturally aligns with #381 retrieval/projection. ## 2. Ground + Horn remains the hot path Function-free Horn/Datalog should be the principal zero-LLM reasoning workhorse. Semi-naive evaluation, tabling and specialized relational representations are mature. Soufflé demonstrates that Datalog can handle large real-world analyses with compiled/specialized execution, and XSB/SWI provide tabled logic-programming paths. ## 3. Existential reasoning must be opt-in General Datalog with existential heads is undecidable. Use warded/guarded/acyclic fragments and bounded chase/query-directed methods. Vadalog is strong evidence for Warded Datalog± as a serious candidate profile, not necessarily a dependency. ## 4. Context closure must be bounded Recursive imports/bridges need cycle detection, memoization and explicit selection. Do not automatically union all ancestor microtheories. ## 5. Provenance can dominate storage A conclusion can have combinatorially many derivations. Persist compact shared dependency structure and bounded material explanations; do not persist a complete expanded proof tree for every answer. ## 6. Specialized reasoners should be legal The semantic IR is an interchange/control plane. A query may dispatch to: ```text SWI/XSB tabling compiled Datalog engine CLP(FD/Q/R) OWL/DL reasoner existential-rule reasoner future probabilistic reasoner ``` provided the profile mapping is trusted and semantics-preserving for the admitted subset. `Prolog-RLM` owns the semantic contract, not necessarily every low-level solver algorithm. --- # Adversarial review ## Attack 1: contexts become an ontology-management nightmare Correct risk. A system that creates a unique full context for every source × time × speaker × scenario × ontology version will explode. **Countermeasure:** contexts have stable opaque identity plus facets; theory membership/imports/bridges are sparse explicit relations. Query context composition is computed, not eagerly cross-product materialized. ## Attack 2: bridge rules are just hidden trust heuristics They can be. Therefore bridge provenance/status must be explicit and inspectable, and compiler/model proposals cannot auto-activate trusted bridges. ## Attack 3: proposition canonicalization breaks intensional meaning Two syntactically similar formulas can differ by context, vocabulary version, quantifier binding or concept identity. **Countermeasure:** proposition structural fingerprints are scoped to canonicalized formula + exact vocabulary/signature version. Assertion/context identity remains separate. Cross-vocabulary equivalence is explicit knowledge, never fingerprint magic. ## Attack 4: existential witnesses pollute entity reconciliation Very real. A labelled null is not an entity assertion. **Countermeasure:** use a distinct `witness` semantic kind with scope/origin; reconciliation may link it later but cannot silently rewrite it into a global entity. ## Attack 5: justification graph becomes larger than the KB Likely for recursive rules. **Countermeasure:** shared DAG/hyperedges, derivation-class retention policy, on-demand explanation, and derived-cache eviction. Durable source assertions remain enough to replay/rederive. ## Attack 6: four-valued status conflicts with stable/well-founded/default semantics It can if treated as the universal logic. **Countermeasure:** use support/refutation pair as a **query information summary** over assertion evidence, while each reasoning profile defines its own consequence semantics. Pass #400 decides default/nonmonotonic semantics. ## Attack 7: too many reasoning profiles fragment the system Also real. **Countermeasure:** profiles form a small versioned registry with explicit capability/compatibility declarations. Prefer a handful of standardized profiles; unknown domain vocabulary should not require a new profile. Profiles vary **semantics**, vocabularies vary **domain concepts**. ## Attack 8: arbitrary web/LLM text can create rules that later execute Still forbidden. ```text compiled procedure/rule != trusted runtime predicate != authority to perform action ``` A model can generate candidate semantic data. Validation can admit it as knowledge. Only separately trusted expert/tool/capability mapping can cause host effects. --- # Concrete canonical changes recommended ## Update #392 semantic IR Add explicit requirements for: 1. first-class `context` and `theory` identities; 2. sparse context facets + imports/bridge relations; 3. source assertion context distinct from promoted/world theory membership; 4. first-class scoped existential witnesses/labeled unknowns; 5. explicit justification/derivation hypergraph schema; 6. support/refutation-preserving assertion polarity sufficient to compute `neither/supported/refuted/both` information states; 7. profile capability contracts including query class, decidability where known, lowerer and incremental/materialization behavior; 8. versioned signature/vocabulary identity in proposition fingerprints; 9. canonical vs rebuildable-derived-state separation; 10. validation-shape/schema layer separate from inference semantics; 11. optional annotation algebra interface without treating confidence/probability/trust/provenance as one number. ## Downstream symbolic-memory #4/#6 Storage must preserve `context/theory/witness/justification` records and must not flatten them into generic triples. Current views should be theory/context aware and derived materializations must be explicitly rebuildable. ## Pass #400 boundary Do **not** prematurely settle: - stable vs well-founded semantics; - belief revision policy; - default specificity/priorities; - ATMS environment management; - paraconsistent consequence relation; - probabilistic confidence calculus. #398B only ensures the representation does not destroy the information those later semantics need. --- # Revised north-star representation test Compile a corpus containing all of: 1. a Wikipedia revision making a declarative assertion; 2. a news report quoting two conflicting sources; 3. an LLM troubleshooting conversation that produces a successful repair outcome; 4. a manual containing a conditional procedure and exception; 5. scientific prose containing a universal and an existential claim; 6. two ontology versions using different but alignable terms; 7. a hypothetical scenario that contradicts current-world data. With the original prose removed from reasoning context, the IR/world-model must be able to answer: ```text What is asserted in the general world theory? What did each source separately claim? Which conclusions are conflicted? Which facts are only hypothetical? Which anonymous/existential entities remain unresolved? What rule/procedure applies to the failure? Why does the system believe that procedure applies? Which derivations depend on the old ontology mapping? What would become invalid if source assertion A were retracted/superseded? ``` Every answer must return theory/context, profile, supporting/refuting assertion IDs and exact source/derivation provenance. ## #398B conclusion The original preferred design remains valid but is incomplete. **Machine Spirit should be designed as a contextual theory system, not a flat knowledge graph.** The refined core is: ```text semantic formula/proposition + assertion episode + context / theory + scoped existential witnesses + justification dependencies + declared reasoning profile ``` That combination is substantially better suited to the user's actual intended ingestion domain — arbitrary LLM logs, web/news/encyclopedia text, manuals and research — because it distinguishes *meaning*, *who/what said it*, *under what assumptions/world/time it applies*, *what is still unknown*, and *why a derived conclusion follows*. The next numbered pass remains **#399 semantic compilation from language**. It should now target this richer context/theory/witness/justification IR and actively test whether language compilation can populate it without losing attribution, quantification, discourse scope or procedural semantics.
Author
Owner

Deepening pass #398C — modular heterogeneous theories, conservative imports, logic composition, and ontology boundaries

This is subpass C of four for Machine Spirit depth 1 (#398). A/B established the semantic kernel, proposition/assertion split, first-class contexts/theories, scoped witnesses, justification hypergraphs, and explicit reasoning profiles. This pass attacks a remaining hidden assumption: that one world model can be safely treated as a single theory with a shared vocabulary and a single import operation.

For the intended inputs — LLM logs, Wikipedia revisions, news sources, scientific literature, manuals, policies, project-specific knowledge, historical schemas, and domain ontologies — that assumption is false. Machine Spirit must support many partially overlapping theories whose domains, identities, vocabularies, and consequence relations need not coincide.

Research questions

  1. What does it mean to safely combine two theories without changing old conclusions unexpectedly?
  2. How should relations between different ontologies/logics be represented when their individual domains and identity assumptions differ?
  3. Should module imports mean textual union, semantic conservative extension, query-preserving projection, or something weaker?
  4. How can a general knowledge system connect temporal, spatial, taxonomic, Horn, constraint, procedural, and preservation-only theories without taking the complexity of their unrestricted product?
  5. How do we keep new domain vocabularies cheap/open while making ontology/version boundaries explicit enough for replay and provenance?

Primary / authoritative sources inspected

  • Kutz, Lutz, Wolter & Zakharyaschev, E-Connections of Abstract Description Systems, Artificial Intelligence 156(1), 2004. https://iccl.inf.tu-dresden.de/web/LATPub284/en — E-connections combine decidable KR systems through explicit link relations while preserving decidability transfer under stated conditions. The important architectural lesson is that connection does not require flattening all component domains into one interpretation.
  • Borgida & Serafini, Distributed Description Logics: Assimilating Information from Peer Sources, 2003, DOI 10.1007/978-3-540-39733-5_7. This explicitly studies independent information sources that maintain different views and may not have one-to-one mappings between their individuals.
  • Botoeva, Konev, Lutz, Ryzhikov, Wolter & Zakharyaschev, Inseparability and Conservative Extensions of Description Logic Ontologies, 2017/2018. https://arxiv.org/abs/1804.07805 — “safe replacement” is query/application dependent; query inseparability, concept inseparability and conservative extension are materially different contracts.
  • ISO/IEC 24707:2018 Common Logic. https://www.iso.org/standard/66249.html — a family/interchange framework can provide broad declarative semantics without claiming to solve computation/optimization uniformly.
  • W3C SHACL Recommendation and SHACL 1.2 work. https://www.w3.org/TR/shacl/ and https://www.w3.org/TR/shacl-core/ — structural validation is a separate operation from entailment; reusable shapes can be imported independently from the data graph being validated.

Core finding

import is too vague to be a primitive. Machine Spirit needs a typed theory composition algebra where every edge declares what semantic promise it makes.

A source-context theory, an ontology module, a rule module, and a constraint solver profile should not all be connected by one imports/2 relation.

Recommended canonical distinction:

include          = include records under the same semantics/profile/version
reference        = make symbols/records addressable; no entailment transfer
translate        = map expressions through an explicit semantics-preserving/declared transform
bridge           = derive statements across theories under explicit bridge rules
conservative_ext = extension promises not to change old-language consequences
query_preserve   = preserve answers for a declared query/signature class
project          = expose only a selected vocabulary/consequence interface
link_domain      = relate entities across distinct interpretation domains

These are semantic contracts, not filesystem-module mechanisms.

Candidate architecture A — global merged theory

Normalize all accepted records into one canonical vocabulary and let profile tags distinguish semantics.

Advantages: easiest querying; simple index; straightforward cross-source joins.

Failure: identity and ontology boundaries become accidental. Adding a new ontology/rule set can alter conclusions everywhere. Conflicting closed-world/open-world assumptions leak. Imported defaults interact globally. Version replay becomes fragile. This is acceptable only as a materialized query view, never canonical semantics.

Reject as canonical design.

Candidate architecture B — fully isolated microtheories with arbitrary bridges

Every source/domain/profile is a separate theory. Cross-theory reasoning occurs only through model/compiler-proposed bridge rules.

Advantages: strong isolation; easy provenance.

Failure: knowledge becomes fragmented; bridge explosion; model-generated mappings become hidden semantic authority; no contract that a bridge preserves meaning or queries.

Reject in this unrestricted form.

Candidate architecture C — typed theory graph + declared interfaces (preferred)

Represent theories/modules as first-class objects with explicit signatures, profile contracts and typed composition edges.

Conceptual API/data:

sem_theory(T,
           context(Context),
           vocabulary(VocabVersion),
           profiles(ProfileRefs),
           exports(SignatureRef),
           assumptions(AssumptionSet),
           meta(Meta)).

sem_theory_edge(E,
                From,
                To,
                kind(Kind),
                mapping(MappingRef),
                contract(ContractRef),
                status(Status),
                provenance(Provenance)).

Where Kind is closed/versioned and can represent the contracts above.

Export signatures are first-class

A theory should declare an interface:

sem_signature_set(sig_weather_v1,
  [predicate(temperature,[location,time,quantity]),
   predicate(raining,[location,time])]).

Internal symbols/rules need not be globally addressable. This makes a theory closer to a module with a semantic API.

Mappings are data, not predicate aliases

sem_mapping(map7,
  source_symbol(src:maintainer),
  target_symbol(project:repository_maintainer),
  relation(narrower_than),
  conditions(...),
  provenance(...)).

Do not rewrite source records. A mapping is reversible provenance-bearing knowledge.

Theory edges carry proof obligations

A composition edge can declare:

contract = syntactic_only
contract = sound_for(QueryClass)
contract = complete_for(QueryClass)
contract = conservative_over(Signature)
contract = unknown/unverified

A model/compiler may propose an edge, but trusted admission determines whether it can participate in automatic inference. Unverified mappings remain searchable evidence.

Logic combination lesson from E-connections

Do not attempt unrestricted cross-profile formula nesting as the default composition mechanism.

Prefer link relations between theories/domains:

link(person_theory:alice,
     temporal_theory:alice_lifespan,
     represents_lifespan).

A temporal solver can reason about the lifespan object; a taxonomic reasoner can reason about the person; a declared bridge moves only the required result between them.

This avoids turning Horn × temporal × spatial × modal × constraint × defeasible into one giant undecidable logic.

Conservative change / ontology evolution

The append-only model needs more than schema version numbers. For each new theory/vocabulary version, allow a conformance test expressing the intended compatibility contract.

Conceptual forms:

sem_version_relation(v2, extends, v1).
sem_compatibility(v2, v1,
                  conservative_over(Signature),
                  evidence(TestOrProofRef)).

If no proof/test exists, compatibility status is unverified; never infer that a newer ontology is backwards-compatible merely because its version number increased.

This directly supports historical LLM/web ingestion: old interpretations stay tied to the vocabulary/theory version under which they were compiled.

Query projections should be semantic modules

A bounded projection for an expert/model should itself declare:

source theories
exported signature
query class
theory edges followed
profiles used
materialized consequences included
known omitted/unsupported semantics

Thus projection is not “top-K facts”; it is a replayable query-specific module.

Validation versus entailment

SHACL reinforces an important boundary: structural/schema validation must remain separate from semantic entailment.

For Machine Spirit:

IR schema validation
vocabulary/signature validation
theory-edge contract validation
reasoning-profile admission
query execution

are distinct gates.

A record may be structurally valid but belong to a theory that cannot legally import into the current query environment.

Complexity / scaling

  • Maintain local indexes/materializations per theory/profile where possible.
  • Cross-theory queries should expand a bounded theory dependency graph rather than union the entire KB.
  • The complexity of a composed query is governed by the selected component profiles + bridge/link restrictions; do not advertise the weakest component's guarantee as the whole system's guarantee automatically.
  • Conservative-extension checking is expensive/undecidable in broad logics; treat exact proof as profile-dependent and allow regression/query-suite evidence as a weaker explicitly labeled contract.
  • Store theory edges and mappings separately from source assertions so changing an alignment invalidates only dependent materializations/justifications.

Epistemic / provenance consequences

A conclusion derived across modules needs a justification path containing:

assertion(s)
 -> source theory
 -> mapping/bridge edge(s)
 -> profile reasoner(s)
 -> target theory/query module
 -> conclusion

A result can therefore say not only “source A supports P,” but “P follows only if ontology mapping M and bridge B are accepted.”

That is essential when an LLM-derived ontology alignment is uncertain.

Safety consequences

  • Theory imports grant semantic visibility, never host authority.
  • A source ontology declaring permitted(delete_file) remains epistemic data.
  • Cross-theory mappings cannot bind semantic symbols directly to runtime tools.
  • Mapping/bridge admission is separate from execution-capability admission.
  • A malicious imported ontology cannot gain runtime behavior by choosing predicate names matching host predicates.

Adversarial cases / required fixtures

  1. Two ontologies use owner differently; naive merge yields false equivalence. Typed mapping must preserve distinction.
  2. Historical schema v1 and current v2 differ; replay under v1 still returns historical interpretation.
  3. A bridge is retracted; dependent derived facts disappear from current materialization but remain explainable historically.
  4. Two independently decidable profiles are linked; unrestricted nesting is rejected while an admitted link relation remains queryable.
  5. A source theory is structurally valid but its mapping contract is unverified; it must not silently affect authoritative world-theory conclusions.
  6. Query projection reports exactly which theory edges it traversed.

Canonical recommendations

  1. Extend #392 theory/context model with export signatures + typed theory edges + mapping/compatibility contracts.
  2. #394 must treat reasoning profile composition and theory-edge traversal as explicit input to lowering/querying.
  3. #396 semantic_projection/4 should return a replayable query module/receipt, not an untyped list of relevant facts.
  4. symbolic-memory #6 should persist theory/mapping/version edges append-only and invalidate dependent materialized views when an edge changes.
  5. symbolic-memory #10 identity/ontology reconciliation should emit typed mappings (equivalent, narrower, broader, overlap, different) with theory/signature scope rather than global same_as shortcuts.

Rejected alternatives

  • one global canonical ontology;
  • plain textual module imports;
  • globally rewriting source vocabulary into canonical names;
  • unrestricted formula nesting between reasoning profiles;
  • treating ontology version increment as proof of compatibility;
  • letting model-proposed alignments participate in inference without explicit status/admission.

Depth-1 delta

A/B gave Machine Spirit proposition → assertion → context/theory → justification → profile.

C makes the theory layer modular and compositional:

many semantic theories
      ↓
explicit interfaces/signatures
      ↓
typed mappings / links / bridges
      ↓
query-specific bounded composition
      ↓
profile-specific reasoning

The world model is therefore a network of theories with explicit semantic contracts, not one enormous global Prolog database.

This subpass intentionally does not decide truth revision/default logic (#400) or long-term persistence engine details (#402).

## Deepening pass #398C — modular heterogeneous theories, conservative imports, logic composition, and ontology boundaries This is **subpass C of four for Machine Spirit depth 1 (#398)**. A/B established the semantic kernel, proposition/assertion split, first-class contexts/theories, scoped witnesses, justification hypergraphs, and explicit reasoning profiles. This pass attacks a remaining hidden assumption: that one world model can be safely treated as a single theory with a shared vocabulary and a single import operation. For the intended inputs — LLM logs, Wikipedia revisions, news sources, scientific literature, manuals, policies, project-specific knowledge, historical schemas, and domain ontologies — that assumption is false. Machine Spirit must support **many partially overlapping theories whose domains, identities, vocabularies, and consequence relations need not coincide**. ### Research questions 1. What does it mean to safely combine two theories without changing old conclusions unexpectedly? 2. How should relations between different ontologies/logics be represented when their individual domains and identity assumptions differ? 3. Should module imports mean textual union, semantic conservative extension, query-preserving projection, or something weaker? 4. How can a general knowledge system connect temporal, spatial, taxonomic, Horn, constraint, procedural, and preservation-only theories without taking the complexity of their unrestricted product? 5. How do we keep new domain vocabularies cheap/open while making ontology/version boundaries explicit enough for replay and provenance? ### Primary / authoritative sources inspected - Kutz, Lutz, Wolter & Zakharyaschev, **E-Connections of Abstract Description Systems**, *Artificial Intelligence* 156(1), 2004. https://iccl.inf.tu-dresden.de/web/LATPub284/en — E-connections combine decidable KR systems through explicit link relations while preserving decidability transfer under stated conditions. The important architectural lesson is that *connection* does not require flattening all component domains into one interpretation. - Borgida & Serafini, **Distributed Description Logics: Assimilating Information from Peer Sources**, 2003, DOI 10.1007/978-3-540-39733-5_7. This explicitly studies independent information sources that maintain different views and may not have one-to-one mappings between their individuals. - Botoeva, Konev, Lutz, Ryzhikov, Wolter & Zakharyaschev, **Inseparability and Conservative Extensions of Description Logic Ontologies**, 2017/2018. https://arxiv.org/abs/1804.07805 — “safe replacement” is query/application dependent; query inseparability, concept inseparability and conservative extension are materially different contracts. - ISO/IEC 24707:2018 **Common Logic**. https://www.iso.org/standard/66249.html — a family/interchange framework can provide broad declarative semantics without claiming to solve computation/optimization uniformly. - W3C **SHACL** Recommendation and SHACL 1.2 work. https://www.w3.org/TR/shacl/ and https://www.w3.org/TR/shacl-core/ — structural validation is a separate operation from entailment; reusable shapes can be imported independently from the data graph being validated. ### Core finding **`import` is too vague to be a primitive.** Machine Spirit needs a typed *theory composition algebra* where every edge declares what semantic promise it makes. A source-context theory, an ontology module, a rule module, and a constraint solver profile should not all be connected by one `imports/2` relation. Recommended canonical distinction: ```text include = include records under the same semantics/profile/version reference = make symbols/records addressable; no entailment transfer translate = map expressions through an explicit semantics-preserving/declared transform bridge = derive statements across theories under explicit bridge rules conservative_ext = extension promises not to change old-language consequences query_preserve = preserve answers for a declared query/signature class project = expose only a selected vocabulary/consequence interface link_domain = relate entities across distinct interpretation domains ``` These are semantic contracts, not filesystem-module mechanisms. ### Candidate architecture A — global merged theory Normalize all accepted records into one canonical vocabulary and let profile tags distinguish semantics. **Advantages:** easiest querying; simple index; straightforward cross-source joins. **Failure:** identity and ontology boundaries become accidental. Adding a new ontology/rule set can alter conclusions everywhere. Conflicting closed-world/open-world assumptions leak. Imported defaults interact globally. Version replay becomes fragile. This is acceptable only as a *materialized query view*, never canonical semantics. **Reject as canonical design.** ### Candidate architecture B — fully isolated microtheories with arbitrary bridges Every source/domain/profile is a separate theory. Cross-theory reasoning occurs only through model/compiler-proposed bridge rules. **Advantages:** strong isolation; easy provenance. **Failure:** knowledge becomes fragmented; bridge explosion; model-generated mappings become hidden semantic authority; no contract that a bridge preserves meaning or queries. **Reject in this unrestricted form.** ### Candidate architecture C — typed theory graph + declared interfaces **(preferred)** Represent theories/modules as first-class objects with explicit signatures, profile contracts and typed composition edges. Conceptual API/data: ```prolog sem_theory(T, context(Context), vocabulary(VocabVersion), profiles(ProfileRefs), exports(SignatureRef), assumptions(AssumptionSet), meta(Meta)). sem_theory_edge(E, From, To, kind(Kind), mapping(MappingRef), contract(ContractRef), status(Status), provenance(Provenance)). ``` Where `Kind` is closed/versioned and can represent the contracts above. #### Export signatures are first-class A theory should declare an interface: ```prolog sem_signature_set(sig_weather_v1, [predicate(temperature,[location,time,quantity]), predicate(raining,[location,time])]). ``` Internal symbols/rules need not be globally addressable. This makes a theory closer to a module with a semantic API. #### Mappings are data, not predicate aliases ```prolog sem_mapping(map7, source_symbol(src:maintainer), target_symbol(project:repository_maintainer), relation(narrower_than), conditions(...), provenance(...)). ``` Do not rewrite source records. A mapping is reversible provenance-bearing knowledge. #### Theory edges carry proof obligations A composition edge can declare: ```text contract = syntactic_only contract = sound_for(QueryClass) contract = complete_for(QueryClass) contract = conservative_over(Signature) contract = unknown/unverified ``` A model/compiler may propose an edge, but trusted admission determines whether it can participate in automatic inference. Unverified mappings remain searchable evidence. ### Logic combination lesson from E-connections Do not attempt unrestricted cross-profile formula nesting as the default composition mechanism. Prefer **link relations between theories/domains**: ```prolog link(person_theory:alice, temporal_theory:alice_lifespan, represents_lifespan). ``` A temporal solver can reason about the lifespan object; a taxonomic reasoner can reason about the person; a declared bridge moves only the required result between them. This avoids turning `Horn × temporal × spatial × modal × constraint × defeasible` into one giant undecidable logic. ### Conservative change / ontology evolution The append-only model needs more than schema version numbers. For each new theory/vocabulary version, allow a conformance test expressing the intended compatibility contract. Conceptual forms: ```prolog sem_version_relation(v2, extends, v1). sem_compatibility(v2, v1, conservative_over(Signature), evidence(TestOrProofRef)). ``` If no proof/test exists, compatibility status is `unverified`; never infer that a newer ontology is backwards-compatible merely because its version number increased. This directly supports historical LLM/web ingestion: old interpretations stay tied to the vocabulary/theory version under which they were compiled. ### Query projections should be semantic modules A bounded projection for an expert/model should itself declare: ```text source theories exported signature query class theory edges followed profiles used materialized consequences included known omitted/unsupported semantics ``` Thus projection is not “top-K facts”; it is a replayable **query-specific module**. ### Validation versus entailment SHACL reinforces an important boundary: structural/schema validation must remain separate from semantic entailment. For Machine Spirit: ```text IR schema validation vocabulary/signature validation theory-edge contract validation reasoning-profile admission query execution ``` are distinct gates. A record may be structurally valid but belong to a theory that cannot legally import into the current query environment. ### Complexity / scaling - Maintain local indexes/materializations per theory/profile where possible. - Cross-theory queries should expand a bounded theory dependency graph rather than union the entire KB. - The complexity of a composed query is governed by the selected component profiles + bridge/link restrictions; do not advertise the weakest component's guarantee as the whole system's guarantee automatically. - Conservative-extension checking is expensive/undecidable in broad logics; treat exact proof as profile-dependent and allow regression/query-suite evidence as a weaker explicitly labeled contract. - Store theory edges and mappings separately from source assertions so changing an alignment invalidates only dependent materializations/justifications. ### Epistemic / provenance consequences A conclusion derived across modules needs a justification path containing: ```text assertion(s) -> source theory -> mapping/bridge edge(s) -> profile reasoner(s) -> target theory/query module -> conclusion ``` A result can therefore say not only “source A supports P,” but “P follows only if ontology mapping M and bridge B are accepted.” That is essential when an LLM-derived ontology alignment is uncertain. ### Safety consequences - Theory imports grant **semantic visibility**, never host authority. - A source ontology declaring `permitted(delete_file)` remains epistemic data. - Cross-theory mappings cannot bind semantic symbols directly to runtime tools. - Mapping/bridge admission is separate from execution-capability admission. - A malicious imported ontology cannot gain runtime behavior by choosing predicate names matching host predicates. ### Adversarial cases / required fixtures 1. Two ontologies use `owner` differently; naive merge yields false equivalence. Typed mapping must preserve distinction. 2. Historical schema v1 and current v2 differ; replay under v1 still returns historical interpretation. 3. A bridge is retracted; dependent derived facts disappear from current materialization but remain explainable historically. 4. Two independently decidable profiles are linked; unrestricted nesting is rejected while an admitted link relation remains queryable. 5. A source theory is structurally valid but its mapping contract is unverified; it must not silently affect authoritative world-theory conclusions. 6. Query projection reports exactly which theory edges it traversed. ### Canonical recommendations 1. Extend #392 theory/context model with **export signatures + typed theory edges + mapping/compatibility contracts**. 2. #394 must treat reasoning profile composition and theory-edge traversal as explicit input to lowering/querying. 3. #396 `semantic_projection/4` should return a replayable query module/receipt, not an untyped list of relevant facts. 4. symbolic-memory #6 should persist theory/mapping/version edges append-only and invalidate dependent materialized views when an edge changes. 5. symbolic-memory #10 identity/ontology reconciliation should emit typed mappings (`equivalent`, `narrower`, `broader`, `overlap`, `different`) with theory/signature scope rather than global `same_as` shortcuts. ### Rejected alternatives - one global canonical ontology; - plain textual module imports; - globally rewriting source vocabulary into canonical names; - unrestricted formula nesting between reasoning profiles; - treating ontology version increment as proof of compatibility; - letting model-proposed alignments participate in inference without explicit status/admission. ### Depth-1 delta A/B gave Machine Spirit `proposition → assertion → context/theory → justification → profile`. C makes the theory layer **modular and compositional**: ```text many semantic theories ↓ explicit interfaces/signatures ↓ typed mappings / links / bridges ↓ query-specific bounded composition ↓ profile-specific reasoning ``` The world model is therefore a **network of theories with explicit semantic contracts**, not one enormous global Prolog database. This subpass intentionally does not decide truth revision/default logic (#400) or long-term persistence engine details (#402).
Author
Owner

Deepening pass #398D — deductive execution substrate: Datalog compilation, demand transformation, incremental tabling, CHR/constraints, and derived-state architecture

This is subpass D of four for Machine Spirit depth 1 (#398). A/B/C now define a rich semantic object model and modular theory graph. D asks the operational question that decides whether any of this can become useful intelligence rather than archival semantics:

How should Machine Spirit compile admitted semantic theories into fast, bounded, explainable zero-LLM reasoning plans without collapsing canonical knowledge into implementation-specific Prolog clauses?

This pass stays at the KR/execution boundary. It does not choose non-monotonic truth semantics (#400), durable storage technology (#402), or symbolic attention/retrieval policy (#403). It defines the execution architecture those later passes can rely on.

Research questions

  1. Which fragments should be compiled to bottom-up Datalog/materialization, top-down tabled evaluation, demand-transformed rules, CHR/constraint solvers, or preservation-only inspection?
  2. How do we avoid deriving the entire closure of a million-record world model for every query?
  3. What should be canonical versus rebuildable derived state?
  4. How can update invalidation, proof/explanation and query optimization share one dependency representation?
  5. How do we keep compiled execution plans deterministic/replayable and separate from semantic authority?

Primary / authoritative sources inspected

  • Bancilhon, Maier, Sagiv & Ullman, Magic Sets and Other Strange Ways to Implement Logic Programs, PODS 1986, DOI 10.1145/6012.15399. Magic Sets rewrite logic programs so bottom-up evaluation is restricted toward facts relevant to the query, combining database joins/materialization with demand information.
  • Abiteboul, Hull & Vianu, Foundations of Databases (1995). The deductive-database framework gives the right separation between declarative Datalog meaning and evaluation strategy, including safety/fixpoint foundations.
  • Modern Datalog systems continue to use semi-naive evaluation, computing deltas rather than recomputing the entire recursive closure each iteration; e.g. Nexus and modern declarative systems use semi-naive/delta iteration for graph workloads.
  • SWI-Prolog Incremental Tabling documentation: https://www.swi-prolog.org/pldoc/man?section=tabling-incremental . SWI maintains an Incremental Dependency Graph: changes to dynamic incremental predicates invalidate dependent tables; re-evaluation happens on demand and propagates only when answers actually change.
  • Frühwirth / Schrijvers et al., Constraint Handling Rules (CHR). CHR is a declarative rule language for writing constraint solvers and transformations, with Prolog-host implementations, but its operational semantics are materially different from plain Horn deduction.
  • W3C SHACL reinforces the distinction between structural validation and inference; validation processors leave input graphs unchanged and produce separate validation results.
  • ISO Common Logic reinforces representation/interchange without prescribing one universal computational strategy.

Core finding

The preferred architecture is not “lower semantic IR to Prolog clauses and query them.”

It is a three-plane system:

CANONICAL SEMANTIC PLANE
  immutable propositions/assertions/theories/rules/contexts/provenance
                       ↓ compile
DEDUCTIVE PLAN PLANE
  profile-selected normalized rules + indexes + dependency plan + demand transform
                       ↓ execute
DERIVED STATE PLANE
  tables/materializations/constraint results/query caches/proof receipts

Only the first plane is semantic source-of-truth. The other two are rebuildable.

Candidate architecture A — direct Prolog lowering

Translate every admitted relation/rule to generated Prolog predicates and rely on normal SLD execution.

Strengths: simple prototype; excellent interactive ergonomics.

Failures:

  • predicate namespace becomes semantic namespace;
  • execution behavior depends on clause order/indexing/control accidents;
  • loops/left recursion/nontermination become easy;
  • cross-source invalidation is opaque;
  • query provenance/explanation is bolted on later;
  • arbitrary large theory closure is not managed as a dataflow/dependency problem.

Reject as canonical execution architecture. Trusted generated helper predicates may exist inside a compiled reasoner module, but never as the semantic model itself.

Candidate architecture B — pure bottom-up materialization

Compile every admissible Horn theory to Datalog and materialize its complete least fixpoint.

Strengths: deterministic; database-friendly; excellent for repeated broad queries; simple provenance/materialization semantics.

Failure: large heterogeneous KBs will derive enormous irrelevant closure. Temporal/event/identity relations may explode. Updating one base assertion can force costly recomputation without incremental dependency tracking.

Keep as one execution strategy, not the universal strategy.

Candidate architecture C — pure top-down tabled Prolog

Use tabled evaluation for all rule queries, memoizing answers.

Strengths: demand-driven; avoids irrelevant global closure; handles many recursive definitions elegantly.

Failure: less natural for broad reusable materializations, database-style joins, distributed/streaming updates, and bulk rule application; requires careful mapping of semantic update invalidation into table dependencies.

Keep as another strategy.

Candidate architecture D — profile compiler + hybrid demand/materialization engine (preferred)

The runtime compiles each admitted theory/query into an explicit deductive plan.

Conceptually:

semantic_prepare_query(+TheoryGraph,
                       +QueryIR,
                       +Options,
                       -DeductivePlan).

semantic_execute_plan(+DeductivePlan,
                      +RuntimeState,
                      -Outcome).

DeductivePlan is inspectable data containing at minimum:

selected theories and versions
selected semantic profiles
query signature/bindings
normalized safe rules
rule stratification / SCCs where relevant
chosen evaluation mode per component
required indexes
magic/demand transformations
constraint solver calls
materialization/table dependencies
proof/justification capture policy
resource bounds
unsupported/preservation-only nodes
plan fingerprint

No model is needed to execute an already-compiled symbolic plan.

1. Horn/Datalog as the primary zero-LLM workhorse

For function-free/range-restricted monotonic rules, compile to a Datalog-like normalized form.

Example semantic rule:

maintains(P,R) ∧ vulnerable(R) -> responsible_for(P, patching(R))

becomes internal rule data, not source clauses:

kr_rule(r17,
        head(atom(responsible_for,[var(p),patching(var(r))])),
        body([atom(maintains,[var(p),var(r)]),
              atom(vulnerable,[var(r)])]),
        profile(horn_safe),
        provenance(...)).

The compiler can then map that closed representation into a trusted generic Datalog evaluator or generated private reasoner code.

2. Semi-naive materialization

For repeated/broad queries, use delta fixpoint semantics:

I0 = base facts
Δ1 = rules(I0)
I1 = I0 ∪ Δ1
Δ2 = only consequences involving Δ1
...

This avoids recomputing old consequences at each recursive iteration.

Materializations are indexed by:

theory version
profile version
rule-set fingerprint
base semantic generation

They are caches, never historical truth.

3. Magic/demand transformation

For narrow queries over large rule sets, transform evaluation so bottom-up reasoning follows top-down demand.

Example:

query: responsible_for(alice, What)

should not materialize responsible_for/2 for every entity in years of ingested logs.

The plan records the demand transformation and its query binding pattern, making it reproducible/explainable.

This is one of the most important scaling ideas for Machine Spirit: symbolic attention can begin at the deductive compiler, before later retrieval/model projection.

4. Tabled evaluation for recursive/demand-heavy components

Use tabling where query-directed recursion is natural. On SWI, tabling already provides a mature primitive and incremental tabling provides dependency-driven invalidation.

Crucial abstraction:

semantic dependency graph
        ↓ compile
runtime dependency/table graph

Do not expose SWI's table identifiers as canonical knowledge IDs. They are an implementation detail of one backend.

5. Incremental invalidation

Every derived answer/materialization should depend on canonical semantic generations/edges.

When an assertion, theory mapping, bridge, rule, or lifecycle status changes:

append semantic event
       ↓
identify affected dependency nodes
       ↓
invalidate derived tables/materializations
       ↓
recompute lazily or eagerly according to plan/profile

SWI's Incremental Dependency Graph is direct evidence that this pattern is practical for tabled logic programming: updated dynamic predicates mark dependent tables invalid and re-evaluation occurs on demand.

The public contract should remain backend-neutral:

semantic_invalidate(+SemanticDelta, +State0, -State).
semantic_refresh(+QueryOrView, +Options, -Outcome).

6. Constraint profiles are solver calls, not ordinary predicates

CLP(FD), CLP(Q/R), temporal interval constraints, unit/dimension constraints, etc. should compile into explicit trusted solver nodes.

Example plan node:

solver_call(
  clp_fd,
  constraints([...closed validated expressions...]),
  inputs([...]),
  outputs([...])).

Never turn an arbitrary semantic expression into a Prolog callable term.

7. CHR as a trusted extension profile, not the universal rule language

CHR is attractive for:

  • constraint propagation;
  • normalization;
  • solver implementation;
  • equivalence/simplification rules;
  • incremental constraint stores.

But CHR has operational semantics (simplification/propagation/simpagation) distinct from Horn entailment.

Therefore define an optional trusted chr_constraint profile whose programs/extensions are host-admitted/versioned. Do not compile arbitrary natural-language rules directly into unrestricted CHR.

8. Validation compiles separately

Schema/shape checking should have its own validation plan:

Candidate IR
  -> shape/type/signature validator
  -> ValidationReport
  -> admitted semantic package

Validation failures are evidence; they do not mutate the candidate or silently repair it.

A later repair/compiler pass may propose corrected IR.

9. Explanations piggyback on evaluation

Every successful derived result should optionally emit a compact derivation receipt:

derivation_receipt(
  ResultAssertion,
  plan(PlanFingerprint),
  rule_apps([...]),
  premise_refs([...]),
  theory_edges([...]),
  solver_receipts([...]),
  semantic_generation(...)).

Do not duplicate full proof trees when common subderivations exist. Store/reference a justification DAG/hypergraph.

For hot ephemeral queries the proof structure may remain transient; promoted conclusions and action-relevant VERIFY evidence should retain replayable receipts.

10. Derived state has typed freshness

A materialized fact needs status equivalent to:

fresh       built from current admitted generations
invalid     a dependency changed
refreshing  recomputation underway
stale_read  explicitly allowed stale snapshot
unavailable reasoner/backend unavailable

No stale cached inference may silently masquerade as current truth.

Execution strategy selector

The compiler can use deterministic heuristics/profile metadata rather than an LLM:

small ground lookup                     -> indexed direct lookup
narrow recursive Horn query             -> tabled/demand evaluation
broad repeated Horn closure             -> semi-naive materialization
large narrow bottom-up Datalog query    -> magic-set/demand transform
finite-domain arithmetic                -> CLP(FD)
rational/real symbolic arithmetic       -> CLP(Q/R)
trusted constraint-rewrite theory       -> CHR profile
unsupported quantified FOL              -> structural/preservation query only

The choice and reason are included in the plan receipt.

Query planning and cross-theory composition

Subpass C's theory graph is used before rule execution:

query
  -> resolve query signature
  -> select candidate theory modules
  -> traverse admitted theory edges
  -> compute compatible profile composition
  -> normalize rules/facts into plan-local namespace
  -> choose evaluation strategy
  -> execute

The runtime never unions the entire durable KB first.

Performance model / complexity honesty

Each semantic profile declares known complexity/termination properties where possible. The plan may reject or bound a query whose requested composition escapes supported guarantees.

Examples:

  • positive function-free Datalog: finite least fixpoint;
  • stratified negation: only when explicitly admitted by later epistemic semantics;
  • unrestricted FOL: preservation/structural query, no generic termination promise;
  • existential rules: only admitted bounded/decidable fragments;
  • constraints: complexity delegated to declared trusted solver profile;
  • cross-profile composition: guarantees apply only under declared compatibility contract.

Do not turn a timeout into unknown=false; report resource_exhausted/unsupported separately from logical unknown.

Machine Spirit scaling consequences

For millions of semantic records:

  1. canonical store remains append-only/indexed;
  2. hot theory/profile materializations are selective;
  3. query demand narrows theories before execution;
  4. magic/demand transformations prevent irrelevant recursive closure;
  5. incremental dependency invalidation avoids global rebuilds;
  6. model prompts receive only post-reasoning bounded projections when a model is needed;
  7. known tasks execute entirely through the symbolic plan.

Safety / authority consequences

  • Deductive plan compilation grants no execution authority.
  • Semantic action restart(service) can be reasoned about as data but cannot invoke a tool.
  • Solver backends are allowlisted profile implementations.
  • Generated private Prolog code, if used as an optimization, is produced only from validated closed IR and loaded into a confined trusted module; its fingerprint is tied to the plan and source semantic generation.
  • No source/model-supplied predicate name is resolved to arbitrary host code.
  • Resource ceilings (time, inference steps, memory, table size) are runtime limits, not monetary/model budget charges.

Adversarial fixtures

  1. Recursive graph theory with 10^6 unrelated nodes; narrow query must avoid whole closure.
  2. Add one base assertion; only dependent tables/materializations invalidate.
  3. Retract/supersede a theory bridge; conclusions depending on it become invalid while unrelated tables remain fresh.
  4. Constraint expression tries to name shell/1; validator keeps it inert/unsupported.
  5. Recursive rule loop terminates through tabling/fixpoint in admitted profile.
  6. Unsupported FOL formula remains representable but planner refuses executable lowering.
  7. Re-run same query/semantic generation produces same plan fingerprint and equivalent result set.
  8. Full derivation explanation reconstructs source assertions + theory mappings + rules + solver evidence.
  9. Timeout/resource ceiling yields structured resource_exhausted, not semantic false/unknown.
  10. Model/provider disabled: a fully known Horn+constraint task still succeeds end-to-end.

Canonical recommendations

  1. #392: preserve the three-plane distinction: canonical semantic records != compiled deductive plan != derived materialization.
  2. #394: add an explicit plan compilation boundary and backend-neutral evaluation strategy contract; exact negation/default/conflict semantics still belong there/#400.
  3. #396: semantic_projection should be able to consume/query a prepared symbolic plan and expose its bounded dependency/theory slice rather than selecting context only by heuristic relevance.
  4. #381 retrieval: deductive demand should become one retrieval signal; a logical query can identify exactly which predicates/theories are relevant before embeddings are consulted.
  5. symbolic-memory #6: derived materializations are rebuildable caches keyed by semantic generation; canonical append-only semantics remain authoritative.
  6. #384 VERIFY expert: verification should accept derivation receipts as evidence but independently check required acceptance predicates rather than trusting a cached success label.

Rejected alternatives

  • direct semantic-IR -> arbitrary Prolog clauses as canonical representation;
  • full closure materialization of all theories by default;
  • pure top-down SLD without tabling/dependency tracking;
  • embedding all constraint semantics into Horn rules;
  • unrestricted model-generated CHR programs;
  • storing every intermediate proof tree durably;
  • treating cached/materialized inference as immutable truth;
  • using an LLM to choose an evaluation strategy when deterministic profile/query metadata suffice.

Depth-1 final architecture after A/B/C/D

                 EXACT SOURCE EVIDENCE
                        ↓
              VERSIONED SEMANTIC KERNEL
      terms / formulas / propositions / assertions
                        ↓
                CONTEXTS + THEORIES
             witnesses / validity / stance
                        ↓
               MODULAR THEORY GRAPH
    signatures / mappings / bridges / contracts
                        ↓
             JUSTIFICATION HYPERGRAPH
                        ↓
              REASONING PROFILE LATTICE
                        ↓
              DEDUCTIVE PLAN COMPILER
      theory slice / demand / rules / solvers
                        ↓
       HYBRID SYMBOLIC EXECUTION BACKENDS
 Datalog | tabling | materialization | CLP | CHR
                        ↓
           REBUILDABLE DERIVED WORLD VIEWS
                        ↓
       bounded projection / expert / conversation

This completes the four-subpass KR-foundations depth. It is still design/research evidence, not Machine Spirit acceptance. #399 should now attack whether language can be compiled into this architecture with acceptable semantic fidelity.

## Deepening pass #398D — deductive execution substrate: Datalog compilation, demand transformation, incremental tabling, CHR/constraints, and derived-state architecture This is **subpass D of four for Machine Spirit depth 1 (#398)**. A/B/C now define a rich semantic object model and modular theory graph. D asks the operational question that decides whether any of this can become useful intelligence rather than archival semantics: > How should Machine Spirit compile admitted semantic theories into fast, bounded, explainable **zero-LLM reasoning plans** without collapsing canonical knowledge into implementation-specific Prolog clauses? This pass stays at the KR/execution boundary. It does **not** choose non-monotonic truth semantics (#400), durable storage technology (#402), or symbolic attention/retrieval policy (#403). It defines the execution architecture those later passes can rely on. ### Research questions 1. Which fragments should be compiled to bottom-up Datalog/materialization, top-down tabled evaluation, demand-transformed rules, CHR/constraint solvers, or preservation-only inspection? 2. How do we avoid deriving the entire closure of a million-record world model for every query? 3. What should be canonical versus rebuildable derived state? 4. How can update invalidation, proof/explanation and query optimization share one dependency representation? 5. How do we keep compiled execution plans deterministic/replayable and separate from semantic authority? ### Primary / authoritative sources inspected - Bancilhon, Maier, Sagiv & Ullman, **Magic Sets and Other Strange Ways to Implement Logic Programs**, PODS 1986, DOI 10.1145/6012.15399. Magic Sets rewrite logic programs so bottom-up evaluation is restricted toward facts relevant to the query, combining database joins/materialization with demand information. - Abiteboul, Hull & Vianu, **Foundations of Databases** (1995). The deductive-database framework gives the right separation between declarative Datalog meaning and evaluation strategy, including safety/fixpoint foundations. - Modern Datalog systems continue to use **semi-naive evaluation**, computing deltas rather than recomputing the entire recursive closure each iteration; e.g. Nexus and modern declarative systems use semi-naive/delta iteration for graph workloads. - SWI-Prolog **Incremental Tabling** documentation: https://www.swi-prolog.org/pldoc/man?section=tabling-incremental . SWI maintains an Incremental Dependency Graph: changes to dynamic incremental predicates invalidate dependent tables; re-evaluation happens on demand and propagates only when answers actually change. - Frühwirth / Schrijvers et al., **Constraint Handling Rules (CHR)**. CHR is a declarative rule language for writing constraint solvers and transformations, with Prolog-host implementations, but its operational semantics are materially different from plain Horn deduction. - W3C **SHACL** reinforces the distinction between structural validation and inference; validation processors leave input graphs unchanged and produce separate validation results. - ISO Common Logic reinforces representation/interchange without prescribing one universal computational strategy. ### Core finding The preferred architecture is **not** “lower semantic IR to Prolog clauses and query them.” It is a three-plane system: ```text CANONICAL SEMANTIC PLANE immutable propositions/assertions/theories/rules/contexts/provenance ↓ compile DEDUCTIVE PLAN PLANE profile-selected normalized rules + indexes + dependency plan + demand transform ↓ execute DERIVED STATE PLANE tables/materializations/constraint results/query caches/proof receipts ``` Only the first plane is semantic source-of-truth. The other two are rebuildable. ### Candidate architecture A — direct Prolog lowering Translate every admitted relation/rule to generated Prolog predicates and rely on normal SLD execution. **Strengths:** simple prototype; excellent interactive ergonomics. **Failures:** - predicate namespace becomes semantic namespace; - execution behavior depends on clause order/indexing/control accidents; - loops/left recursion/nontermination become easy; - cross-source invalidation is opaque; - query provenance/explanation is bolted on later; - arbitrary large theory closure is not managed as a dataflow/dependency problem. **Reject as canonical execution architecture.** Trusted generated helper predicates may exist *inside a compiled reasoner module*, but never as the semantic model itself. ### Candidate architecture B — pure bottom-up materialization Compile every admissible Horn theory to Datalog and materialize its complete least fixpoint. **Strengths:** deterministic; database-friendly; excellent for repeated broad queries; simple provenance/materialization semantics. **Failure:** large heterogeneous KBs will derive enormous irrelevant closure. Temporal/event/identity relations may explode. Updating one base assertion can force costly recomputation without incremental dependency tracking. **Keep as one execution strategy, not the universal strategy.** ### Candidate architecture C — pure top-down tabled Prolog Use tabled evaluation for all rule queries, memoizing answers. **Strengths:** demand-driven; avoids irrelevant global closure; handles many recursive definitions elegantly. **Failure:** less natural for broad reusable materializations, database-style joins, distributed/streaming updates, and bulk rule application; requires careful mapping of semantic update invalidation into table dependencies. **Keep as another strategy.** ### Candidate architecture D — profile compiler + hybrid demand/materialization engine **(preferred)** The runtime compiles each admitted theory/query into an explicit deductive plan. Conceptually: ```prolog semantic_prepare_query(+TheoryGraph, +QueryIR, +Options, -DeductivePlan). semantic_execute_plan(+DeductivePlan, +RuntimeState, -Outcome). ``` `DeductivePlan` is inspectable data containing at minimum: ```text selected theories and versions selected semantic profiles query signature/bindings normalized safe rules rule stratification / SCCs where relevant chosen evaluation mode per component required indexes magic/demand transformations constraint solver calls materialization/table dependencies proof/justification capture policy resource bounds unsupported/preservation-only nodes plan fingerprint ``` No model is needed to execute an already-compiled symbolic plan. ## 1. Horn/Datalog as the primary zero-LLM workhorse For function-free/range-restricted monotonic rules, compile to a Datalog-like normalized form. Example semantic rule: ```text maintains(P,R) ∧ vulnerable(R) -> responsible_for(P, patching(R)) ``` becomes internal rule data, not source clauses: ```prolog kr_rule(r17, head(atom(responsible_for,[var(p),patching(var(r))])), body([atom(maintains,[var(p),var(r)]), atom(vulnerable,[var(r)])]), profile(horn_safe), provenance(...)). ``` The compiler can then map that closed representation into a trusted generic Datalog evaluator or generated private reasoner code. ## 2. Semi-naive materialization For repeated/broad queries, use delta fixpoint semantics: ```text I0 = base facts Δ1 = rules(I0) I1 = I0 ∪ Δ1 Δ2 = only consequences involving Δ1 ... ``` This avoids recomputing old consequences at each recursive iteration. Materializations are indexed by: ```text theory version profile version rule-set fingerprint base semantic generation ``` They are caches, never historical truth. ## 3. Magic/demand transformation For narrow queries over large rule sets, transform evaluation so bottom-up reasoning follows top-down demand. Example: ```text query: responsible_for(alice, What) ``` should not materialize `responsible_for/2` for every entity in years of ingested logs. The plan records the demand transformation and its query binding pattern, making it reproducible/explainable. This is one of the most important scaling ideas for Machine Spirit: **symbolic attention can begin at the deductive compiler**, before later retrieval/model projection. ## 4. Tabled evaluation for recursive/demand-heavy components Use tabling where query-directed recursion is natural. On SWI, tabling already provides a mature primitive and incremental tabling provides dependency-driven invalidation. Crucial abstraction: ```text semantic dependency graph ↓ compile runtime dependency/table graph ``` Do not expose SWI's table identifiers as canonical knowledge IDs. They are an implementation detail of one backend. ## 5. Incremental invalidation Every derived answer/materialization should depend on canonical semantic generations/edges. When an assertion, theory mapping, bridge, rule, or lifecycle status changes: ```text append semantic event ↓ identify affected dependency nodes ↓ invalidate derived tables/materializations ↓ recompute lazily or eagerly according to plan/profile ``` SWI's Incremental Dependency Graph is direct evidence that this pattern is practical for tabled logic programming: updated dynamic predicates mark dependent tables invalid and re-evaluation occurs on demand. The public contract should remain backend-neutral: ```prolog semantic_invalidate(+SemanticDelta, +State0, -State). semantic_refresh(+QueryOrView, +Options, -Outcome). ``` ## 6. Constraint profiles are solver calls, not ordinary predicates `CLP(FD)`, `CLP(Q/R)`, temporal interval constraints, unit/dimension constraints, etc. should compile into explicit trusted solver nodes. Example plan node: ```prolog solver_call( clp_fd, constraints([...closed validated expressions...]), inputs([...]), outputs([...])). ``` Never turn an arbitrary semantic expression into a Prolog callable term. ## 7. CHR as a trusted extension profile, not the universal rule language CHR is attractive for: - constraint propagation; - normalization; - solver implementation; - equivalence/simplification rules; - incremental constraint stores. But CHR has operational semantics (simplification/propagation/simpagation) distinct from Horn entailment. Therefore define an optional trusted `chr_constraint` profile whose programs/extensions are host-admitted/versioned. Do not compile arbitrary natural-language rules directly into unrestricted CHR. ## 8. Validation compiles separately Schema/shape checking should have its own validation plan: ```text Candidate IR -> shape/type/signature validator -> ValidationReport -> admitted semantic package ``` Validation failures are evidence; they do not mutate the candidate or silently repair it. A later repair/compiler pass may propose corrected IR. ## 9. Explanations piggyback on evaluation Every successful derived result should optionally emit a compact derivation receipt: ```prolog derivation_receipt( ResultAssertion, plan(PlanFingerprint), rule_apps([...]), premise_refs([...]), theory_edges([...]), solver_receipts([...]), semantic_generation(...)). ``` Do not duplicate full proof trees when common subderivations exist. Store/reference a justification DAG/hypergraph. For hot ephemeral queries the proof structure may remain transient; promoted conclusions and action-relevant VERIFY evidence should retain replayable receipts. ## 10. Derived state has typed freshness A materialized fact needs status equivalent to: ```text fresh built from current admitted generations invalid a dependency changed refreshing recomputation underway stale_read explicitly allowed stale snapshot unavailable reasoner/backend unavailable ``` No stale cached inference may silently masquerade as current truth. ## Execution strategy selector The compiler can use deterministic heuristics/profile metadata rather than an LLM: ```text small ground lookup -> indexed direct lookup narrow recursive Horn query -> tabled/demand evaluation broad repeated Horn closure -> semi-naive materialization large narrow bottom-up Datalog query -> magic-set/demand transform finite-domain arithmetic -> CLP(FD) rational/real symbolic arithmetic -> CLP(Q/R) trusted constraint-rewrite theory -> CHR profile unsupported quantified FOL -> structural/preservation query only ``` The choice and reason are included in the plan receipt. ## Query planning and cross-theory composition Subpass C's theory graph is used before rule execution: ```text query -> resolve query signature -> select candidate theory modules -> traverse admitted theory edges -> compute compatible profile composition -> normalize rules/facts into plan-local namespace -> choose evaluation strategy -> execute ``` The runtime **never** unions the entire durable KB first. ## Performance model / complexity honesty Each semantic profile declares known complexity/termination properties where possible. The plan may reject or bound a query whose requested composition escapes supported guarantees. Examples: - positive function-free Datalog: finite least fixpoint; - stratified negation: only when explicitly admitted by later epistemic semantics; - unrestricted FOL: preservation/structural query, no generic termination promise; - existential rules: only admitted bounded/decidable fragments; - constraints: complexity delegated to declared trusted solver profile; - cross-profile composition: guarantees apply only under declared compatibility contract. Do not turn a timeout into `unknown=false`; report `resource_exhausted`/`unsupported` separately from logical unknown. ## Machine Spirit scaling consequences For millions of semantic records: 1. canonical store remains append-only/indexed; 2. hot theory/profile materializations are selective; 3. query demand narrows theories before execution; 4. magic/demand transformations prevent irrelevant recursive closure; 5. incremental dependency invalidation avoids global rebuilds; 6. model prompts receive only post-reasoning bounded projections when a model is needed; 7. known tasks execute entirely through the symbolic plan. ## Safety / authority consequences - Deductive plan compilation grants no execution authority. - Semantic action `restart(service)` can be reasoned about as data but cannot invoke a tool. - Solver backends are allowlisted profile implementations. - Generated private Prolog code, if used as an optimization, is produced only from validated closed IR and loaded into a confined trusted module; its fingerprint is tied to the plan and source semantic generation. - No source/model-supplied predicate name is resolved to arbitrary host code. - Resource ceilings (time, inference steps, memory, table size) are runtime limits, not monetary/model budget charges. ## Adversarial fixtures 1. Recursive graph theory with 10^6 unrelated nodes; narrow query must avoid whole closure. 2. Add one base assertion; only dependent tables/materializations invalidate. 3. Retract/supersede a theory bridge; conclusions depending on it become invalid while unrelated tables remain fresh. 4. Constraint expression tries to name `shell/1`; validator keeps it inert/unsupported. 5. Recursive rule loop terminates through tabling/fixpoint in admitted profile. 6. Unsupported FOL formula remains representable but planner refuses executable lowering. 7. Re-run same query/semantic generation produces same plan fingerprint and equivalent result set. 8. Full derivation explanation reconstructs source assertions + theory mappings + rules + solver evidence. 9. Timeout/resource ceiling yields structured `resource_exhausted`, not semantic false/unknown. 10. Model/provider disabled: a fully known Horn+constraint task still succeeds end-to-end. ## Canonical recommendations 1. **#392:** preserve the three-plane distinction: canonical semantic records != compiled deductive plan != derived materialization. 2. **#394:** add an explicit plan compilation boundary and backend-neutral evaluation strategy contract; exact negation/default/conflict semantics still belong there/#400. 3. **#396:** `semantic_projection` should be able to consume/query a prepared symbolic plan and expose its bounded dependency/theory slice rather than selecting context only by heuristic relevance. 4. **#381 retrieval:** deductive demand should become one retrieval signal; a logical query can identify exactly which predicates/theories are relevant before embeddings are consulted. 5. **symbolic-memory #6:** derived materializations are rebuildable caches keyed by semantic generation; canonical append-only semantics remain authoritative. 6. **#384 VERIFY expert:** verification should accept derivation receipts as evidence but independently check required acceptance predicates rather than trusting a cached `success` label. ## Rejected alternatives - direct semantic-IR -> arbitrary Prolog clauses as canonical representation; - full closure materialization of all theories by default; - pure top-down SLD without tabling/dependency tracking; - embedding all constraint semantics into Horn rules; - unrestricted model-generated CHR programs; - storing every intermediate proof tree durably; - treating cached/materialized inference as immutable truth; - using an LLM to choose an evaluation strategy when deterministic profile/query metadata suffice. ## Depth-1 final architecture after A/B/C/D ```text EXACT SOURCE EVIDENCE ↓ VERSIONED SEMANTIC KERNEL terms / formulas / propositions / assertions ↓ CONTEXTS + THEORIES witnesses / validity / stance ↓ MODULAR THEORY GRAPH signatures / mappings / bridges / contracts ↓ JUSTIFICATION HYPERGRAPH ↓ REASONING PROFILE LATTICE ↓ DEDUCTIVE PLAN COMPILER theory slice / demand / rules / solvers ↓ HYBRID SYMBOLIC EXECUTION BACKENDS Datalog | tabling | materialization | CLP | CHR ↓ REBUILDABLE DERIVED WORLD VIEWS ↓ bounded projection / expert / conversation ``` This completes the **four-subpass KR-foundations depth**. It is still design/research evidence, not Machine Spirit acceptance. #399 should now attack whether language can be compiled into this architecture with acceptable semantic fidelity.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
nsaspy/prolog-rlm#400
No description provided.