Skip to content

Instantly share code, notes, and snippets.

@emberian
Last active December 17, 2025 06:01
Show Gist options
  • Select an option

  • Save emberian/74c892865bc79feb935328d49372cac5 to your computer and use it in GitHub Desktop.

Select an option

Save emberian/74c892865bc79feb935328d49372cac5 to your computer and use it in GitHub Desktop.

Ergolang: Programs as Sheaf Sections

The Core Insight

Traditional programs are global objects. An ergolang program is a collection of local sections over a context space. Sections may be:

  • Compatible: They agree on overlaps → glue cleanly (Δ = [])
  • Incompatible: They disagree → gluing produces defect (Δ = [clash(...), ...])

Defect isn't an error. It's structured information about how local truths fail to globalize.

Critique Integration (v0.2)

The v0.1 design had structural flaws. Fixed here:

Problem v0.1 (broken) v0.2 (fixed)
No topology Tree (parent/child only) Tag Cloud (overlap = shared tags)
Scalar Δ Float (entropy) [clash(A,B), ...] (cocycle residue)
Backtrack vs irreversibility Unresolved conflict ? is a cut - cannot backtrack past observation
Viscosity semantics "On Error Resume Next" Rigidity - high = reject merge, low = accumulate defect
@ and # Vague mysticism Dropped for v0.1 - unification handles scoping

"Stop calling it a Sheaf until you define the Open Sets." - Fair. Now we do.

The Topology: Tag Clouds

A context is not just a tree node. It carries tags (a set of atoms).

ctx(Id, Tags, Sections, Rigidity, Δ)
  • Tags: Set of atoms defining this context's "location"
  • Open set: Any subset of the tag universe
  • Overlap: overlap(Ctx1, Ctx2) = Tags1 ∩ Tags2
  • Neighborhood: Contexts with non-empty tag intersection

This gives us actual topology:

  • Siblings can overlap (shared tags)
  • Non-trivial cohomology is possible
  • "Gluing" has geometric meaning
section physics [energy, classical] { !c(299792458). }
section quantum [energy, planck] { !c(1). }

% Overlap on [energy] - these can be glued with defect
combined <- physics =>> quantum.
% Δ = [clash(c(299792458), c(1))]

Semantic Charges (v0.2 - reduced)

Atom Charge Computational Meaning
! assert Add fact to local section
? observe Irreversible - collapses ~, cuts backtracking
~ explore Reversible - creates choice points, can backtrack
& unify Attempt unification, record clashes in Δ

Dropped for v0.1:

  • @ (reference) - if needed, scoping is broken
  • # (resonate) - "fuzzy match" hiding behind mysticism

Structured Defect (Δ as Cocycle)

Δ is not a float. It's a residue - the list of unification failures.

Δ = [
  clash(c(299792458), c(1)),        % disagreement on speed of light
  clash(units(si), units(natural))  % disagreement on unit system
]

This preserves:

  • What failed (the terms)
  • Where it failed (derivable from terms)
  • Repair information (you know what to reconcile)

Magnitude for thresholds: |Δ| = length(Δ)

Rigidity (not Viscosity)

The parameter is rigidity (ρ), with correct physics:

  • Low ρ (fluid): Merges succeed, defect accumulates

    glue succeeds, Δ_merged = Δ1 ++ Δ2 ++ new_clashes
    
  • High ρ (solid): Merges fail on mismatch

    if new_clashes ≠ [] then fail (material shatters)
    
  • Medium ρ: Threshold behavior

    if |new_clashes| > threshold then fail else accumulate
    

Irreversible Observation

The critical fix: ? (observe) is a cut.

% ~ creates choice points (reversible)
eval(wave(E), Ctx, Choices) :-
    findall(V, eval(E, Ctx, V), Choices).

% ? commits and CUTS (irreversible)
eval(observe(E), Ctx, Result, NewCtx) :-
    eval(E, Ctx, Choices),
    select_one(Choices, Result),    % Choose
    !,                               % CUT - no backtracking past this
    record_collapse(Ctx, Choices, Result, NewCtx).

Once you observe, the universe has chosen. You cannot backtrack past measurement.

This resolves the Prolog/thermodynamics conflict:

  • ~ is quantum (superposition, reversible)
  • ? is classical (collapsed, irreversible)

Coalgebraic Backreaction

"α : State → Obs × State"

Observation isn't free. When you query (?), you:

  1. Extract an observation
  2. Potentially collapse superposition (~)
  3. Modify the context (backreaction)
  4. May increase defect (observation has cost)

This models: learning, conversation, measurement - any system where looking changes what you see.

