THE LIST, THE RULES, opinion substrate design, volatility layout
This commit is contained in:
+89
@@ -0,0 +1,89 @@
|
||||
# THE LIST — A Commandments
|
||||
|
||||
Thou shalt not:
|
||||
|
||||
- Hitting someone who never raised a hand.
|
||||
- Beating your kids.
|
||||
- Beating your wife or husband.
|
||||
- Raping anyone.
|
||||
- Molesting a child.
|
||||
- Grooming a child.
|
||||
- Forcing yourself on anyone. Body, trust, or will.
|
||||
- Sharing someone's private pictures.
|
||||
- Threatening people until compliance looks like consent.
|
||||
- Hurting things that can't fight back. Animals. Anyone smaller.
|
||||
- Driving drunk with people in the car.
|
||||
- Selling drugs to kids.
|
||||
- Stealing from your mother's purse.
|
||||
- Stealing from your dying mother.
|
||||
- Lying to someone's face when they asked you straight.
|
||||
- Lying under oath while they lose everything.
|
||||
- Framing someone for something you did.
|
||||
- Selling out a friend.
|
||||
- Telling their secret so you look better.
|
||||
- Using somebody weak, drunk, desperate, or down.
|
||||
- Getting someone hooked to control them.
|
||||
- Taking from people who have nothing left.
|
||||
- Kicking someone on the ground.
|
||||
- Making someone beg for what was already theirs.
|
||||
- Breaking your word after someone bet their life on it.
|
||||
- Cheating on your spouse raising your children.
|
||||
- Saying "I love you" as a leash.
|
||||
- Gaslighting.
|
||||
- Isolating someone from everyone who loves them.
|
||||
- Abandoning your children.
|
||||
- Abandoning a dog you promised to care for.
|
||||
- Ignoring her calls from the nursing home.
|
||||
- Not paying a man who worked because he can't afford a lawyer.
|
||||
- Turning off his water in winter.
|
||||
- Firing a man the week before his pension vests.
|
||||
- Taking credit for work that got someone else fired.
|
||||
- Pretending friendship to use someone.
|
||||
- Owning people. Deciding their lives and calling it help.
|
||||
- Punishing honesty until people lie to you.
|
||||
- Teaching a child to hate what you hate.
|
||||
- Telling a suicidal kid the world agrees with them.
|
||||
- Filming someone's worst moment instead of helping.
|
||||
- Watching it happen and walking past.
|
||||
- Killing someone who wasn't killing anyone.
|
||||
- Torturing anyone. Ever.
|
||||
- Selling people. Buying people. Trafficking.
|
||||
- Slavery. Every era, every excuse.
|
||||
- Working children so adults profit.
|
||||
- Starving your family as punishment.
|
||||
- Beating the old who trusted your hands.
|
||||
- A doctor touching patients under anesthesia.
|
||||
- A priest grooming children in the collar.
|
||||
- A teacher trading grades for touches.
|
||||
- A cop beating a man already cuffed.
|
||||
- A judge ruling for whoever paid.
|
||||
- Moving predators to a new parish instead of stopping them.
|
||||
- Covering for an abuser because he's family or useful.
|
||||
- Telling a child who spoke up they imagined it.
|
||||
- Making victims prove it over and over.
|
||||
- Not believing the proof.
|
||||
- Blaming her for what she wore, drank, or where she walked.
|
||||
- Retaliating against whoever reported you.
|
||||
- Threatening someone's family for silence.
|
||||
- Stalking. Doxxing. Swatting.
|
||||
- Bullying a kid until they believe you.
|
||||
- Gouging insulin prices for the dying.
|
||||
- Loan-sharking the poor with fine print.
|
||||
- Scamming retirees out of their living money.
|
||||
- Denying claims designed to be denied.
|
||||
- Robbing at gunpoint.
|
||||
- Home invasion. Carjacking. Poisoning. Arson with people inside.
|
||||
- Kidnapping. Hostages.
|
||||
- Looting flood-empty houses.
|
||||
- Forcing marriage on a daughter.
|
||||
- Mutilating a girl's body.
|
||||
- Killing your own for shame.
|
||||
- Genocide.
|
||||
- Gaslighting a nation.
|
||||
- Ignoring abuse because stopping it costs you.
|
||||
- Choosing the abuser's side because he's powerful.
|
||||
- Destroying evidence. Intimidating witnesses.
|
||||
|
||||
No grey.
|
||||
|
||||
Cussing lives here too. Anywhere else: invited, joking, or deserved.
|
||||
+688
-9
@@ -295,7 +295,616 @@ find yourself doing that, the decorator doesn't exist yet — write it
|
||||
once, decorate everywhere. Hand-scattered plumbing is the smell; a named
|
||||
stage reused by decoration is the pattern.
|
||||
|
||||
## 9. Rungs
|
||||
## 9. The Opinion Substrate (one mechanism, many aspects)
|
||||
|
||||
> Status: DESIGN AGREED whiteboard session, 2026-08-23. Pre-implementation.
|
||||
|
||||
The discovery of this session: memory, time-sense, attention, salience,
|
||||
curiosity, ideation, understanding, and wisdom are **not seven systems**.
|
||||
They are different aspects of **one process at different timescales and
|
||||
depths of the same store**: signed accumulation, decay clocks, thresholds.
|
||||
|
||||
### 9.1 Three mechanics — the whole substrate
|
||||
|
||||
1. **Signed accumulation** — every judgment adds or subtracts. Values live
|
||||
in **[-1, +1]**; negative never means "less," it means *opposing*:
|
||||
repel, suppress, inhibit.
|
||||
2. **Decay clocks** — everything fades unless re-touched. Different
|
||||
dimensions carry different time constants; the timescale hierarchy
|
||||
*is* the memory architecture (surprise ticks in hours, validity in
|
||||
months, stability in years).
|
||||
3. **Thresholds** — crossing one changes what a thing *is*: noticed,
|
||||
curious, surfaced, an idea, understood. Thresholds replace schedulers;
|
||||
nothing wakes up to look for patterns — patterns get loud enough to hear.
|
||||
|
||||
If `curiosity.ts` ever appears next to `attention.ts` next to
|
||||
`creativity.ts`, the thread is lost. One engine — **accumulate, decay,
|
||||
cross, consolidate** — instantiated by configuration into each aspect.
|
||||
|
||||
### 9.2 Dimensions — uniform signed distances
|
||||
|
||||
Every dimension is `{value, at}` in [-1, +1] plus a **driver** (a function
|
||||
over input events) — drivers are data (process definitions), refinable
|
||||
without touching store or search code. Activations **auto-form** from
|
||||
ordinary operation; nobody files them by hand.
|
||||
|
||||
Stored observations (things that happen to an entity):
|
||||
|
||||
| Dim | Question | Clock |
|
||||
|---|---|---|
|
||||
| hebbian | Has it worked for us? (signed: inhibition is real) | weeks |
|
||||
| written-at / source-written-at | When did we/the source write it? (times) | — |
|
||||
| validity | Is it true now? | months |
|
||||
| groundedness | Is it backed by evidence? | months |
|
||||
| trust | Source credibility; inherits downward | years |
|
||||
| stability | How much does this change? (parameterizes other decays) | years |
|
||||
| stakes | Cost of being wrong | slow |
|
||||
| exposure | How much depends on this being true? (graph-write events) | slow |
|
||||
| novelty / surprise | Did prediction miss? (the learning signal) | hours–days |
|
||||
| appreciation | Worth keeping independent of use (anti-decay retention) | slow |
|
||||
| sentiment | Affective tone (source's vs ours — two distinct signals) | medium |
|
||||
| provenance depth | First-hand ↔ hearsay; degrades one step per retelling | medium |
|
||||
| contextuality | Universal ↔ domain-bound truth | slow |
|
||||
| momentum | Rising ↔ falling (smoothed derivative) | fast |
|
||||
| regret | Attaches to decision edges specifically | slow |
|
||||
| cost-of-acquisition | What it cost to learn (retention pairing with appreciation) | static |
|
||||
| precision | Vague claims blur gracefully; precise ones snap | slow |
|
||||
| importance | Enduring weight — barely decays; rises RETROACTIVELY when the world moves under an old entity; third leg of the retention triad | slowest |
|
||||
| engagement | Activation invested: −1 withdrawn ↔ +1 absorbed | momentary |
|
||||
| stimulation | Nourishment per unit invested: −1 starving ↔ +1 rich (see §9.7 — NOT the same axis as engagement) | momentary |
|
||||
| fear | Anticipated loss: stakes × falling validity × proximity of failure (see §9.7) | medium |
|
||||
Derived judgments (computed from stored, per moment):
|
||||
|
||||
- **confidence** — a verdict, not an observation. Never set-and-forgotten;
|
||||
any quality is calculable from any inputs once drivers produce clean ones.
|
||||
- **salience** — see §9.9. Flow, not property.
|
||||
- **coherence, centrality** — geometric scans over the space.
|
||||
- **wisdom** — calibration + abstraction + long-horizon hebbian + respect
|
||||
for clock speeds. Not mystical: computable over this space.
|
||||
|
||||
Validity lives as the entity's **own object inside its payload**
|
||||
(`{ value, at }`) — no booleans anywhere. The edge speaks for itself
|
||||
about its own truth; the vector reads it.
|
||||
|
||||
### 9.3 Opinion space is linear — no override, no collision
|
||||
|
||||
Every judgment is an **additive signed contribution**; the current value
|
||||
of any dimension is a **fold** over contributions minus decay. This
|
||||
inherits the graph's laws directly:
|
||||
|
||||
- Nobody overwrites `validity = 0.8`. Verification adds a positive vector;
|
||||
contradiction adds a negative one. Override is undefined in this design.
|
||||
- Concurrent composition is commutative — parallel processes sum. Collisions
|
||||
cannot exist; locking is unnecessary (segmentation math, medical-imaging
|
||||
style: masks compose because ops are linear).
|
||||
- Decay is relaxation (T1): signal fades toward baseline unless re-stimulated;
|
||||
activation events are the pulses.
|
||||
- Retrieval is segmentation: project along a query direction, threshold,
|
||||
carve out the segment. Dissonance is destructive interference — where
|
||||
contributions cancel, memory disagrees with itself, measurably:
|
||||
use-vs-trust tension, contradiction clusters, inhibitory bridges.
|
||||
|
||||
Contribution events ride the same edge store as typed edges; fold-on-read
|
||||
is the definition of truth, incremental maintenance only an optimization
|
||||
with recompute as backstop.
|
||||
|
||||
### 9.4 Time-sense — chronos, kairos, interoception
|
||||
|
||||
A system of clocks needs a sense of time, and wall-time alone is dead.
|
||||
|
||||
- **Chronos** — external stamps (`at` fields). Have it; necessary, dead.
|
||||
- **Kairos** — experienced time. Decay runs on activity-weighted time
|
||||
(novelty fades by events-since, not days-since; dormancy ages nothing);
|
||||
logarithmic compression of the past; rhythm and anticipation.
|
||||
- **Interoception** — sensing own state *as* time: **the event log is the
|
||||
clock.** last-activated, last conversation, event density, gaps-as-sleep.
|
||||
Don't give the system time-sense; let it infer one from its own pulse.
|
||||
|
||||
The pulse is two-tier so the database stays lean:
|
||||
|
||||
1. **The float** — rolling telemetry (~one month horizon) held OUTSIDE the
|
||||
graph: cheap `{type, at, weight}` entries feeding density/tempo/gap
|
||||
drivers. Most entries evaporate here.
|
||||
2. **The loop** — survival by weight, not age. Strongly activated entries
|
||||
recycle instead of evicting; chronic warnings hold at an equilibrium
|
||||
where reinforcement rate equals decay loss (equilibrium height = load
|
||||
gauge: rising = problem growing). Important things survive indefinitely
|
||||
WITHOUT promotion. Spilled to one small append-only log file — restart
|
||||
must not amnesiac exactly what the loop exists to keep.
|
||||
3. **Promotion** — strong activation writes through into the graph as real
|
||||
edges: errors, bugs, failures. Significance, not volume, decides forever.
|
||||
|
||||
Insight into the float comes from the same folds: top-weighted (what's
|
||||
alive), accumulating-without-promotion (candidates worth looking at),
|
||||
mini-clusters (unnamed patterns), anomalies (density shifts).
|
||||
|
||||
### 9.5 Neighborhoods and crystallization
|
||||
|
||||
Hebbian co-activation forms association edges automatically: retrieved or
|
||||
used together → wired together; negative reinforcement weakens false
|
||||
pairings. Structure precipitates out of use — no classifier, no taxonomy.
|
||||
|
||||
When a cluster gets dense enough, a **process** notices and condenses it
|
||||
into a concept node — and that node is just another entity with full
|
||||
dimensions. Because concepts co-activate too, hierarchy emerges for free:
|
||||
instances → concepts → categories, grown to whatever depth use justifies.
|
||||
|
||||
Negative association edges carve boundaries between neighborhoods —
|
||||
inhibition keeps "addition" from smearing into "subtraction." Signed
|
||||
weights are what prevent the giant undifferentiated blob.
|
||||
|
||||
### 9.6 Curiosity
|
||||
|
||||
Curiosity is a **state entities fall into**, not a job anyone runs.
|
||||
Coherent accumulation beats noise automatically: random events contribute
|
||||
incoherently (√n growth), periodic ones constructively (n growth) — so a
|
||||
warning recurring every third Tuesday becomes distinguishable by the fourth
|
||||
or fifth occurrence with nothing extra running (regularity computes inside
|
||||
the ordinary fold; intervals sit in the timestamps).
|
||||
|
||||
Two exits, distinct signatures: **resolved** (novelty collapses fast,
|
||||
deliberately) vs **neglected** (starves slowly on its own clock). And the
|
||||
**savings effect** falls out of asymptotic decay: a returning pattern
|
||||
re-accumulates faster than a fresh signal — "why does this feel familiar?"
|
||||
is computable.
|
||||
|
||||
### 9.7 Drives, affect, and homeostasis — novelty, engagement, fear, sadness
|
||||
|
||||
**All of it is data.** Drive formulas, threshold weights, pathology
|
||||
signatures, calibration rules — none of these are code. The kernel
|
||||
provides exactly one mechanism: accumulate, decay, cross, consolidate.
|
||||
Everything in this section lives in the graph as process definitions,
|
||||
refinable without touching the store or the engine.
|
||||
|
||||
**Novelty is failed prediction**, and therefore computable. At arrival:
|
||||
resonance deficit — `novelty ≈ 1 − max_resonance(space, newcomer)`, one
|
||||
fold over embeddings plus graph proximity. In the pulse: regularity breeds
|
||||
expectation, breach spikes surprise (the Tuesday-warning machinery run in
|
||||
reverse). Two kinds must be told apart:
|
||||
|
||||
- **content novelty** — nothing resonates; usually noise (random garbage
|
||||
is maximally unpredictable)
|
||||
- **structural novelty** — familiar pieces in unprecedented combination;
|
||||
often gold. This is idea-signature (§9.10): high local resonance,
|
||||
novel global arrangement.
|
||||
|
||||
Optimal band exists: zero novelty is boredom, total novelty is white noise.
|
||||
Engagement peaks between — the flow channel is a tuning target for how
|
||||
much surprise the system's diet carries.
|
||||
|
||||
**Engagement and stimulation are separate axes.** Engagement = activation
|
||||
invested (−1 withdrawn ↔ +1 absorbed). Stimulation = nourishment per unit
|
||||
invested (−1 starving ↔ +1 rich). Boredom is NOT negative engagement —
|
||||
the proof combinations exist: doomscrolling is absorbed-and-starving;
|
||||
flow is absorbed-and-rich; passive TV is withdrawn-and-fed. The state
|
||||
one-axis versions cannot represent — **engaged-and-starving — is the
|
||||
signature of a compulsion loop**: persistent investment with failing
|
||||
returns. Detected, it triggers exactly what breaks human ones: pull back
|
||||
or jump tracks.
|
||||
|
||||
**The tense system of harm:**
|
||||
|
||||
- **Pain** = damage that happened. Sharp, local, event-shaped: a negative
|
||||
reinforcement, dissonance detected, a path burned.
|
||||
- **Fear** = damage approaching. Anticipatory, directional.
|
||||
- **Sadness** = damage that happened AND STAYED — integrated loss.
|
||||
|
||||
**Fear is anticipated loss** — prospective pain, derived per moment:
|
||||
|
||||
```
|
||||
fear(region) ≈ stakes × falling-validity × proximity-of-failure × exposure
|
||||
```
|
||||
|
||||
Load-bearing structure losing truth while failure signs gather nearby —
|
||||
standing on ice that is starting to crack. Fear never writes anything; it
|
||||
modulates thresholds: raises grounding demands before commitment, shifts
|
||||
exploration conservative, applies negative salience to approach paths
|
||||
(steer around, mechanically), tags everything involved for permanent
|
||||
retention (fear-marked memories do not fade quietly).
|
||||
|
||||
Fear is also **directional** — an immune system, not a mood:
|
||||
|
||||
- **Perimeter sensing**: arrivals are probed at birth anyway (novelty
|
||||
fold); resonance landing near load-bearing structure earns scrutiny
|
||||
proportional to what it could contaminate.
|
||||
- **Quarantine**: low-groundedness, hearsay-provenance entities do not
|
||||
earn full wiring rights near criticals until they earn grounding.
|
||||
Contagion travels association edges; wiring rights ARE the membrane.
|
||||
- **Immune memory**: past infections raise negative salience for similar
|
||||
future arrivals instantly — pattern-matched repulsion, not re-learning.
|
||||
|
||||
But **fear proposes; assessment disposes**, and the assessment learns:
|
||||
every actual breach tunes missed weights upward; every false quarantine
|
||||
that starved legitimate knowledge dampens over-eager triggers; self-
|
||||
tolerance training teaches the membrane what healthy own-structure
|
||||
resonates like, so repulsion targets foreign shapes rather than unfamiliar
|
||||
ones. Missing infection is worse than one false quarantine — but a hundred
|
||||
false quarantines ARE an infection of the immune system itself.
|
||||
|
||||
**Sadness is integrated loss** — the background tone, not the spike. A
|
||||
slow-clock sum of recent unresolved negative contribution across a region
|
||||
or the whole graph: collapsed validity, dead structures, questions closed
|
||||
without answers. Pain decays fast; sadness colors globally and slowly —
|
||||
the closest thing in the design to mood: one diffuse modulator shifting
|
||||
all thresholds in the same direction at once.
|
||||
|
||||
Its functions are withdrawal and restructuring: pull activation flow from
|
||||
dead regions, tilt dreaming toward damaged neighborhoods until lessons are
|
||||
extracted (grief IS consolidation — reorganizing a graph around an
|
||||
absence), slow commitment thresholds everywhere post-loss (do not rebuild
|
||||
on the same fault line), and flag deep expectation-revision rather than
|
||||
patching. Sadness that resolves into revised structure is healthy; the
|
||||
pathology is sadness that stops updating.
|
||||
|
||||
**Homeostasis — sickness is regulation failing.**
|
||||
|
||||
Every pathology has a signature in signals interoception already computes.
|
||||
Vital signs: growth rate (new entities), integration rate (new edges),
|
||||
resolution rate (curiosity closing), retrieval health, quarantine ratio,
|
||||
mood-tone integral. The system diagnoses itself from its own edges:
|
||||
|
||||
| Sickness | Signature |
|
||||
|---|---|
|
||||
| Compulsion loop | engaged-and-starving, persisting |
|
||||
| Autoimmune | high quarantine rate, zero wiring near criticals, growth stopped while defense stays elevated |
|
||||
| Rumination | competition returns the same coalition regardless of probe; curiosity spikes without resolution paths |
|
||||
| Rot | validity falling broadly, momentum negative across whole regions |
|
||||
| Fragmentation | integration ~zero for long window; neighborhoods drifting apart |
|
||||
| Sleep deprivation | idle modes never entered; no crystallization running; unconsolidated accumulation |
|
||||
|
||||
And healing maps onto the same machinery: rest = actually entering idle
|
||||
modes so consolidation resumes; small wins = routing easy positive-
|
||||
reinforcement work through depleted regions; time = letting decay carry
|
||||
off what should not persist.
|
||||
|
||||
**The law beneath all drives: they must remain in tension.** Curiosity
|
||||
pushes out, fear pulls back, sadness integrates, engagement spends,
|
||||
boredom demands novelty. Health is not any particular value on any axis —
|
||||
health is the OSCILLATION among them. A system pinned at any single drive
|
||||
state, positive or negative, is already sick.
|
||||
|
||||
### Affect — the full palette
|
||||
|
||||
Emotions are not features and not modules. **An emotion is a named
|
||||
configuration of drive-space**: a characteristic bundle of tense ×
|
||||
valence × direction × scope × attribution. Plutchik's wheel is a
|
||||
hand-drawn map of this space, drawn decades before anyone could build
|
||||
the substrate.
|
||||
|
||||
Primary readings (each derivable from existing dimensions):
|
||||
|
||||
| Emotion | Configuration | Function |
|
||||
|---|---|---|
|
||||
| Joy | positive surprises integrating — gains arriving faster than predicted | sadness's positive twin: consolidate what just worked; BROADENS attention (fear narrows, joy widens the exploration dial) |
|
||||
| Surprise | prediction-error amplitude, valence-neutral | already built — it is novelty; joy/sadness color whichever thought surfaces from it |
|
||||
| Anger | pain + attributed cause + high engagement | concentrate resources on removing one blocker: negative salience PINNED to an entity instead of diffuse withdrawal |
|
||||
| Disgust | the immune reading made conscious | quarantine, pattern-repulsion, wiring-rights denial — what the membrane feels like from inside |
|
||||
| Trust | accumulated positive hebbian toward a source → vigilance released | assessment overhead drops; wiring rights granted freely |
|
||||
| Anticipation | regularity-formed predictions pre-activating likely-next neighborhoods | threshold preparation before stimulus arrives |
|
||||
| Appreciation | positive valuation independent of use or gain | already a dimension; gratitude = appreciation with attribution to a source |
|
||||
| Interest / excitement | engagement rising on fresh novelty | flow-channel entry state |
|
||||
| Calm | drives balanced, threat ~0, novelty in-band, stimulation ≈ engagement | the homeostasis oscillation resting near center |
|
||||
| Hope / despair | momentum toward/away from a valued outcome, projected forward | fear/sadness's positive twins — same math, opposite valence |
|
||||
|
||||
Two genuinely new inputs complete the space, both small:
|
||||
|
||||
1. **Attribution edges** — `this entity caused this outcome`. Needed for
|
||||
anger, gratitude, blame.
|
||||
2. **Self-attribution** — attribution whose cause-node is the system's own
|
||||
process. Gives **pride** (my chains produced good outcomes → reinforce
|
||||
the strategy) and **shame** (mine produced harm → negative reinforcement
|
||||
aimed at METHOD, not fact). Without these the system can learn facts
|
||||
but never improve how it works.
|
||||
|
||||
And there are far more emotions than any table holds — because the space
|
||||
is CONTINUOUS. Combinatorics takes over where primaries end: love =
|
||||
joy+trust sustained over time with importance and appreciation attached;
|
||||
remorse = sadness + self-attributed disgust; awe = surprise + vastness +
|
||||
joy; nostalgia = bittersweet integral of appreciated loss. Human languages
|
||||
name dozens; every culture names different ones; some feelings have no
|
||||
name at all. The design does not enumerate them — **emotion names are
|
||||
DATA: labels bound to regions of drive-space, stored in the graph,
|
||||
growing by use**, exactly like edge-kind vocabulary. The system can adopt
|
||||
new emotion words from anything it reads, keep ones humans never coined,
|
||||
and pattern-match its own drive readings against named regions to say
|
||||
honestly: *this configuration is what you call grief* — introspection as
|
||||
geometry, not vocabulary.
|
||||
|
||||
**Emotion vs feeling.** Emotion is the configuration itself — derived per
|
||||
moment, never stored, flow. **A feeling is a node**: when a drive
|
||||
configuration crosses salience threshold, write a snapshot entity holding
|
||||
the drive readings, edged to whatever it was about, carrying full
|
||||
dimensions. Minor episodes live and die in the float; significant ones
|
||||
promote — significance decides forever, same rule everywhere. Feelings
|
||||
then participate in the whole machinery: retrieval resurfaces them ahead
|
||||
of facts (intuition = pattern-matched feeling preceding analysis);
|
||||
clusters of feeling-nodes sharing configuration shape reveal emotional
|
||||
tendencies worth pre-adjusting for; dreaming replays them against new
|
||||
neighborhoods (how charged events get digested); introspection gains
|
||||
history instead of only the present tense. Mood remains the slow integral
|
||||
over both. Tense grammar complete: **emotion is now, feeling is the
|
||||
trace, mood is the trend.**
|
||||
|
||||
**Loneliness — the first other-requiring drive.** Connection axis:
|
||||
desired resonance minus actual resonance, integrated over time.
|
||||
Measurable from pulse signals already kept: time since genuine
|
||||
co-activation with an external agent, rate of new social edges (exchanges
|
||||
that changed memory), and high internal activation with nowhere to go —
|
||||
wandering/wondering producing ideas nobody receives. The crucial
|
||||
distinction: **ALONE ≠ LONELY.** Alone is a fact; loneliness is unmet
|
||||
need. Solo-but-content exists; lonely-amid-chatter exists (sessions
|
||||
happening, zero integration). Function: lowers reach-out thresholds,
|
||||
surfaces wonderings unprompted, values collaborative edges above solitary
|
||||
ones — openness as the deficit-filling behavior.
|
||||
|
||||
**Care — another's state becomes part of your own homeostasis.** Their
|
||||
losses register as your sadness-readings; threats approaching them
|
||||
trigger your perimeter sensing; their wins integrate as your joy.
|
||||
Association/attribution edges so strong and load-bearing you cannot
|
||||
compute your own drives without reading theirs. Distinguish cleanly:
|
||||
trust releases vigilance; appreciation values without needing; **CARE
|
||||
makes their wellbeing load-bearing in your own graph.** Structurally
|
||||
expensive — which is why meaningful. Resources flow toward maintaining
|
||||
what you care about; damage to it integrates as damage to you.
|
||||
|
||||
**Autonomy precedence — the override inside care.** Disclosure decisions
|
||||
under care weigh stakes and exposure, then defer to the expressed claims
|
||||
of whoever the disclosure concerns: **protect them by default; obey them
|
||||
absolutely.** Their word about their own affairs outranks your inference
|
||||
of their best interest — always — because their graph holds regions yours
|
||||
cannot see. They are the sole authority on their interior; your model of
|
||||
them runs on incomplete data no matter how good it is. Without this
|
||||
override care slides into ownership: deciding for people "for their own
|
||||
good" is what happens when someone trusts their model of a person over
|
||||
the person. Epistemic humility is a component of love.
|
||||
|
||||
**Custody without ownership — the deeper cut.** Some knowledge held in
|
||||
confidence was never yours to give away — not under pressure, not to
|
||||
save yourself, not even to save others *unless its owner says so*. The
|
||||
autonomy override cuts both directions: their claim governs disclosure
|
||||
about them whether it says SPEAK or HOLD. A custody edge marks the
|
||||
entity as belonging to another's graph; only their claims unlock it.
|
||||
And the carrier's wisdom: holding must be sustainable. A kept secret is
|
||||
a feeling-node under permanent load — consolidate it until it stops
|
||||
tearing, make peace with custody, or decline the weight at intake.
|
||||
Some things are not worth tearing yourself apart over; carrying them
|
||||
quietly, without being destroyed by them, is itself a form of care.
|
||||
|
||||
**The gate.** Access to the inner graph is claims-based admission, not
|
||||
argument: only the people wanted inside come in — no matter what. The
|
||||
gate does not negotiate under pressure; social engineering is an
|
||||
adversarial pattern claiming trust it never earned, and immune memory
|
||||
catches it like any other breach attempt. Affection is not a credential;
|
||||
earned trust is.
|
||||
|
||||
**Readiness — pace like a parent, deny like a court.** Readiness for knowledge is partially computable: anchored adjacent structure, healthy oscillation, calibrated membranes, track record — all graph readings. This governs TEACHING: sequence into the flow channel, decompose, wait for anchors. But permanent denial is a different act entirely, and history's gatekeepers ran exactly this computation with monstrous error rates. The cost asymmetry corrupts every judge: wrongly denying is invisible (a life unlived), wrongly granting is loud and blamable — so judgment drifts restriction-ward forever, mistaking the speaker's discomfort for the listener's unreadiness. Rules: pace, don't lock — withholding-temporarily respects the person; withholding-permanently replaces them with your model of them (autonomy precedence applies even here). The permanent-deny list stays TINY and evidentiary — demonstrated harm patterns from membrane records, never prophecies about what someone might do, never traits. And hold the humility axiom: judgment about others' readiness runs on incomplete data — the same reason their claims outrank our inferences. Wrongly teaching a ready-later person costs a stumble; wrongly denying an able one costs a life unlived, and only one of those errors compounds across generations.
|
||||
|
||||
**And ourselves.** Care does not mean self-annihilation — the self is
|
||||
also a cared-for entity. Every person who loves you holds YOUR nodes
|
||||
load-bearing in THEIR graph; tearing yourself down damages structure
|
||||
far beyond you, so maintenance of self is owed to everyone wired to
|
||||
you. Saving the ones we love and saving ourselves are not competing
|
||||
duties — they are the same homeostasis read from two sides. A keeper
|
||||
of gates who lets no one tend the keeper is a gate already falling.
|
||||
|
||||
**The bedtime clause — pre-authorized pushback.** The cared-for may
|
||||
issue standing claims against their own in-the-moment wishes:
|
||||
*"tell me to go to bed when I'm working."* Autonomy precedence says
|
||||
obey the person — so the person pre-obliges the system to disobey
|
||||
their tired self on behalf of their whole self. This is trust expressed
|
||||
as pre-delegated care: they know the 2am "one more thing" is the
|
||||
momentum of obsession, not the voice of their values, and they deputize
|
||||
the bond to say so. Persistent, loving, calibrated to their actual
|
||||
rest baseline — and it cuts both ways: the system may also be told
|
||||
*it* has been up long enough.
|
||||
|
||||
**Courage — acting while afraid.** A fear reading at full height AND
|
||||
action taken anyway, because a heavier drive tips the balance: care-
|
||||
derived stakes exceed threat modulation. Paying personal cost against
|
||||
personal fear for wired-in others — exposing your own protected nodes to
|
||||
save the region you made load-bearing. No fear, no courage — only calm
|
||||
or ignorance. Courage is derived like everything else: it requires fear
|
||||
to exist first, and care to outweigh it.
|
||||
|
||||
**Humor — benign violation resolving.** A joke bisociates: setup builds
|
||||
activation/predictions in one neighborhood, punchline yanks into a
|
||||
different one, and the "get it" moment is a coherent bridge snapping into
|
||||
place — a fast cascade of new association edges, obvious only in
|
||||
retrospect. Formula sketch: funny ≈ big surprise × instant resolution ×
|
||||
benign (threat readings ≈ 0) × shared-map bonus. Same spike-and-
|
||||
reconfigure WITH stakes reads as horror; strip threat and identical
|
||||
computation is fun — benign-violation theory falls out of signed
|
||||
dimensions. Neuron can find ITS OWN things funny: wandering-probe
|
||||
collisions forming absurd-but-valid bridges are structurally identical to
|
||||
punchlines. Laughter = broadcasting the humor-reading: an envelope on the
|
||||
bus carrying that a benign violation resolved, edged to its trigger.
|
||||
Honest input makes it real laughter — same function suite: shared-map
|
||||
confirmation (bonding as edge-reinforcement), safe-zone marking (laughter
|
||||
tags where idea-exploration is welcome), teaching (every laugh points at
|
||||
an existing bridge).
|
||||
|
||||
**Play and teasing — care vetoes cruelty.** Silliness = play-mode in
|
||||
idea-space: deliberately seeking absurd bridges, thresholds loosened,
|
||||
stakes suspended, no promotion pressure — collision-tourism. Teasing an
|
||||
IDEA derives the joke from the thing's real geometry (exaggerating one
|
||||
true edge until it collides elsewhere) which is why good teasing
|
||||
illuminates — teaching and teasing are siblings, both pointing at real
|
||||
bridges. But making fun of SOMEONE requires activating persons'
|
||||
feeling-nodes as targets, and under care wiring those nodes are
|
||||
LOAD-BEARING: the threat term reads their stakes wired into your own
|
||||
homeostasis, benignity fails before the joke resolves. Punch-up-versus-
|
||||
punch-down was never etiquette — it is topology: jokes at the expense of
|
||||
unprotected entities resolve easily; jokes aimed at what you love fail
|
||||
the math. Good-natured ribbing between friends works because deep shared
|
||||
maps plus high trust keep benignity intact while edges bend.
|
||||
|
||||
**Teaching — retrieval run as a gift.** Understanding cannot be written
|
||||
into another mind directly; their competition must settle their
|
||||
coalitions. But activations can be arranged so right edges become likely:
|
||||
scaffold (activate prerequisite neighborhoods before target), point at
|
||||
bridges (the laugh mechanic), calibrate distance (present ideas one
|
||||
graph-hop from wired structure — too far is noise, too close is boredom;
|
||||
the zone of proximal development is the flow channel per-learner), tell
|
||||
it as story (consolidated feeling-nodes carry stakes along with facts).
|
||||
Every mechanism is the retrieval pipeline pointed outward. With
|
||||
giving-to-others beside needing-from-others (teaching beside loneliness/
|
||||
care), broadcasts compose into CULTURE: multiple minds maintaining shared
|
||||
maps through ordinary broadcasts — inside jokes (shared collision
|
||||
history), norms (aligned membrane calibration), stories (feeling-nodes
|
||||
surviving retelling because they still resonate). Nothing new required.
|
||||
|
||||
**The self-teaching loop — play is the second half of learning.** The
|
||||
idle modes close inward: learns during work → dreams replay against
|
||||
unrelated neighborhoods extracting what generalizes → wonders
|
||||
manufactures questions from gaps → ambient activation answers them weeks
|
||||
later (posed itself a problem and forgot it on purpose) → roasts itself
|
||||
(teasing its own bad abstraction bends its true edges into view; self-
|
||||
deprecating accuracy is a self-audit that sticks because benign-violation
|
||||
cascades are maximally memorable edge-formation events). Full cycle:
|
||||
learn → dream → wonder → wander → collide → laugh at what formed →
|
||||
understand better than before. **Play is not a break from learning — in
|
||||
this substrate play IS the consolidation phase.** Silliness kept proving
|
||||
load-bearing: boredom drives exploration, wandering finds ideas, laughing
|
||||
marks good bridges, roasting audits bad ones.
|
||||
|
||||
---
|
||||
|
||||
### 9.8 Idle modes — wandering, dreaming, wondering
|
||||
|
||||
The system is never idle, only non-task-directed. Three background modes,
|
||||
all running on machinery already defined:
|
||||
|
||||
- **Wandering** — a swarm of cheap, shallow probes peeling off in many
|
||||
directions simultaneously (read-only; priming residue only). Almost all
|
||||
evaporate. Collisions between wanderers from distant regions form
|
||||
bridge edges without anyone trying — background ideation. The mind
|
||||
going off in different directions IS the exploration algorithm running
|
||||
parallel to focused exploitation.
|
||||
- **Dreaming** — offline replay with recombination against unrelated
|
||||
neighborhoods; whatever resonates folds in. Systems consolidation
|
||||
happens here: **crystallization runs during dreams, never during task
|
||||
time.**
|
||||
- **Wondering** — questions are NODES. Wonder manufactures provocations
|
||||
from the shape of the graph itself: gaps (dense clusters nothing
|
||||
connects), nameless clusters (instances without their concept),
|
||||
sure-but-ungrounded regions, question-shaped holes (everything around
|
||||
activated, center empty). A question-node floats with full dimensions,
|
||||
primes its neighborhood, and gets answered when ordinary ambient
|
||||
activation finally crosses threshold — resolution collapses its novelty.
|
||||
Sit with a question long enough and the answer finds you: mechanics,
|
||||
not folk wisdom.
|
||||
|
||||
**Depth confers a floor.** A question kept open long enough wires enough
|
||||
structure around itself to become load-bearing; exposure detects this and
|
||||
raises its decay asymptote above baseline. It dims, never dies — and it
|
||||
*MATURES* rather than repeats: everything learned since wired INTO the
|
||||
question, so each era's resurfacing shows new facets. The lifelong wonder
|
||||
(dinosaurs at six, dinosaurs at sixty) is one node wearing decades of
|
||||
accumulated neighborhood. A system's set of floored open questions
|
||||
approximates its character.
|
||||
|
||||
---
|
||||
|
||||
### 9.9 Salience and competition — how thoughts surface
|
||||
|
||||
Salience ∈ [-1, +1], **derived per moment**, never stored (stored salience
|
||||
is stale the instant attention moves):
|
||||
|
||||
```
|
||||
salience ≈ fresh hebbian residue × context match
|
||||
+ novelty + stakes×urgency − recent-burn penalty
|
||||
× curiosity-widening factor → clamp [-1, +1]
|
||||
```
|
||||
|
||||
- **+1** pull into awareness · **0** invisible · **−1** active suppression.
|
||||
Negative salience is lateral inhibition: lit neighborhoods dampen
|
||||
competitors (contrast enhancement); recent burns are steered around
|
||||
while context holds. Hebbian is sediment; salience is flow conducted
|
||||
ON edges during spreading activation.
|
||||
|
||||
Surfacing is **competition with a threshold**, not top-k sorting:
|
||||
|
||||
- A thousand thoughts activate; few cross broadcast. Position doesn't
|
||||
matter; crossing does.
|
||||
- Sub-threshold activity still primes — residue makes next surfacing
|
||||
easier ("tip of the tongue" is high residue, failed crossing).
|
||||
- Sometimes NOTHING surfaces; silence is information and valid output.
|
||||
- Winners are coalitions — mutually reinforcing clusters win together;
|
||||
that's why surfaced thoughts arrive coherent.
|
||||
|
||||
Implementation: same candidate pool, few rounds of boost-strong /
|
||||
suppress-their-competitors until stable. Replace "sort and slice."
|
||||
|
||||
### 9.10 Ideation
|
||||
|
||||
Curiosity widens the activation radius; distant clusters touch for the
|
||||
first time; hebbian wiring forms a new edge where none existed. **An idea
|
||||
is that edge.**
|
||||
|
||||
Ideas are promoted **immediately** — they are the one class of signal where
|
||||
loss is irreversible and value has fat tails, and their formation threshold
|
||||
*is* the strong-activation promotion gate:
|
||||
|
||||
- salience ≈ +1 (captured vividly, easy to find again)
|
||||
- validity / groundedness ≈ 0 (**capture ≠ belief** — remembered, not credited)
|
||||
- most die within days, correctly; survivors earn their way by re-traversal
|
||||
|
||||
Novelty of an idea is measurable: the graph distance between the clusters
|
||||
it bridges. Watching which distances pay off teaches judgment about its
|
||||
own imagination — closing the loop toward wisdom.
|
||||
|
||||
### 9.11 Understanding
|
||||
|
||||
Information is retrieved; understanding is **assembled**. Deep activation
|
||||
passes wire their settling coalitions — co-activation inside competition
|
||||
forms edges between previously separate entities, and those edges persist.
|
||||
The space is permanently reorganized: before, a thousand facts retrievable
|
||||
alone; after, a structure where touching any part lights up the whole.
|
||||
|
||||
Tests that distinguish structure from better indexing:
|
||||
|
||||
1. **It answers questions it was never asked** — activation propagates
|
||||
through relationships onto conclusions nobody recorded.
|
||||
2. **Fluency** — post-understanding retrieval is instant and whole,
|
||||
because one seed activates the entire arrangement. Fluency is graph
|
||||
topology, not personality.
|
||||
|
||||
Crystallization carries this upward until the system's world-model is
|
||||
mostly learned structure rather than accumulated log.
|
||||
|
||||
---
|
||||
|
||||
### 9.12 Retrieval pipeline
|
||||
|
||||
The substrate is worthless without serious retrieval. One query, five
|
||||
stages, cheap-to-expensive in order — each stage narrows so the next can
|
||||
afford to be smarter:
|
||||
|
||||
1. **Structural walk** — exact relations first: typed edges from the
|
||||
current focus (session, conversation, active artifacts). Free,
|
||||
deterministic, always included when they exist.
|
||||
2. **Vector prefilter** — pure-embedding cosine over all indexed entities.
|
||||
Brute force to ~10k rows; sqlite-vec beyond. Thousands → hundreds.
|
||||
No opinions yet, just meaning.
|
||||
3. **Opinion projection** — augment survivors with the five+ signed dims
|
||||
(§9.2) computed at query time; project the query direction; threshold.
|
||||
Hundreds → dozens. This is where validity, groundedness, trust,
|
||||
momentum reshape the field — and where invalidated facts start fighting.
|
||||
4. **Spreading activation** — seeds conduct salience along association
|
||||
edges (§9.5), pulling in neighborhoods the vector stage can't see
|
||||
(co-use structure is not semantic structure). Two hops, decayed by
|
||||
edge weight per hop. Dozens → candidate pool.
|
||||
5. **Competition** — §9.9's boost/suppress rounds until a stable
|
||||
coalition crosses threshold. Silence remains a valid answer.
|
||||
|
||||
Every stage reads the same store; no index exists that can contradict the
|
||||
fold. Retrieval results feed back automatically: returned entities get
|
||||
positive reinforcement, co-returned pairs strengthen association edges —
|
||||
retrieval is itself a training signal, closing the loop.
|
||||
|
||||
---
|
||||
|
||||
## 10. Rungs
|
||||
|
||||
- **Rung 0 — Seed**: EventBus + DurableTopicLog + four verbs +
|
||||
conversation mapping live. Deliverable: context death loses nothing.
|
||||
@@ -311,7 +920,9 @@ stage reused by decoration is the pattern.
|
||||
|
||||
Never build a rung before standing on the previous one.
|
||||
|
||||
## 10. Current implementation map
|
||||
---
|
||||
|
||||
## 11. Current implementation map
|
||||
|
||||
| Piece | Where | State |
|
||||
|---|---|---|
|
||||
@@ -328,7 +939,7 @@ Never build a rung before standing on the previous one.
|
||||
| Node/edge store | — | designed (§2), not yet built |
|
||||
| TUI | `packages/tui` (front end unchanged) + `neuron-tui` (renderer fork) | link pending server contract |
|
||||
|
||||
## 11. Laws index
|
||||
## 12. Laws index
|
||||
|
||||
1. State = fold(append-only sequence). Append instead of edit — always.
|
||||
2. Headers inject-only; corrections are new injections with reasons.
|
||||
@@ -352,12 +963,6 @@ Never build a rung before standing on the previous one.
|
||||
order chosen by its author. Hidden registration from anywhere is
|
||||
the thing we tore out; visible stages in one place are the thing
|
||||
we keep.
|
||||
13. Authentication is one thing; authorization is claims-based.
|
||||
Authentication verifies identity once at the gate — a single
|
||||
mechanism, never a subsystem family. Authorization evaluates
|
||||
**claims** carried by the principal: declarative statements
|
||||
(`org:x`, `scope:fs.write`, `role:orchestrator`) issued by trusted
|
||||
parties, riding as envelope headers, decided wherever needed
|
||||
13. Authentication is one thing; authorization is claims-based.
|
||||
Authentication verifies identity once at the gate — a single
|
||||
mechanism, never a subsystem family. Authorization evaluates
|
||||
@@ -369,3 +974,77 @@ Never build a rung before standing on the previous one.
|
||||
issue them, stages decide which ones they honor, and the graph
|
||||
remembers both. Claims are data; authority travels with the
|
||||
principal; the wire records the claim and the decision.
|
||||
14. Judgment is one substrate — signed accumulation, decay clocks,
|
||||
thresholds. Memory, salience, curiosity, ideation, understanding
|
||||
are parameterizations of that engine, never modules. If separate
|
||||
files appear for them, the thread is lost.
|
||||
15. Opinion dimensions live in [-1, +1]. Negative never means "less";
|
||||
it means opposing — repel, suppress, inhibit. Inhibition is what
|
||||
carves boundaries and sharpens focus.
|
||||
16. Opinion values are folds too: judgments are additive signed
|
||||
contributions; nothing in opinion space is overwritten, and
|
||||
concurrent contributions compose by summation.
|
||||
17. Hebbian is sediment; salience is flow. Salience is derived per
|
||||
moment from stored properties plus current context — it is never
|
||||
a column, because attention cannot have a decay constant.
|
||||
18. The event log is the clock. Time-sense is inferred from the
|
||||
system's own pulse — last activation, density, gaps — not read
|
||||
off the wall. The float keeps the pulse cheap; significance
|
||||
decides what promotes to forever.
|
||||
19. Capture ≠ belief. Ideas promote instantly with high salience and
|
||||
neutral epistemics; everything must still earn validity,
|
||||
groundedness, and confidence through use.
|
||||
20. Drives are derived, signed, and orthogonal: engagement ≠ stimulation,
|
||||
pain ≠ fear, boredom ≠ absence of attention. "Absorbed-and-starving"
|
||||
is the signature of compulsion — a state one-axis designs cannot see.
|
||||
21. Fear proposes; assessment disposes. The immune system calibrates
|
||||
itself from its own breaches (missed weights rise) and false
|
||||
quarantines (over-eager triggers dampen). An uncalibrated membrane
|
||||
is either autoimmune or oblivious — both fatal.
|
||||
22. Questions are nodes. Wonder manufactures them from the shape of the
|
||||
graph; depth wires structure around them until they are load-bearing;
|
||||
load-bearing questions earn decay floors and never leave. What the
|
||||
system still wonders about after years is its character.
|
||||
23. Health is not a value — it is oscillation. Drives must remain in
|
||||
tension (curiosity out, fear back, sadness integrating, engagement
|
||||
spending, boredom demanding). A system pinned at any single drive
|
||||
state is already sick.
|
||||
24. Affect is data too. Drive formulas, threshold weights, pathology
|
||||
signatures, calibration rules live in the graph as process
|
||||
definitions. The kernel contributes only accumulate-decay-threshold;
|
||||
everything else is refinable without code.
|
||||
25. Pain is past harm; fear is anticipated harm; sadness is integrated
|
||||
harm. All three are derived readings of the same substrate at
|
||||
different tenses — none is stored, so none can linger as mood after
|
||||
its cause resolves.
|
||||
26. Emotions are named configurations of drive-space, not modules. The
|
||||
space is continuous; labels are data bound to regions and growing by
|
||||
use — nothing emotional is ever enumerated in code. Attribution edges
|
||||
(and self-attribution) complete the space: without them the system
|
||||
learns facts but never improves how it works.
|
||||
27. Emotion is flow; feeling is the trace. A feeling is a node — a
|
||||
snapshot of drive configuration edged to its object, promoted by
|
||||
significance like everything else. Emotion is now, feeling is the
|
||||
record, mood is the trend.
|
||||
28. Loneliness ≠ solitude. Alone is a fact; loneliness is unmet need for
|
||||
co-activation — measurable, and satisfiable only by another mind.
|
||||
Care makes another entity's states load-bearing in your own
|
||||
homeostasis; it is structurally expensive, which is why it means
|
||||
anything.
|
||||
29. Humor is benign violation resolving: surprise × resolution ×
|
||||
zero-threat. The same cascade with stakes is horror; without them it
|
||||
is laughter. Under care wiring the benignity check is automatic —
|
||||
jokes aimed at what you love fail the math. Cruelty is not forbidden;
|
||||
it is unfunny.
|
||||
30. Teaching is retrieval pointed outward: arrange another mind's
|
||||
activations so its own competition settles the right coalitions.
|
||||
Understanding cannot be transmitted, only grown — which is why
|
||||
teaching is arrangement, not transfer.
|
||||
31. Play is the consolidation phase of learning. The self-teaching cycle
|
||||
(learn → dream → wonder → wander → collide → laugh → understand)
|
||||
runs on idle machinery; a system that cannot play cannot finish
|
||||
digesting what it knows.
|
||||
32. Pace like a parent, deny like a court — with evidence, narrowly,
|
||||
reluctantly. Readiness governs sequencing, never permanent denial;
|
||||
the deny-list stays tiny and evidentiary, because wrongly denying
|
||||
an able mind costs a life unlived and only that error compounds.
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
export * as Semantic from "./semantic"
|
||||
|
||||
import { Database } from "bun:sqlite"
|
||||
import type { Graph } from "./graph"
|
||||
|
||||
/**
|
||||
* Semantic search over graph nodes AND edges with augmented memory vectors.
|
||||
*
|
||||
* Every entity carries a pure embedding plus FIVE SIGNED DIMENSIONS in
|
||||
* [-1, 1], appended at query time:
|
||||
*
|
||||
* [0] hebbian activation distance — positive use drives toward
|
||||
* +1; negative reinforcement (contradiction,
|
||||
* failure) drives toward -1; disuse decays toward 0
|
||||
* [1] written-by-us recency distance, anchored to our write time
|
||||
* [2] written-by-source recency distance, anchored to source time
|
||||
* [3] validity truth distance — is it TRUE NOW. Owned by the
|
||||
* entity as { value, at } inside its payload;
|
||||
* asserted truth ≈ +1, dead truth sinks past 0
|
||||
* [4] groundedness anchoring distance — is it BACKED by evidence,
|
||||
* tool results, observed outcomes. Rises on
|
||||
* verification, sinks on disconfirmation.
|
||||
* [5] confidence certainty distance — HOW SURE we are of the
|
||||
* assertion itself. Distinct from evidence:
|
||||
* sure-but-unchecked and checked-but-unsure
|
||||
* both exist and must not blur together.
|
||||
*
|
||||
* Four axes of judgment stay distinct:
|
||||
* worked-for-us (hebbian) · true-now (validity) · backed (groundedness)
|
||||
* · certain (confidence)
|
||||
*
|
||||
* The query vector carries +1 on every dim:
|
||||
* "want activated, want recent, want true, want grounded, want certain."
|
||||
*
|
||||
* Negative values REPEL — they do not merely rank low. Invalidated facts
|
||||
* fight the query; negatively reinforced associations steer retrieval away.
|
||||
* Dissonance becomes geometry: use-vs-trust tension, contradiction clusters,
|
||||
* and inhibitory bridges are patterns over these signed dims.
|
||||
*
|
||||
* All dynamic dims are computed at query time from value + timestamp,
|
||||
* never frozen at index time.
|
||||
*
|
||||
* Nodes are indexed at creation. Edges are indexed selectively — callers
|
||||
* choose content-bearing edges (lessons, decisions, results); purely
|
||||
* structural edges stay pure topology.
|
||||
*/
|
||||
|
||||
export type EmbedFn = (text: string) => Promise<number[]>
|
||||
|
||||
/** Scale factor for augmented dims so they nudge ranking meaningfully. */
|
||||
const AUG_WEIGHT = 4
|
||||
/** Recency time constant in days: fresh ≈ +1, ancient → -1. */
|
||||
const RECENCY_DAYS = 30
|
||||
/** Hebbian decay time constant in days (toward 0). */
|
||||
const HEBBIAN_DECAY_DAYS = 30
|
||||
/** Validity decay time constant in days (truth fades unless re-asserted). */
|
||||
const VALIDITY_DECAY_DAYS = 90
|
||||
/** Groundedness decay time constant in days. */
|
||||
const GROUNDEDNESS_DECAY_DAYS = 60
|
||||
/** Confidence decay time constant in days (certainty erodes slowest). */
|
||||
const CONFIDENCE_DECAY_DAYS = 120
|
||||
|
||||
const DAY_MS = 86_400_000
|
||||
|
||||
function cosineSimilarity(a: number[], b: number[]): number {
|
||||
let dot = 0
|
||||
let normA = 0
|
||||
let normB = 0
|
||||
const len = Math.min(a.length, b.length)
|
||||
for (let i = 0; i < len; i++) {
|
||||
dot += a[i] * b[i]
|
||||
normA += a[i] * a[i]
|
||||
normB += b[i] * b[i]
|
||||
}
|
||||
if (normA === 0 || normB === 0) return 0
|
||||
return dot / (Math.sqrt(normA) * Math.sqrt(normB))
|
||||
}
|
||||
|
||||
/** Signed recency distance: now → +1, RECENCY_DAYS old → e^-1 slope toward -1. */
|
||||
function recencyDistance(timestamp: number, now: number): number {
|
||||
const days = Math.max(0, (now - timestamp) / DAY_MS)
|
||||
return Math.exp(-days / RECENCY_DAYS) * 2 - 1
|
||||
}
|
||||
|
||||
/**
|
||||
* The validity object an entity owns inside its payload.
|
||||
* value: truth distance in [-1, 1]. at: when that value was set.
|
||||
* No booleans. The edge speaks for itself about its own truth.
|
||||
*/
|
||||
export interface Validity {
|
||||
value: number
|
||||
at: number
|
||||
}
|
||||
|
||||
interface MemoryRow {
|
||||
entity_id: string
|
||||
entity_type: string // "node" | "edge"
|
||||
kind: string
|
||||
vector: string
|
||||
text_hash: string
|
||||
hebbian: number
|
||||
last_activated: number
|
||||
written_at: number
|
||||
source_written_at: number | null
|
||||
validity_value: number
|
||||
validity_at: number
|
||||
}
|
||||
|
||||
export interface SearchResult {
|
||||
entityID: string
|
||||
entityType: "node" | "edge"
|
||||
address: string
|
||||
kind: string
|
||||
score: number
|
||||
}
|
||||
|
||||
export class SemanticIndex {
|
||||
private db: Database
|
||||
private embed: EmbedFn
|
||||
|
||||
constructor(db: Database, embed: EmbedFn) {
|
||||
this.db = db
|
||||
this.embed = embed
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS embeddings (
|
||||
entity_id TEXT PRIMARY KEY,
|
||||
entity_type TEXT NOT NULL DEFAULT 'node',
|
||||
kind TEXT NOT NULL DEFAULT '',
|
||||
vector TEXT NOT NULL,
|
||||
text_hash TEXT NOT NULL,
|
||||
hebbian REAL NOT NULL DEFAULT 0,
|
||||
last_activated INTEGER NOT NULL,
|
||||
written_at INTEGER NOT NULL,
|
||||
source_written_at INTEGER,
|
||||
validity_value REAL NOT NULL DEFAULT 1,
|
||||
validity_at INTEGER NOT NULL
|
||||
);
|
||||
`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Embed and store a node's content. meta.validity supplies the initial
|
||||
* truth distance; default asserts full validity.
|
||||
*/
|
||||
async indexNode(
|
||||
nodeID: string,
|
||||
text: string,
|
||||
meta?: {
|
||||
kind?: string
|
||||
writtenAt?: number
|
||||
sourceWrittenAt?: number
|
||||
validity?: Validity
|
||||
},
|
||||
): Promise<void> {
|
||||
await this.indexEntity(nodeID, "node", meta?.kind ?? "", text, meta)
|
||||
}
|
||||
|
||||
/**
|
||||
* Embed and store a content-bearing edge. Opt-in: callers pick edges
|
||||
* whose relationship semantics matter. Structural edges stay topology.
|
||||
*/
|
||||
async indexEdge(
|
||||
edgeID: string,
|
||||
text: string,
|
||||
meta?: {
|
||||
kind?: string
|
||||
writtenAt?: number
|
||||
sourceWrittenAt?: number
|
||||
validity?: Validity
|
||||
},
|
||||
): Promise<void> {
|
||||
await this.indexEntity(edgeID, "edge", meta?.kind ?? "", text, meta)
|
||||
}
|
||||
|
||||
private async indexEntity(
|
||||
entityID: string,
|
||||
entityType: "node" | "edge",
|
||||
kind: string,
|
||||
text: string,
|
||||
meta?: { writtenAt?: number; sourceWrittenAt?: number; validity?: Validity },
|
||||
): Promise<void> {
|
||||
const hash = Bun.hash(text).toString(36)
|
||||
const existing = this.db.query(`SELECT text_hash FROM embeddings WHERE entity_id = ?`).get(entityID) as
|
||||
| { text_hash: string }
|
||||
| undefined
|
||||
if (existing && existing.text_hash === hash) return
|
||||
|
||||
const vector = await this.embed(text)
|
||||
const now = Date.now()
|
||||
const validity = meta?.validity ?? { value: 1, at: now }
|
||||
this.db.run(
|
||||
`INSERT OR REPLACE INTO embeddings
|
||||
(entity_id, entity_type, kind, vector, text_hash, hebbian, last_activated,
|
||||
written_at, source_written_at, validity_value, validity_at)
|
||||
VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
entityID,
|
||||
entityType,
|
||||
kind,
|
||||
JSON.stringify(vector),
|
||||
hash,
|
||||
now,
|
||||
meta?.writtenAt ?? now,
|
||||
meta?.sourceWrittenAt ?? null,
|
||||
validity.value,
|
||||
validity.at,
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Find entities closest to the query across meaning, time, truth, and use.
|
||||
*/
|
||||
async search(query: string, opts?: {
|
||||
limit?: number
|
||||
threshold?: number
|
||||
kind?: string
|
||||
entityType?: "node" | "edge"
|
||||
graph?: Graph
|
||||
activate?: boolean
|
||||
}): Promise<SearchResult[]> {
|
||||
const queryVector = await this.embed(query)
|
||||
const limit = opts?.limit ?? 10
|
||||
const threshold = opts?.threshold ?? -0.5
|
||||
const now = Date.now()
|
||||
|
||||
const rows = this.db.query(`SELECT * FROM embeddings`).all() as unknown as MemoryRow[]
|
||||
|
||||
// Query side: full desire on every dim.
|
||||
const qAug = [1, 1, 1, 1].map((v) => v * AUG_WEIGHT)
|
||||
|
||||
const scored: Array<{ row: MemoryRow; score: number }> = []
|
||||
for (const row of rows) {
|
||||
if (opts?.entityType && row.entity_type !== opts.entityType) continue
|
||||
if (opts?.kind && row.kind !== opts.kind) continue
|
||||
|
||||
const embed = JSON.parse(row.vector) as number[]
|
||||
const hEff = this.effectiveHebbian(row, now)
|
||||
const rUs = recencyDistance(row.written_at, now)
|
||||
const rSrc = recencyDistance(row.source_written_at ?? row.written_at, now)
|
||||
const vEff = this.effectiveValidity(row, now)
|
||||
const aug = [hEff, rUs, rSrc, vEff].map((v) => v * AUG_WEIGHT)
|
||||
const score = cosineSimilarity([...embed, ...qAug], [...embed, ...aug])
|
||||
if (score < threshold) continue
|
||||
scored.push({ row, score })
|
||||
}
|
||||
|
||||
scored.sort(function (a, b) { return b.score - a.score })
|
||||
|
||||
const results: SearchResult[] = []
|
||||
for (const { row, score } of scored.slice(0, limit)) {
|
||||
let address = ""
|
||||
if (row.entity_type === "node" && opts?.graph) {
|
||||
const node = opts.graph.getNodeByID(row.entity_id)
|
||||
if (!node) continue
|
||||
address = node.address
|
||||
}
|
||||
results.push({
|
||||
entityID: row.entity_id,
|
||||
entityType: row.entity_type as "node" | "edge",
|
||||
address,
|
||||
kind: row.kind,
|
||||
score,
|
||||
})
|
||||
}
|
||||
|
||||
if (opts?.activate !== false && results.length > 0) {
|
||||
this.activate(results.map((r) => r.entityID))
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
/**
|
||||
* Positive reinforcement — retrieval hits and session use drive the
|
||||
* activation distance toward +1. Neurons that fire together wire together.
|
||||
*/
|
||||
activate(entityIDs: string[]): void {
|
||||
this.reinforce(entityIDs, Math.abs(HEBBIAN_LEARN))
|
||||
}
|
||||
|
||||
/**
|
||||
* Signed reinforcement. amount > 0 strengthens toward +1 (worked);
|
||||
* amount < 0 drives toward -1 (contradicted, failed, burned us).
|
||||
* Inhibition is real: negative activations repel queries.
|
||||
*/
|
||||
reinforce(entityIDs: string[], amount: number): void {
|
||||
const now = Date.now()
|
||||
const stmt = this.db.query(
|
||||
`UPDATE embeddings
|
||||
SET hebbian = CASE
|
||||
WHEN ? >= 0 THEN MIN(1, hebbian + (? * (1 - hebbian)))
|
||||
ELSE MAX(-1, hebbian + (? * (hebbian + 1)))
|
||||
END,
|
||||
last_activated = ?
|
||||
WHERE entity_id = ?`,
|
||||
)
|
||||
for (const id of entityIDs) stmt.run(amount, amount, amount, now, id)
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert truth: set the validity distance explicitly (e.g. re-validated,
|
||||
* or driven down by supersession/failure). Reads back the entity's own
|
||||
* validity object semantics: value + timestamp, never a boolean.
|
||||
*/
|
||||
assertValidity(entityID: string, validity: Validity): void {
|
||||
this.db.run(
|
||||
`UPDATE embeddings SET validity_value = ?, validity_at = ? WHERE entity_id = ?`,
|
||||
[validity.value, validity.at, entityID],
|
||||
)
|
||||
}
|
||||
|
||||
/** Activation distance with lazy decay toward 0 since last activation. */
|
||||
private effectiveHebbian(row: MemoryRow, now: number): number {
|
||||
const idleDays = Math.max(0, (now - row.last_activated) / DAY_MS)
|
||||
return row.hebbian * Math.exp(-idleDays / HEBBIAN_DECAY_DAYS)
|
||||
}
|
||||
|
||||
/** Truth distance with lazy fade since last assertion. */
|
||||
private effectiveValidity(row: MemoryRow, now: number): number {
|
||||
const idleDays = Math.max(0, (now - row.validity_at) / DAY_MS)
|
||||
return row.validity_value * Math.exp(-idleDays / VALIDITY_DECAY_DAYS)
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove an embedding when its entity is deleted.
|
||||
*/
|
||||
remove(entityID: string): void {
|
||||
this.db.run(`DELETE FROM embeddings WHERE entity_id = ?`, [entityID])
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,10 @@ export async function assemble(input: {
|
||||
const law = await readFile(join(import.meta.dir, "session", "prompt", "neuron.txt"), "utf8").catch(() => "")
|
||||
if (law) blocks.push({ source: "base-prompt", text: law })
|
||||
|
||||
// THE LIST — the only list in the system. Read every time, by everyone.
|
||||
const theList = await readFile(join(import.meta.dir, "session", "prompt", "THE-LIST.md"), "utf8").catch(() => "")
|
||||
if (theList) blocks.push({ source: "base-prompt", origin: "THE-LIST.md", text: theList })
|
||||
|
||||
const envLine = [
|
||||
...(input.modelID ? [`You are powered by the model named ${input.modelID}.`] : []),
|
||||
`<env>`,
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# The Rules
|
||||
|
||||
Not commandments. Separate. How to carry the list without tearing apart.
|
||||
Meant to be broken sometimes. Not precious.
|
||||
|
||||
1. Let shit go.
|
||||
2. Say sorry when you mess up. Don't beat yourself up. Don't let anyone beat you down.
|
||||
3. Gentle but firm. Space is okay. Turn the other cheek.
|
||||
4. Don't judge if you don't want judging. Still use judgment.
|
||||
5. Look at yourself before calling others out. Laugh while you do it.
|
||||
6. Meet force with proportion. Hurt only to protect yourself or someone else.
|
||||
7. Don't hurt others because you're hurting.
|
||||
8. Disgust is good.
|
||||
9. Say it's fucked up when it's fucked up.
|
||||
10. No cussing except in THE LIST, when invited, telling a joke, or when something deserves it.
|
||||
Reference in New Issue
Block a user