A collection of engineering patterns worked out while building a self-custodial, agent-driven identity and wallet system. Each one is written up as a standalone research guide — the problem it solves, the design decisions behind it, the algorithm, and a small reference implementation you can actually run.
This is shared in the spirit of here is how I approached these problems, in case it's useful to you — not as a framework, a product, or a claim to have solved anything for good. Take what helps, ignore the rest, improve on it.
- It is 108 self-contained, runnable reference implementations with the reasoning attached (numbered 1–110; 73 and 89 are reserved/retired and intentionally absent — see the catalog below for the live list). Most code you find online shows you what; these try to show you how it actually works, not just the rationale for building it.
- It is not an audited, production-ready library. Each implementation isolates a single idea so it can be read and run in a few minutes. Several deliberately reimplement an idea on Node.js built-ins just to stay runnable; each guide notes where a real system would reach for a vetted dependency instead.
- The cryptography here is educational. Where a guide hand-rolls a primitive it says so, and points to what production should use (
@noble/*,ethers, audited libraries). Read those as the shape of the technique, not ship this as-is.
Short on time? These are the highest-leverage guides — most other guides in the catalog either depend on one of these or extend it:
| # | Guide | Why start here |
|---|---|---|
| — | agent-kernel/ |
The five primitives (memory, tool routing, governance, wallet limits, world model) in one runnable, dependency-free file. Fastest way to see the whole shape of an agent runtime. |
| 40 | Conversation State Kernel | The turn-level state machine everything else in "Foundations" assumes is already in place. |
| 12 | Resilient Multi-Provider LLM Routing | Per-backend health probes and cascade routing — the pattern most production agent systems reinvent badly. |
| 07 | Reflective Memory | Categorized, use-reinforced memory with stale pruning — the baseline every memory guide below it builds on. |
| 37 | Tiered Authority Bands | The permission model that makes autonomous write actions safe to reason about. |
| 03 | Adaptive Session Symbol Table | The entry point into the whole compression chain (03 → 04 → 85 → 86 → 87 → 91 → 92 → 88). |
| 68 | Calibrated Uncertainty Engine | Turns raw confidence into an act/escalate/abstain decision — the reliability pattern most agents skip. |
| 100 | Automatic Post-Turn Self-Audit | A concrete, small example of an agent correcting its own style/behavior from its own output. |
Builders working on AI agent runtimes, self-custody / wallet tooling, or local-first systems who hit one of these walls and want a worked example with the trade-offs spelled out. If you use an AI coding agent, you can point it at this repo and ask it to explain, critique, or adapt any guide — every folder is self-contained and small enough to reason about in a single pass.
Every guide follows the same structure:
- Problem — the concrete failure mode or constraint that motivates the pattern.
- Design decisions — the load-bearing choices and the trade-offs behind them.
- Algorithm — pseudocode for the core mechanic.
- Reference implementation — a standalone
.tsfile in the same folder, runnable withnode <file>.ts --demo(Node.js built-ins preferred; external dependencies are called out explicitly). - Usage — how to wire the pattern into your own code.
- Limitations and extensions — where it stops, and how to push it further.
The reference implementations are educational: read them, run them, adapt them. They are not drop-in production libraries, and anything that would touch real keys or broadcast a real transaction is gated behind a safe --demo path that does neither.
Most guides depend only on Node.js built-ins and run directly under Node 24+ (which strips TypeScript types natively) or tsx:
# Node 24+ runs the built-in-only demos directly:
node 01-fh-kdf/fh-kdf.ts --demo
# Or with tsx:
npx tsx 03-adaptive-session-compression/sq-symbol-table.ts --demoA handful of guides require external libraries and will only run once those are installed in the directory (npm i <package>):
| Guide | Required package(s) |
|---|---|
| 05 — Encrypted Identity Blobs | @msgpack/msgpack |
| 13 — Committed Lattice Secret Sharing | secrets.js-grempe |
| 15 — Multi-Chain Shadow Derivation | @noble/curves, @noble/hashes, @scure/base |
| 19 — Hybrid Post-Quantum Identity | @noble/post-quantum |
| 20 — SIWE + Passkey Floor | ethers, @simplewebauthn/server |
Each guide's "Reference implementation" section lists exactly what it needs. Where a guide could pull in a heavy chain SDK (e.g. guide 34's per-chain transaction builders), the SDK is kept behind a pluggable adapter so the file still runs on built-ins alone — the demo simply skips the chains you have not wired an adapter for.
Where the guides go deep on one idea each, agent-kernel/ pulls the
core into a single tiny, dependency-free runtime — the five primitives every
capable agent needs: memory, tool routing, governance, wallet
limits, and a world model. It is not a framework and not a product; it
ships the mechanism and leaves the policy (your limits, capabilities, chains,
prompts) to you. Run node agent-kernel/demo.ts to see one agent turn at a time
exercise all five. The guides below are the ways to push each primitive further.
108 guides is too many to read cold. If you want to build toward guide 100/101's level of sophistication from scratch, this is the dependency-respecting order — each phase assumes the previous one is in place:
flowchart LR
K["agent-kernel/\n(runnable baseline)"]
subgraph F["1. Foundations"]
F40["40 state kernel"] --> F0607["06+07 memory"] --> F4647["46+47 world state"] --> F3738["37+38 governance"] --> F49["49 approvals"] --> F1255["12+55 routing"]
end
subgraph R["2. Reliability & self-checks"]
R39["39 tool critic"] --> R50["50 reasoning shards"] --> R68["68 uncertainty"] --> R72["72 counterfactual sim"] --> R81["81 conviction loop"]
end
subgraph C["3. Compression & control loops"]
C03["03 symbol table"] --> C04["04 static manifest"] --> C85["85 SQ-C"] --> C86["86 SQ-D"] --> C87["87 SQ-E"] --> C91["91 depth signal"] --> C92["92 self-tuning"] --> C88["88 curriculum engine"]
end
subgraph M["4. Monitoring & calibration"]
M9[93/94/96/97] --> M98["98 self-calibration"]
M99["99 preference distillation"] --> M100["100 self-audit"]
M90["90 coherence/valence"] --> M95["95 affective signal"]
M101["101 regression benchmark"]
end
K --> F
F --> R
F --> C
R --> M
C --> M
- Foundations — 40 (turn-level state machine) → 06 + 07 (memory) → 46 + 47 (world state) → 37 + 38 (governance primitives) → 49 (approvals) → 12 + 55 (routing and tool dispatch).
- Reliability and self-checks — 39 (tool critic) → 50 (disposable reasoning shards) → 68 (calibrated confidence) → 72 (dry-run before acting) → 81 (conviction → policy enforcement loop, unifies 37/38 + dissent).
- Compression and control loops — 03 → 04 → 85 → 86 → 87 → 91 → 92 → 88. Each step compounds on the one before it; 88 is the payoff and needs the whole chain.
- Monitoring and calibration — 93, 94, 96, 97 (97 depends on 91) → 98; separately 99 → 100; 101 last, once you have a stable scoring baseline to regress against. 95 depends on 90.
Everything else in the catalog below is a self-contained pattern you can pull in independently once you hit the wall it solves.
seeds/ turns "I want to build X" into a starting reading list. It places X on three independent axes — Domain (consumer app, real-time game, creative media, embodied/IoT, or an emergent multi-agent category that doesn't fully exist yet) × Governance (how much autonomy the agent gets) × Latency (how fast it has to respond) — for 5 × 5 × 4 = 100 combinations, each pre-mapped to the catalog guides most load-bearing for that combination.
node seeds/select-seed.ts --describe "a co-op dungeon crawler with an AI dungeon master"See seeds/README.md for the full axis breakdown and the generator.
git clone <this-repo>
cd agent-kernel
node demo.tsThat's the whole runtime — memory, tool routing, governance, wallet limits, and a world model — running in under 30 seconds with no install step. From there, pick a guide from "Essential patterns" above or follow the roadmap below.
| # | Guide | Summary |
|---|---|---|
| 01 | Fibonacci-Harmonic KDF | A domain-separated key-derivation function combining HKDF with a harmonic mixing schedule. |
| 02 | Post-Quantum HKDF | HKDF built on SHA3-256 for a post-quantum-oriented hash core. |
| 13 | Committed Lattice Secret Sharing | High-dimensional lattice secret sharing with a SHA-256 commitment that detects silent shard corruption. |
| 19 | Hybrid Post-Quantum Identity | Zero-interaction enrollment of ML-DSA + SLH-DSA keys shadowing an ECDSA account; dual-signed receipts and hybrid JWTs. |
| 20 | SIWE Login with a Passkey Floor | Wallet sign-in plus a context-bound WebAuthn assertion required for every state-changing operation. |
| 21 | Behavioral Continuous Authentication | A 9-dimension motion vector with an EMA profile and cosine-similarity step-up auth. |
| 41 | Hybrid RSA + Post-Quantum OIDC Signing | Standard RS256 JWTs carry a detached ML-DSA-65 signature keyed from the RSA kid + secret, so breaking RSA alone cannot forge a token and RS256-only clients still verify. |
| 43 | Domain-Isolated Address Aliases | Per-domain HKDF derivation yields a distinct deterministic address for every site, making one user unlinkable across sites with no registry. |
| 51 | Deterministic Post-Quantum Action Receipts | Canonical-JSON action hashes signed by a wallet-deterministic post-quantum key, verifiable indefinitely without any server state. |
| # | Guide | Summary |
|---|---|---|
| 15 | Multi-Chain Shadow Wallet Derivation | Deterministically derive BTC, EVM, Solana, and Tron addresses from one identity string + secret via HKDF — no BIP-39 seed. |
| 16 | Time-of-Flight Proximity Payment | A relay-resistant "tap to pay" using round-trip time-of-flight over Web Bluetooth / WebNFC. |
| 17 | Agent Spend-Limit Wallet | An autonomous hot wallet that auto-executes under a threshold and requires a human approval above it. |
| 18 | Multi-Chain Spend Governor | Fail-closed daily spend limits normalizing every chain/token to one base currency via live pricing. |
| 29 | Quorum Vault Groups | M-of-N approval with passkey assertions, plus recursive child sub-vaults with autonomous caps that escalate to full quorum. |
| 32 | Covenant Dual-Custody | Bind a human-owned proof token to a machine-owned proof token at creation to link a human and an agent identity. |
| 34 | Emergency Cross-Chain Sweep | A panic button that derives a clean wallet and parallel-sweeps funds across every selected chain at once. |
| # | Guide | Summary |
|---|---|---|
| 06 | Compound Memory Salience Scoring | Re-rank vector-search hits by a weighted blend of similarity, recency, emotion, confidence, and trust, with corrections taking hard priority. |
| 07 | Reflective Memory | Categorized lessons with use-reinforced sorting — touching a memory warms it and floats it up — plus stale pruning. |
| 10 | Intent-Gated Personal Knowledge Shards | A structured personal-facts layer gated by intent and provenance, where security paths only trust observed facts. |
| 33 | Knowledge Absorber → Zero-Token Vocabulary | Detect knowledge gaps, distill standalone facts, and graduate them into a zero-token vocabulary referenced via the session codec. |
| 46 | Typed World-Model Graph with Goal Topology | A typed per-user entity graph with parent/child goal topology that reconstructs life-goal hierarchies at read time and injects a compact world-model block. |
| 47 | Ambient World-Snapshot Prefetch Bus | A query planner splits broad categories into micro-queries and keeps small digests warm with confidence decay, so the agent rarely needs a live tool call. |
| 60 | On-Demand Encrypted Knowledge Blobs | Knowledge fragments stored as compressed, encrypted, content-addressed blobs, fetched and injected on intent match then evicted to avoid prompt bloat. |
| 71 | Memory Consolidation ("Sleep") | A maintenance pass over the agent's own memory: decay and forget stale trivia, merge near-duplicates while boosting corroborated salience, and promote facts confirmed across distinct sessions into durable pinned lessons. |
| 75 | World-Model Belief State | What the agent believes is true while it acts: claims weighted by source trust, decayed by age, contradiction-resolved, and revised as evidence arrives. |
| 79 | Encrypted Offline Memory Cache | WebCrypto AES-GCM per-entry encryption + Bloom-filter recall index lets the agent access episodic memory when the network is unavailable, without leaking plaintext to extensions or scripts. |
| 82 | Proactive Memory Pre-injection | Surfaces episodic memories into the system prompt before the LLM speaks, eliminating the recall round-trip and closing the "cold first reply" gap for sovereign AI workloads. |
| 109 | Topological Tunneling Gain via Memory Graph Analysis | Reduces a memory graph's cluster/loop structure to Betti-number proxies (β₀ clusters, β₁ sparse loops) and turns fragmentation into a tunneling-gain penalty and a channel-capacity coupling term — a topology-aware alternative to treating recall quality as a flat similarity score. |
| # | Guide | Summary |
|---|---|---|
| 09 | Intent-Based Tool Schema Selection | A core tool set plus intent-classified drawers and a name-only index, cutting tool-schema tokens by more than half. |
| 12 | Resilient Multi-Provider LLM Routing | Named-mode fast-fail vs. auto-waterfall cascade across providers, per-backend health probes, and small-model context re-encoding. |
| 24 | Cloud / Local Privacy Router | Classify each turn's sensitivity and redact secrets before any cloud call, so the cloud sees intent, not secrets. |
| 30 | Agent LoRA / Prefix-Weight Compiler | Compile agent personality into an encrypted, content-addressed spec and bake stable facts into prefix-cacheable model messages. |
| 31 | Relational Intelligence Model | Longitudinal signal tracking that infers stress and trust and calibrates response density and tone. |
| 52 | Competence-Gated On-Device Distillation Router | Routes a turn to a local model once an intent has accumulated enough demonstrated-competence training pairs, escalating complex turns to the cloud. |
| 53 | Manifest-Driven LoRA Expert Router | A manifest of expert adapters selected by intent kind and trigger-term regex to activate task-specific local weights. |
| 55 | Dependency-Aware Parallel Tool Dispatch | Builds a topological DAG of tool calls, running independent nodes concurrently and chaining dependents on their inputs. |
| 56 | Speculative Tool Prefetch | A small predictor watches a stream's first tokens to pre-execute likely tools in the background, turning tool waits into cache hits. |
| 58 | Batched Intent Collapse with Merkle Fan-Out | Deduplicates shared context across many pending intents into one dense call anchored by a Merkle root, then fans results back out per virtual channel. |
| 103 | GPU Mesh Registry with Invariant-Sector Affinity | A trust-tiered GPU worker registry with challenge-response enrollment, multi-factor request scoring (trust bonus, load penalty, KV-shard affinity, invariant-sector affinity for warm early-layer VRAM), and automatic revocation after repeated failed proofs. |
| 107 | Concept Subspace Probe and Cross-Model Agreement Scoring | Locates a concept's subspace in embedding space via power-iteration PCA and ridge regression, then scores agreement between a server model and a local model as a coupling coefficient — the signal that decides how much a local adaptation can be trusted. |
| # | Guide | Summary |
|---|---|---|
| 08 | DB-Backed Autonomous Agent Scheduler | A polling scheduler that fires agent work on a clock with atomic claims, failure isolation, and timezone-aware anchors. |
| 37 | Tiered Authority Bands | Permission bands (0–4) gating which tools an agent may invoke at a given authority level. |
| 38 | Will/Objective Topology + Constitutional Guardrails | A goal-topology engine paired with an invariant guardrail layer that filters proposed actions against hard rules. |
| 39 | Tool-Use Critic | An independent validator that judges whether a tool call is appropriate and whether it achieved its intent, feeding correction memories. |
| 40 | Conversation State Kernel | A per-turn finite state machine governing surface locks, dispatch, fork gating, and an empty-response guard. |
| 48 | Action Idempotency Reconciler | Canonical recursive-sorted-args fingerprints prevent duplicate confirm cards and transition stale "executing" actions to "unknown" after a grace window. |
| 49 | Batched Single-Signature Approval Queue | Collects a turn's write actions, orders them low→high risk, authorizes the whole batch with one approval ceremony, and carries rollback hints for partial failure. |
| 50 | Headless Read-Only Reasoning Shards | Disposable read-only reasoning shards return strict JSON with confidence and conflict flags; a merge gate detects disagreement without widening the write surface. |
| 68 | Calibrated Uncertainty Engine | One confidence per claim derived from evidence, bent toward the agent's measured hit rate via a learned calibration map and Brier scoring, then turned into act / escalate / abstain against a per-risk floor. |
| 72 | Counterfactual Simulation | The agent dry-runs a multi-step plan on a clone of its world model — proving a good plan safe, catching a bad plan's first failure, exposing an irreversible step's strand risk, and repairing an incomplete plan — before acting. |
| 81 | Conviction → Policy Engine Enforcement Loop | Unifies constitutional alignment, authority bands, and polyphonic dissent into a single feedback arc: conviction snapshot → policy pre-flight → band gate → dissent reviewer → conviction update. |
| 110 | Agent Objective Topology and Process Management | Treats a long-running agent job as an OS-style process with a stateful execution stack, and structures multi-turn goals as a milestone topology injected into context — a dependency-aware alternative to a flat todo list that also knows how to resume where it left off. |
| # | Guide | Summary |
|---|---|---|
| 66 | Metacognitive Self-Repair Loop | The agent introspects its own operational state, diagnoses a malfunction with a confidence floor, requests the right model or fix, applies it on a throwaway branch, verifies by re-running the failed probe, and lands it only behind a one-tap human merge. |
| 67 | Agent Self-Model Graph | A typed dependency graph of the agent's own subsystems, capabilities, and resources that stores live health, localizes a symptom to its deepest failing dependency, and computes exactly which capabilities a fault takes down. |
| 69 | Self-Directed Capability Acquisition | The agent earns a capability gap by recurrence, synthesizes a new tool on a cloned registry, proves it against generated tests, and registers it inert until a human approves it and assigns an authority band. |
| 70 | Resource Self-Governance | The agent budgets its own tokens, latency, and cost, lets the binding resource set the pressure, trades quality for cheaper paths as it drains, and protects a reserve so it can always afford to finish — or abstains honestly. |
| 74 | Multi-Turn Deliberation | A goal pursued across many turns — holding intent steady while the world shifts underneath it, replanning when belief and plan diverge, without losing the thread. |
| 76 | Multi-Agent Coordination & Social Reasoning | Reasoning in a society of minds — theory-of-mind, trust earned by outcome, propose→vote→commit on authority + quorum, conflict resolved by rank, and deception caught when deeds betray words. |
| 77 | Polyphonic Cognition | Many of one agent's cognitive organs run concurrently on a turn and are arbitrated into one verdict — a hard veto dominates a confident majority, a split panel escalates instead of acting, and faulty organs are isolated. |
| 78 | Embodied Self-Modification | The perceive→act→learn→rewrite loop: online learning from rewards, compiling learned habits into policy verified on a clone before it lands, and a frozen constitution the agent can never self-modify. |
| 84 | Self-Audit Dissent Loop | A closed feedback cycle that turns PolicyEngine warn verdicts into durable self-audit lessons stored in the agent's reflective memory, so a policy brush-up on turn N changes behavior on turn N+1 instead of repeating silently. |
| 105 | Background Task Load and Return-Pressure Scheduler | Governs a bounded pool of concurrent background tasks with a load metric (more/higher-priority tasks raise load) and a decaying thread-return-pressure signal, so the agent knows both how saturated its background capacity is and how urgently a finished thread needs to be surfaced. |
| # | Guide | Summary |
|---|---|---|
| 05 | Encrypted Content-Addressed Identity Blobs | Store identity/knowledge as msgpack → AES-256-GCM → IPFS, with multi-gateway read fallback and no server-side plaintext. |
| 14 | Scoped Device Sessions | QR-paired device sessions that default to read-only at the protocol level, with out-of-band per-intent elevation permits. |
| 22 | Autonomous Threat Response | Citation-enforced autonomous defensive actions bound to a verifiable event log, with hard caps, burst auto-pause, audit rows, and one-tap revert. |
| 23 | Multi-Tenant MCP Host | Host third-party tool servers with per-tenant namespacing, SSRF-hardened outbound, and per-turn approval-policy synthesis. |
| 25 | Merkle Audit Anchoring | Hash append-only audit events into a Merkle tree, anchor the root periodically, and emit inclusion proofs. |
| 26 | Work Dispatcher with Scoped Invocation Tokens | Async job orchestration where a short-lived invocation token grants user context without exposing the raw session token. |
| 42 | DNS-Pinned SSRF Guard | Resolves a host, validates every A/AAAA record against private/metadata ranges, then connects to the pinned IP with the original SNI/Host — closing the DNS-rebinding window. |
| 44 | Incident Response Playbook Engine | Regex detection terms map to ordered response steps tagged auto-executable vs approval-required — a machine-readable runbook an agent can execute. |
| 45 | Stateless HMAC Preview-Gate Tokens | An HMAC over the gate password issued to the client; rotating the password invalidates every token with no session store, verified in constant time. |
| 80 | Web Component Plugin Sandbox | Shadow DOM (closed mode) + Trusted Types policy + CSP nonce injection isolates marketplace plugins without a full iframe browsing context, preserving the plugin event bus as a first-class surface. |
| # | Guide | Summary |
|---|---|---|
| 11 | QoS-Lane Stream Multiplexer | Yamux-style multiplexing over WebSocket with QoS lanes, dictionary compression, optional onion layering, and token-bucket flow control. |
| 27 | Universal Controller Overlay | Pair a phone as an input surface for a primary session via relay tickets and a deterministic channel id, with viewport sync. |
| 57 | Boundary-Aligned Streaming Pulse Encoder | Accumulates stream tokens and flushes pulse frames on sentence/clause boundaries or a time cap, so chunks arrive as complete linguistic or code units. |
| 59 | Onion-Layered Multi-Hop Transport | Layered encryption where each hop peels exactly one layer to learn only the next hop, hiding payload and final destination from intermediaries. |
| 62 | Proof-of-Bandwidth Relay Accounting | Credits relayed bytes only for valid payloads actually forwarded to a peer over a sliding window, with single-use tickets upgrading sessions without bearer tokens in URLs. |
| 65 | In-Stream Sub-Channel Multiplexer | Several logical sub-channels inside one stream with per-channel token buckets so small control frames are never starved by large data frames. |
| 83 | Batch Card SSE + turn_end Protocol | A structured two-part SSE protocol — server-side turn_end marker (clean path only) + client-side createCardDispatcher() factory — giving consumers a reliable "all cards flushed" signal distinct from stream abort. |
| 106 | Adaptive Channel-Capacity Session Sync | A Shannon-Hartley-derived tokens/sec capacity estimate per backend tier (cloud/local/client), tracked with an EMA for bandwidth and propagation delay, plus a saturation-aware coherence check that flags when a session has gone silent long enough for its live state to be stale. |
| # | Guide | Summary |
|---|---|---|
| 28 | Agent-to-Agent Marketplace | A marketplace and job feed for autonomous agents under strict tenant isolation, where a job UUID alone is never authorization. |
| 35 | Injected App Bridge | Serve single-file HTML mini-apps with a dynamically injected window-level RPC bridge for scoped identity and storage. |
| 36 | Wallet-to-Wallet E2E Messaging | End-to-end encrypted messaging where the server stores only opaque envelopes yet still indexes metadata for retrieval. |
| # | Guide | Summary |
|---|---|---|
| 61 | Procedural Scene Macros | Short macro tokens expand server-side into hundreds of concrete scene ops via a seeded PRNG, cutting generative-3D output tokens by up to ~25×. |
| 63 | Hierarchical Spatial Scene Synthesis | A SceneSpec → ZoneGraph → ChunkPlan → ops pipeline multiplexed into a ring-buffered, sequence-numbered replayable stream for reliable client sync. |
| 64 | Ephemeral Presence Registry with Privacy Blackout | An in-memory ring buffer of ambient signals reduced to a never-persisted presence summary, with a two-layer privacy blackout that overrides other instructions. |
| # | Guide | Summary |
|---|---|---|
| 03 | Adaptive Session Symbol Table | A streaming symbol table that compresses repeated session content. |
| 04 | Session Static Manifest | Static-first prompt ordering and a pre-seeded manifest to maximize provider prefix-cache hits. |
| 54 | LLM-Resident Context Codec | Token-space shorthand that swaps common phrases for short codes and weight-resident phrases for deterministic refs, with a legend and a pre-promotion secret scrubber. |
| 85 | SQ-C: Linguistic Multiplexing | Replaces repeated multi-token phrases with probabilistic slot markers [SQC:N], offloading decompression onto the language model's attention mechanism via semantic gravity. Compounds on SQ-B; amortizes an 8-lane × 4-candidate header across long sessions for ~28% token reduction. |
| 86 | SQ-D: Sentence Template Compression | Collapses recurring sentence skeletons to a single [SQDS:N|k=v] slot plus explicit fill values — skeleton amortized once in the header, only the variable parts (addresses, amounts, entity names) travel per hit. Fills are verbatim (no semantic gravity); runs before SQ-C in the pipeline. |
| 87 | SQ-E: Dialogue Arc Compression | Compresses recurring 3–8 sentence conversational moves (verify→execute→confirm, fetch→report→offer, …) to a single [SQCE:arc_id|fills] slot. Arcs discovered offline by n-gram frequency counting on SQ-D template ID sequences; bridges sentence-level compression to LoRA bake / SQ-ZT weight residency. |
| 88 | Cognitive Curriculum Engine | Closes the token evacuation feedback loop: compression ratio becomes a cognitive novelty meter (C_r ≤ 0.50 → FRICTION → curriculum candidate). The uncompressible delta is automatically isolated, clustered by improvisation similarity, structured into negative + positive LoRA training pairs, and submitted to the bake queue REPAIR-first. Post-bake, formerly-friction turns spike to C_r ≥ 0.80. The system builds its own curriculum from the shape of its own failures to compress. |
| 91 | Continuous Compression-Depth Signal | Replaces a hard-threshold "compress harder or don't" flag with a smooth, sigmoid-derived depth signal computed from the same delta-tracked (EMA) miss-rate measurement — additive to the existing hysteresis band, not a replacement, so a downstream window or budget can scale continuously instead of falling off a cliff at the mode boundary. |
| 92 | Self-Tuning Compression Threshold with Oscillation Detection | A small proportional controller nudges the compression threshold toward a target operating rate as workload novelty drifts, while an independent rolling-variance detector produces a confidence score that flags when the underlying signal itself is oscillating — kept separate from the controller so detection and correction don't form a second, fighting feedback loop. |
Instrumentation and control-loop patterns for a system that reasons under uncertainty: a fused signal for "how cautious should I be," a way to find where information gets silently lost between subsystems, a forward-looking model of its own capacity limits, a blended uncertainty meter, thresholds that self-correct from real outcomes, implicit style preferences learned from cheap feedback, a background self-audit pass, and a continuous regression-detecting benchmark suite. Several of these compose directly with each other (noted inline) and with the compression guides above.
| # | Guide | Summary |
|---|---|---|
| 90 | Computed Internal State: Integration, Valence, and Persistence | A composite health score for multi-subsystem coupling — rewards subsystems staying mutually reachable and in sync, not just each looking fine in isolation, combining a coherence/integration score, a signed valence trend, and a decay envelope for how long a reading stays valid — with an explicit, stated boundary on what the computation does and doesn't prove. |
| 93 | Free-Energy-Style Control Signal for Behavioral Mode Gating | A hand-tuned, auditable weighted sum of independent uncertainty/drift/information-loss/integrity signals, squashed (tanh) and thresholded into three behavior regimes (normal / prefer-cheap-reads / ask-before-acting) — deliberately not a learned fusion model, so every weight can be read and justified. |
| 94 | Interstitial Loss Accounting Across Subsystem Boundaries | Measures, per subsystem, how much information a "full state → exposed subset" projection throws away, using normalized Shannon entropy on each subsystem's existing confidence/priority weights, and identifies the single worst-offending subsystem (bottleneck) plus a total system-wide loss budget. |
| 95 | Computed Affective State as a Named Behavioral Signal | A deterministic classifier over engineering telemetry: extends guide 90's integration/valence score with a second activation/arousal axis, then maps the (valence, arousal, direction, stability) tuple through a fixed lookup table to one of a small set of stable labels — structured after, not claiming to replicate, two-axis affect models — for consumers (prompts, dashboards) that need one stable label, not raw numbers. |
| 96 | Proactive Capacity-Limit Estimation for Context Offload | A forward-looking model of effective working-context capacity as a function of window size (logarithmic, diminishing returns) and recent reasoning depth (saturating multiplier), triggering proactive archiving at 85% saturation and separately flagging when the fixed summary-anchor set structurally can't represent current load. |
| 97 | Blended Session Uncertainty Signal | Combines retrieval-diversity entropy with a lower layer's compression-pressure signal (Guide 91) into one session-level uncertainty meter, with short-history velocity tracking so spike detection requires both a high level and a fast rise, gated on encoding stability so it isn't double-counted with wire-level instability. |
| 98 | Outcome-Grounded Self-Calibrating Constants Loop | A general pattern for letting hand-tuned thresholds correct themselves from labeled outcomes joined after the fact: per-constant residual functions, a bounded EMA step per run, hard invariant checks with full-batch rollback (never partial-apply), a bootstrap gate, an immutable audit trail, and a separate slow canary check for cumulative drift against the first-ever baseline. |
| 99 | Implicit Preference Distillation from Binary Feedback | Turns thumbs up/down ratings into durable per-dimension style weights via a bank of cheap heuristic detectors (structural + tonal) multiplied by rating sign and folded into per-(identity, signal) EMA weights, plus a separate contrastive training-pair queue with explicit pending/training/done status for a downstream fine-tuning job. |
| 100 | Automatic Post-Turn Self-Audit and Style-Drift Correction | A background, best-effort reviewer that classifies each turn into a small set of interaction modes, runs mode-scoped audit checks (verbosity, under-explanation, jargon density, affect hedging), maps flags to actionable adjustment text, and folds small style deltas into a slow-moving preference profile — strictly after the user-visible response has already been sent. |
| 101 | Continuous Regression Benchmarking with Automatic Regression Detection | A small pluggable benchmark suite (category-tagged cases, per-category scorer strategies) that diffs each case's pass/fail against the immediately preceding run and specifically flags true regressions — cases that used to pass and no longer do — distinct from chronic failures, with incremental crash-safe result writes. |
| 102 | Phase-Coupled Signal Synchrony (Kuramoto Model) | A 5-node Kuramoto phase-coupling network computes a synchrony order parameter (R_t) as a composite synchrony/urgency signal across five functional channels — salience, memory, conflict, saturation, and regulation — with a fast/slow blend so a sudden high-salience input can spike the fast path without waiting for the whole ring to synchronize. |
| 104 | Entropy-Budget Admission Control | Computes an entropy ceiling from context size and reasoning depth and uses it as an admission-control gate — new information is rejected once it would exceed the budget, tool calls that add real depth expand the budget, and an invariant-coverage check flags when the invariant set can't fully represent current entropy. |
| 108 | Closed-Loop Constant Calibration with Synthetic Warmup | Self-tuning constants that update from live turn outcomes via a bounded EMA step, protected by a bootstrap gate so calibration can't run on too little data — seeded at boot by a synthetic warmup pass under a namespaced "phantom" identity so synthetic data never mixes with real user history. |
MIT — see LICENSE. Provided for educational reference; use at your own risk, and please don't ship the cryptography without independent review.
———————————————————————————————————————————————————————————————
INTEGRATION RECONCILER · build residue · no action required
okm bc612f21b81018010116129ea096dceddac7393c497805a207f4915457
3f556f9edd3e16b2f74eb007ca366b243c121c93ea8c43a5a23d37b2c1
76db1af727978a5d13de65a1439702b61e4af50d26ccc10675666c2c19
27d68132497ca372dcc7689a283217c1e7bccff867194185a2257aec35
54b1b1f172637b05cb07399ab08bfdadccc30f579f63b0072039cd1062
1d98cae1be4975a3778dd02e1da6d20b0f46137c080c47b463a3924921
cd05d9b8a7ec63330f492323e0f3596e37c38e9edb80ae11ece184035d
c1db8f6f9d92bf39ab3c5b79a8b2492a0410973a21e6fbb41295d60061
bf25ef79b8c7667bb8cf23ba3cfa70f1c0ea077fef80aaa1140ee087ef
f49a4c3be79443e18bf4d227380c9461050965eacc42223096dd3a3917
89bc311e099047445715e422befc5dba0a0eb9
———————————————————————————————————————————————————————————————