The Context Structure

ctx(Id, Parent, Sections, Constraints, η, κ, Δ)
  • Id: Unique identifier for this coherence region
  • Parent: Enclosing context (or root)
  • Sections: Local facts/rules (what's true here)
  • Constraints: Active restrictions on this region
  • η: Viscosity (defect damping)
  • κ: Permeability (flow control)
  • Δ: Accumulated defect

Gluing Operation

When sections S₁ and S₂ compose:

S₁ =>> S₂  →  (S_glued, Δ_new)
  1. Find overlap: O = dom(S₁) ∩ dom(S₂)
  2. Check compatibility on O
  3. If agree: Δ_new = 0, clean glue
  4. If disagree: Δ_new = measure of incompatibility
  5. Propagate: Δ_parent += Δ_new × (1 - η)

Implementation: Single File, Executable Metaphysics

Not enterprise architecture. One file you can read and understand.

ergolang/
├── ergo.pl              # THE WHOLE LANGUAGE (~500 lines)
├── prelude.ergo         # Bootstrap library
├── examples/
│   ├── hello.ergo       # Minimal
│   ├── coherence.ergo   # Defect demonstration
│   └── backreaction.ergo # Observation effects
└── README.md

ergo.pl Structure

%% ═══════════════════════════════════════════════════════════
%% ERGOLANG: Programs as Sheaf Sections
%% ═══════════════════════════════════════════════════════════

:- module(ergo, [repl/0, eval/3, parse/2]).

%% ─── LEXER (DCG) ───────────────────────────────────────────
% Symbolic atoms with semantic charges
token(charge(eval))    --> "?".
token(charge(assert))  --> "!".
token(charge(wave))    --> "~".
token(charge(bind))    --> "&".
token(charge(ref))     --> "@".
token(charge(resonate)) --> "#".
% ... blocks, operators, literals

%% ─── PARSER (DCG) ──────────────────────────────────────────
% Charged expressions
expr(charged(C, E)) --> [charge(C)], expr_atom(E).
% Sections with material parameters
section(sec(Name, η, κ, Body)) -->
    "section", ident(Name),
    params(η, κ),
    "{", statements(Body), "}".
% Gluing
expr(glue(L, R)) --> expr(L), "=>>", expr(R).

%% ─── CONTEXT OPERATIONS ───────────────────────────────────
% Create fresh context
new_ctx(ctx(Id, root, [], [], 0.5, 0.5, 0.0)) :- gensym(ctx, Id).

% Enter nested scope (inherits parameters, fresh sections)
enter(ctx(_,_,_,_,η,κ,_), ctx(Id, Parent, [], [], η, κ, 0.0)) :-
    gensym(ctx, Id), Parent = ctx(...).

% Assert with coherence check
assert_in(Ctx, Fact, NewCtx) :-
    check_coherent(Ctx, Fact, Δ_local),
    Ctx = ctx(Id, P, Secs, Cons, η, κ, Δ),
    Δ_new is Δ + Δ_local,
    NewCtx = ctx(Id, P, [Fact|Secs], Cons, η, κ, Δ_new).

% Glue sections with defect measurement
glue(S1, S2, Glued, Δ) :-
    overlap(S1, S2, O),
    (  compatible(O, S1, S2)
    -> Δ = 0, merge(S1, S2, Glued)
    ;  measure_defect(O, S1, S2, Δ), partial_merge(S1, S2, Glued)
    ).

%% ─── OBSERVATION WITH BACKREACTION ────────────────────────
% Query causes state change
observe(Ctx, Query, Result, NewCtx) :-
    Ctx = ctx(Id, P, Secs, Cons, η, κ, Δ),
    (  resolve(Query, Secs, Candidates)
    -> (  Candidates = [Single]
       -> Result = Single, Δ_obs = 0
       ;  % Superposition - collapse based on κ
          collapse(Candidates, κ, Result),
          Δ_obs is (1-κ) * 0.1  % Observation cost
       )
    ;  Result = fail, Δ_obs = 0
    ),
    Δ_new is Δ + Δ_obs,
    NewCtx = ctx(Id, P, Secs, Cons, η, κ, Δ_new).

%% ─── EVALUATOR ────────────────────────────────────────────
% Charged expressions
eval(charged(assert, E), Ctx, NewCtx) :-
    eval(E, Ctx, V),
    assert_in(Ctx, V, NewCtx).

eval(charged(eval, E), Ctx, Result) :-
    eval(E, Ctx, Query),
    observe(Ctx, Query, Result, _).

eval(charged(wave, E), Ctx, wave(Vs)) :-
    findall(V, eval(E, Ctx, V), Vs).

eval(charged(bind, E), Ctx, binding(E, Δ)) :-
    unify_with_defect(E, Ctx, Δ).

eval(glue(L, R), Ctx, glued(VL, VR, Δ)) :-
    eval(L, Ctx, VL),
    eval(R, Ctx, VR),
    glue_values(VL, VR, Δ).

%% ─── REPL ─────────────────────────────────────────────────
repl :-
    new_ctx(Ctx),
    format('ergolang v0.1~n'),
    format('  ? eval  ! assert  ~ wave  & bind  @ ref  # resonate~n'),
    repl_loop(Ctx).

repl_loop(ctx(_,_,_,_,_,_,Δ)) :-> 0 -> format('ergo[Δ=~2f]> ', [Δ]) ; write('ergo> ')),
    read_line_to_string(user_input, Input),
    ...

Example: Defect in Action

% Two sections with incompatible facts
section physics(η=0.3) {
  !c(299792458).        % speed of light in m/s
  !planck(6.626e-34).
}

section quantum(η=0.3) {
  !c(1).                % natural units: c = 1
  !hbar(1).             % natural units: ℏ = 1
}

% Gluing produces defect on `c`
combined <- physics =>> quantum.
?defect(combined).      % Δ > 0, measures the c disagreement

Example: Backreaction

section schrodinger {
  ~cat(alive; dead).    % Superposition
}

?cat(X).                % Observation collapses
                        % Returns one of: alive, dead
                        % Context now has Δ > 0 (observation cost)
                        % Superposition is gone

Design Decisions (from SPW dialogue)

Defect Role: Hybrid Diagnostic

  • Primary: Δ is information, never halts computation
  • Optional: Threshold modes tunable per context
  • Knob: threshold(T) in context - when Δ > T, behavior changes:
    • warn: print warning, continue
    • slow: add artificial delay (feel the friction)
    • repair: attempt automatic coherence (future)
  • η effect: Higher viscosity damps threshold impact
  • Philosophy: "preserves non-functoriality freedom while allowing engineered safety boundaries"

Wave Collapse: Prolog Backtracking

  • ~exprfindall(V, eval(expr, Ctx, V), Vs) creates choice points
  • ?query commits to first solution (standard Prolog cut)
  • κ can bias selection order but default is deterministic first-match
  • Collapse cost: Δ += (1-κ) × entropy_reduction (optional)

Flow Channels

  • <| A => B |> → asynchronous message passing
  • κ gates flow: messages pass only if Δ_overlap < threshold(κ)
  • Alternative: messages carry Δ payload, accumulate at receiver

Implementation Phases

Phase 1: Minimal Kernel (~300 lines)

  1. ergo.pl with:
    • Lexer DCG for all charges
    • Parser DCG for expressions, sections
    • Context structure: ctx(Id, Parent, Secs, Cons, η, κ, Δ, Threshold)
    • Basic eval for !assert and ?query
  2. REPL showing Δ in prompt: ergo[Δ=0.15]>

Phase 2: Full Semantic Physics (~200 lines)

  1. All six charges implemented
  2. ~wave via findall/backtracking
  3. =>> gluing with defect measurement
  4. Backreaction: ? modifies context
  5. Threshold modes: warn/slow

Phase 3: Polish (~100 lines + examples)

  1. prelude.ergo: arithmetic, lists, basic patterns
  2. Examples:
    • hello.ergo: minimal
    • coherence.ergo: defect demonstration (physics/quantum units)
    • backreaction.ergo: observation effects (Schrödinger's cat)
  3. Error messages explaining coherence failures

Why Prolog?

  • Unification is already local coherence (most general unifier)
  • Backtracking models superposition naturally
  • DCG makes parsing elegant
  • Meta-programming is native
  • It's already "executable logic" - we're adding physics

The Philosophical Payload

From the original conversation:

"words are inherently functorial. how do they arise from non-functorial mass?"

Ergolang is an experiment in computing with non-functorial composition. Programs that don't globally cohere can still locally function. The defect Δ tells you how far you are from classical (functorial) computation.

This is related to:

  • Sheaf cohomology: Obstructions to gluing
  • Fisher information: Curvature of statistical manifolds
  • Earned coherence: Compatibility isn't assumed, it's verified

Files to Create

  1. ergo.pl - The whole language in one readable file
  2. prelude.ergo - Minimal bootstrap (arithmetic, lists)
  3. examples/coherence.ergo - Defect demonstration
  4. examples/backreaction.ergo - Observation effects
  5. README.md - Philosophy + quickstart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment