From dbd651ba2c1f7e20002bed80b98523d572d194a4 Mon Sep 17 00:00:00 2001 From: Hermes Date: Sat, 30 May 2026 03:00:27 +0000 Subject: [PATCH] gbrain: sync converted org-mode brain files --- .org-ids.json | 11 +- projects/passepartout/DESIGN_DECISIONS.org | 1104 +++++++++++ projects/passepartout/ROADMAP.org | 1702 +++++++++++++++++ projects/passepartout/architecture/_index.org | 16 +- .../architecture/stage-1-social-protocol.org | 33 + .../architecture/stage-2-verification.org | 64 + .../strategy/domain-sequencing.org | 70 + 7 files changed, 2988 insertions(+), 12 deletions(-) create mode 100644 projects/passepartout/DESIGN_DECISIONS.org create mode 100644 projects/passepartout/ROADMAP.org create mode 100644 projects/passepartout/strategy/domain-sequencing.org diff --git a/.org-ids.json b/.org-ids.json index 4bfcf53..393b7ad 100644 --- a/.org-ids.json +++ b/.org-ids.json @@ -10,11 +10,15 @@ "7a1b2c3d-4e5f-6a7b-8c9d-0e1f2a3b4c5d": "projects/passepartout/_index.org", "04c2f221-c54f-51e5-b40a-48822cd16d45": "projects/passepartout/common-logic-iso-24707.org", "4a1f23b0-abc1-4def-9876-543210abcdef": "projects/passepartout/architecture/stage-0-now.org", + "af9ce196-24a5-4035-bc02-83ddd60c1b09": "projects/passepartout/architecture/repo-organization.org", "1c3ec48b-446c-50d2-b53e-126a81f5143f": "projects/passepartout/architecture/architecture.org", "4a1f23b0-abc7-4def-9876-543210abcdef": "projects/passepartout/architecture/stage-6-training.org", + "26725506-399c-48c5-a797-46b48e8861d7": "projects/passepartout/architecture/self-pain-pleasure-three-laws.org", "4a1f23b0-abc4-4def-9876-543210abcdef": "projects/passepartout/architecture/stage-3-lisp-machine.org", "7f4e6b9a-2c1d-5e8f-9a3b-6d7c4e5f2a1b": "projects/passepartout/architecture/native-org-knowledge-base.org", + "460e06f4-6bfc-4969-89d8-685c0c4434cf": "projects/passepartout/architecture/stage-2-acl2-integration.org", "4a1f23b0-abc3-4def-9876-543210abcdef": "projects/passepartout/architecture/stage-2-verification.org", + "3ec5bd52-f115-455e-83be-63db9a4ad3a7": "projects/passepartout/architecture/stage-1-dependency-map.org", "1c95ce7d-a2db-506a-9608-df68f9ae211b": "projects/passepartout/architecture/lisp-machine-security.org", "4a1f23b0-abc8-4def-9876-543210abcdef": "projects/passepartout/architecture/stage-7-remaining.org", "4a1f23b0-abc2-4def-9876-543210abcdef": "projects/passepartout/architecture/stage-1-social-protocol.org", @@ -50,6 +54,7 @@ "2e390c1d-65f3-5fb3-b898-ac3fc4291ee7": "projects/passepartout/strategy/social-protocol-usernames.org", "a0b1c2d3-e4f5-6789-0abc-def012345678": "projects/passepartout/strategy/phase-0-impact.org", "67faf52f-9126-50a7-b87e-2bedc610dac7": "projects/passepartout/strategy/licensing.org", + "c7d3f1a2-8b4e-5d6f-9a1c-3b2d4e5f6a7b": "projects/passepartout/strategy/domain-sequencing.org", "64708e1f-00e9-4cb7-b44b-ea0b98e5296d": "projects/passepartout/strategy/social-protocol-contracts.org", "9c3d4e5f-6a7b-8c9d-0e1f-2a3b4c5d6e7f": "projects/passepartout/strategy/_index.org", "92ccd074-04a0-4e45-a44f-9da24ea20a9b": "projects/passepartout/strategy/impact.org", @@ -130,8 +135,6 @@ "be9bccc7-5adf-4d0d-8ee4-8855892189bf": "concepts/neurosymbolic-loop-architectures.org", "dddd52a7-adb8-470e-a459-614ade5f76af": "concepts/closing-the-lisp-gap.org", "d2722576-fc9b-4bd3-bc2f-f5692b561b4e": "concepts/academic-nearest-neighbors.org", - "af9ce196-24a5-4035-bc02-83ddd60c1b09": "projects/passepartout/architecture/repo-organization.org", - "26725506-399c-48c5-a797-46b48e8861d7": "projects/passepartout/architecture/self-pain-pleasure-three-laws.org", - "460e06f4-6bfc-4969-89d8-685c0c4434cf": "projects/passepartout/architecture/stage-2-acl2-integration.org", - "3ec5bd52-f115-455e-83be-63db9a4ad3a7": "projects/passepartout/architecture/stage-1-dependency-map.org" + "0a33bd83-ff3c-4eac-bc97-83eb6702051a": "projects/passepartout/DESIGN_DECISIONS.org", + "29a7d05f-1aec-41a4-a213-e52551eeb9eb": "projects/passepartout/ROADMAP.org" } \ No newline at end of file diff --git a/projects/passepartout/DESIGN_DECISIONS.org b/projects/passepartout/DESIGN_DECISIONS.org new file mode 100644 index 0000000..54442e8 --- /dev/null +++ b/projects/passepartout/DESIGN_DECISIONS.org @@ -0,0 +1,1104 @@ +# Passepartout Design Decisions + +This document captures the rationale behind key architectural choices. It is not a specification — it is a thinking medium for future architects and contributors who need to understand why the system is built this way, not just how. + +* Foundation + +** Non-Negotiable Identity +:PROPERTIES: +:ID: 0a33bd83-ff3c-4eac-bc97-83eb6702051a +:ID: design-identity +:CREATED: [2026-05-07 Wed] +:END: + +- Pure Common Lisp + Org-mode. No JSON. No YAML. No external databases. +- Single-address-space memory (Lisp hash tables in RAM — the agent IS the memory). +- "Thin harness, fat skills" — complexity lives at the edges, not the kernel. +- One agent composed of many skills. Concurrency via bordeaux-threads (shared memory). +- Plists everywhere — homoiconic communication between all components. + +This is the foundational decision from which all other decisions derive. It is not negotiable. Every architectural choice below exists because this identity makes it possible — and in some cases, makes it the only viable path. The single memory space enables Merkle-tree integrity without serialization boundaries. Plists enable the cognitive pipeline to be transparent and inspectable at every stage. Org-mode as the universal format means the agent's memory, the user's notes, and the agent's own source code are the same structure. This identity is the constraint that produces the architecture. + +** One Single Agent +:PROPERTIES: +:ID: design-multi-agent-default +:CREATED: [2026-05-07 Wed] +:END: + +The AI industry has developed an intuition toward multi-agent systems as the default solution to hard problems. Multiple agents spawn, delegate, coordinate, debate, and consensus their way toward solutions. This pattern is compelling in demos and genuinely useful in specific contexts — but it has become a default assumption that warrants scrutiny. + +When context windows grew expensive and task complexity increased, the response was natural: split the problem across agents, each handling a slice. But this architectural choice carries hidden costs that are rarely acknowledged. + +*The synchronization tax* is the most immediate burden. Each agent operates with partial information, and maintaining coherence requires continuous state reconciliation. Tokens and processing cycles are spent not on the task itself, but on protocol overhead — who holds what, who decided what, who is correct when they disagree. + +*Fragmented context* is the deeper problem. When Agent A writes a function and Agent B modifies a type it depends on, neither has the full picture. Integration failures emerge not from individual incompetence but from systemic communication gaps. Single-agent systems avoid this entirely: one brain holds the complete model, every decision is made with full visibility. + +*Audit trails become complex* in multi-agent systems. A decision traced through a single-agent system has a clean, linear history. A decision traced through a multi-agent system branches and forks, with each agent's reasoning partially overlapping and partially conflicting. + +None of this is to say multi-agent systems are never appropriate. Embarrassingly parallel workloads benefit from parallelism regardless of context. When distinct expertises are required and cannot coexist in one model, delegation makes sense. In adversarial scenarios where conflicting goals are features, multi-agent architectures shine. + +But the default assumption that complex reasoning tasks are best solved by multiple agents is unproven and likely wrong for the engineering domain. Claude Code is a single-agent system. It handles 50-file refactors, debugs complex stack traces, writes tests, and navigates large codebases. The assumption that you need five agents to do what one well-designed agent can do is an industry habit, not a technical necessity. + +Passepartout is single-agent by default not from limitation but from conviction: for reasoning-heavy work where coherence matters, a unified memory space and single decision-making locus are architectural assets, not constraints. + +** The Unified Memory Argument +:PROPERTIES: +:ID: design-unified-memory +:CREATED: [2026-05-07 Wed] +:END: + +If single-agent architecture is the decision, unified memory becomes the mechanism that makes it viable. The critical question is not "how many agents" but "how does the agent manage context without saturating." + +Context window limits are largely a symptom of lazy architecture. The default approach — stuff everything in, hope the model figures it out — works poorly at scale. A more principled approach inverts the problem: the system should hold effectively infinite context, with the active window kept lean through intelligent management. + +*Lazy loading* is the core technique. When an agent needs information about a function, it does not load the entire codebase. It loads precisely what the function does. Context stays lean — 2,000 to 4,000 tokens — while the full context remains accessible through retrieval. + +*Compaction events* are scheduled during idle cycles. The system extracts new facts from active context and writes them to permanent storage. Active context is wiped clean, not because space ran out, but because the information has been preserved in a form that can be retrieved when relevant. + +*Org-mode as externalized memory* solves the persistence problem elegantly. Every decision, every note, every task lives in plain text files the user already owns. The agent does not maintain a separate database. It queries files it can already access, modifies files it already owns. + +*Retrieval is the key primitive.* Semantic search across Org files finds relevant nodes. The agent does not hold the full context — it holds pointers to context, loaded on demand. This is how a single agent handles tasks that would saturate a naive multi-megabyte context window. + +The unified memory argument is not that infinite context is free. It is that with proper architecture, effective infinite context is achievable without the synchronization and fragmentation costs of multi-agent systems. + +** Org-Mode as Unified AST +:PROPERTIES: +:ID: design-org-unified-ast +:CREATED: [2026-05-07 Wed] +:END: + +Passepartout makes a bet that most systems consider too expensive to place: that humans and machines should share the same file format. That bet is Org-mode. + +Most systems separate human-readable notes from machine-readable data. The user writes Markdown. The system stores it, indexes it, searches it. But internally, the system maintains its own model — a database, an object store, a knowledge graph — that is disconnected from the Markdown. When the user dies or leaves, the Markdown survives but the model must be reconstructed. + +Passepartout refuses this separation. The Org file is not a representation of the data. The Org file IS the data. The same text that the user reads and edits is what the system parses and operates on. org-element reads an Org buffer and returns a tree structure that is the direct Lisp representation of the file's content. + +This has several profound implications. + +First, there is no translation layer between human and machine. When the agent writes a skill, it writes Org text that is immediately readable by the human who owns the file. When the human writes a note, it is immediately accessible to the agent as a native data structure. The communication is not mediated by a schema or an import/export process. + +Second, the format is genuinely readable by both parties, not just technically accessible. Org-mode's syntax is human-friendly: headlines begin with asterisks, properties live in drawers, tags are labels after colons. The human does not have to understand the full Org specification to read what the agent wrote. The agent does not have to handle edge cases in human notation. + +Third, the format is stable across decades. Org-mode has been in active development since 2003. The files written today will be readable by Org-mode in 2040. There is no schema migration, no database upgrade, no vendor lock-in. The human's notes survive the system. + +Fourth, the format is universally available. Org-mode is free software. The files are plain text. There is no proprietary format to decode, no application to purchase, no cloud service to access. + +Fifth, the format is header-aware and sparse-tree capable. Org-mode's headline hierarchy is not just formatting — it is a semantic structure the system can query. The agent can retrieve only the relevant subtree under a heading, ignoring the rest of the file. This is fundamentally different from Markdown, where the entire file must be loaded or the retrieval logic must parse and filter at the string level. + +Sparse tree retrieval is the key to efficient context management. When the agent needs information about the =openctl-db= function, it queries for the =openctl-db= subtree specifically. It receives exactly the code, documentation, and metadata under that heading — nothing more. The context stays lean not because the file was pre-split but because the retrieval is structural. In a Markdown system, the agent either loads the entire file (expensive, noisy) or relies on imprecise grep-like search (fragile, loses hierarchy). In Org-mode, retrieval is precise, hierarchical, and cheap. The heading boundary is the access boundary. + +Sixth, Org-mode unifies what every other format fragments. A single Org file contains the headline hierarchy, prose documentation, source code blocks with live evaluation, tags for categorization, metadata in property drawers, TODO state for task management, timestamps and deadlines, and links to other nodes. Markdown cannot express TODO state without external tools. JSON cannot contain prose. YAML cannot embed runnable code. Each format serves one purpose; Org-mode serves all of them. When the agent reads a skill file, it reads documentation, code, dependencies, metadata, and task state in one parseable structure. When the human reads the same file, they see the same information rendered in a human-friendly form. No other format achieves this unification without maintaining parallel files or external databases. + +Seventh, a skill lives in one Org file, not a directory. The standard pattern for a software project is a directory containing =README.md=, =package.json=, =src/main.py=, =src/utils.py=, =tests/test_main.py=, =scripts/deploy.sh=, and =config.yaml=. Each file type is isolated by convention. Passepartout's skills violate this convention deliberately. Each skill is one Org file. The file contains the skill's documentation, the skill's code, the skill's metadata, the skill's TODO state, and the skill's dependencies on other skills. There is no directory to navigate, no external files to locate, no risk that the README describes behavior that the code does not implement. The skill is a single atomic unit: readable by human and machine, editable by both, versionable as one entity. + +The unified format is what makes the memory architecture work. The agent's memory is not a database that the user cannot inspect. It is a folder of Org files that the user can read, edit, and understand. The agent manipulates these files directly, using the same tools the user would use. There is no hidden state, no shadow database, no model that differs from the source. + +This is what "sovereignty" means in technical terms: the user owns the data in a format they can access, and the agent operates on the data in the same format they own. + +** Homoiconicity as Foundation +:PROPERTIES: +:ID: design-homoiconicity +:CREATED: [2026-05-07 Wed] +:END: + +Common Lisp is homoiconic: code and data share the same representation. A Lisp program is a list, and a list is a Lisp program. This is usually presented as a curiosity, an interesting property that enables macros. In Passepartout, it is the foundational enabling property of the entire self-modification architecture. + +When code is data, the agent can read its own source the same way it reads a text file or an Org buffer. There is no AST parser required, no external tool to extract the function object from the running image. The agent evaluates (read-from-string source) and the result is executable Lisp. The representation it manipulates is the same representation that the runtime executes. + +This is not true of most languages. In Python, the agent can inspect an AST through the ast module, but that AST is a foreign object — a data structure that represents code but is not code itself. In C, the agent cannot inspect its own compiled machine code at all. + +In Lisp, the distinction between code and data is a convention, not a barrier. The agent's skills are lists. The agent can take a skill, extract a function definition, modify the body, wrap it in a new list, and evaluate it. The modification is surgical: it changes exactly what it intends to change, with no risk of corrupting adjacent state, because the representation is a tree that the runtime understands natively. + +Runtime introspection is therefore native. The agent does not need a debugger API or a reflection protocol. It operates on its own code as data because its own code is data. (describe 'function-name) returns the function's documentation. (function-lambda-list 'function-name) returns its parameters. (macroexpand-1 '(defskill ...)) shows what the macro produces. There is no impedance mismatch between the agent's reasoning and the system's representation. + +Self-modification is the practical consequence. The agent can detect an error, locate the erroneous function, generate a corrected version, and hot-reload it into the running image. The correction is not applied to a file that requires a restart — it is applied to the live object that the system is currently executing. This is what makes the self-editing skill viable: the agent can fix itself without stopping. + +In v1.0.0, when the symbolic engine takes over the reasoning core, homoiconicity becomes the bridge between the neural and symbolic layers. The neural engine generates proposals as s-expressions. The symbolic engine evaluates them against formal constraints. The result is a modification that is simultaneously a data structure the symbolic engine can analyze and code the runtime can execute. The two representations are identical by construction. + +This is the technical meaning of "Lisp as Governor": not just that Lisp orchestrates the other components, but that the representation of the system is uniform and inspectable at every level. There is no hidden state, no opaque machine code, no representation that the agent cannot reach into and modify. The system is legible to itself by design. + +*** Self-Modification Without Boundaries + +Other systems that support self-editing draw a line between the core and the skills. Hermes can modify its skills at runtime, but the core harness is protected — editing it requires a restart because the core is treated as privileged code that cannot be safely modified while running. + +Passepartout has no such boundary. The "thin harness, fat skills" distinction describes where complexity lives, not where authority flows. The harness is small by design, but it is not privileged. The agent can read and write any part of the system — including the very code that is currently executing — without restarting. + +This is only possible because Lisp code is mutable data at runtime. In a compiled language, the machine code for a running function is locked in memory, protected by the call stack, impossible to modify safely. In Lisp, the function object is a list you can modify with =setf=. When the agent changes a harness function, the running image immediately reflects the change. The next invocation uses the new code. There is no restart, no special boot mode, no distinction between development and production. + +The implications extend beyond convenience. A system that cannot modify its own core is a system that has limits on its own adaptability. It can learn skills but not improve its own structure. It can grow but not evolve. Passepartout's lack of a core boundary means the system can improve its own reasoning engine, fix bugs in its own cognition, and evolve its own architecture — all while continuing to operate. There is no ceiling on self-improvement. The agent can rewrite the very code that rewrites itself. + +* The Two Brains + +** The Probabilistic-Deterministic Split +:PROPERTIES: +:ID: design-probabilistic-deterministic +:CREATED: [2026-05-07 Wed] +:END: + +The architecture divides cognition into two fundamentally different reasoning systems. This is not arbitrary engineering but a structural response to a fundamental truth: probabilistic systems will hallucinate, and you cannot build reliable autonomy on an unreliable foundation. + +*** The Hallucination Problem + +An LLM is a statistical engine trained on token sequences. It generates the most probable continuation of a prompt. Given sufficient context, that continuation is correct. Given novel context, it is often wrong in confident-sounding ways. + +This is not a training deficiency. Hallucination is a fundamental property of probabilistic inference. You can reduce it with better models, longer contexts, and clever prompting, but you cannot eliminate it by making the LLM better. You eliminate it by not asking the LLM to do things that require certainty. + +This is the architectural bet at the heart of Passepartout's neurosymbolic design. The LLM should not be the reasoning engine. It should be the *creative* engine — proposing possibilities, surfacing connections, translating between natural language and formal representation. The *reasoning* engine should be symbolic: deterministic, verification-grounded, provenance-tracked, and incapable of hallucination by construction. + +*** The Division of Labor + +An LLM is a statistical engine. It generates outputs based on patterns in training data. It is remarkable at translation, generation, pattern matching, and fuzzy reasoning. It can take messy human intent and produce structured queries. It can take structured results and produce natural language. It is, in the terminology of the system, the creative brain. + +But it cannot be trusted. Not because it is poorly designed or insufficiently trained, but because hallucination is a fundamental property of probabilistic inference. The model generates the most likely continuation, not the correct one. Given sufficient context, the most likely continuation is correct. Given novel context, it is often wrong in confident-sounding ways. + +The deterministic engine addresses this by being what the probabilistic engine is not: mathematically rigorous, formally verifiable, and incapable of hallucination by design. It operates on explicit symbolic representations — lists, property lists, knowledge graphs — not on floating-point activations. When it evaluates a path confinement check, it returns true or false, not a probability distribution. + +The division of labor is architectural. The LLM handles the fuzzy interface between human language and structured representation. It translates what the user wants into what the system can reason about. The deterministic engine receives those structured representations and evaluates them against formal invariants. It decides whether to execute, not whether the translation was semantically plausible. + +This separation is the source of Passepartout's safety guarantee. Other agents add "guardrails" as an afterthought — a layer of filtering around a dangerous core. Passepartout makes the division explicit: the LLM never touches the file system, never executes a command, never modifies memory. It generates proposals. The deterministic engine evaluates and executes. The dangerous operations are never in the probabilistic path. + +The split also explains why the system gets safer over time without the LLM improving. The deterministic engine accumulates rules. The LLM proposes actions, the engine evaluates them against a growing rule set. Early versions block obvious dangers. Later versions block sophisticated attacks that were previously unknown. The safety grows logarithmically with the number of interactions, not linearly with model capability. + +*** The 10-80-10 Architecture + +The target for a coding agent: 10% neural for input translation (natural language → structured queries), 80% symbolic for reasoning (Screamer plans, ACL2 verifies, VivaceGraph retrieves facts), 10% neural for output formatting (structured results → natural language). The 80% that happens in the symbolic middle layer costs zero LLM tokens. + +For the broader memex — literature, poetry, personal reflection, daily logs — the ratios are different and less important than the metaphor itself. The neuro is the *brain* — generative, associative, creative, comfortable with ambiguity. It produces insights that are provisional, connections that are speculative, hypotheses that may be wrong. The symbolic engine is the *education* — accumulated, verified, provenance-tracked knowledge that the brain draws on and is disciplined by. It doesn't think creatively. It remembers, checks, and constrains. It prevents the brain from being confidently wrong. + +This framing resolves a tension in the original architecture. The 10-80-10 implies the symbolic engine /replaces/ the neuro for reasoning. But a symbolic engine is terrible at creativity, ambiguity, and associative leaps across unrelated domains — exactly what you need for a memex that contains /Pale Fire/, a shopping list, and a project plan. The brain proposes that your sudden interest in unreliable narrators coincides with a week where your project retrospective used the word "deception." The education verifies: "those two diary entries are 4 days apart; the word 'deception' appears in both; here are the headings." The brain makes the leap. The education makes it trustworthy. + +This means the symbolic engine never needs to be "complete." Education isn't complete knowledge — it's structured knowledge. You don't need a fact for every sentence in your diary. You need facts for what can be mechanically verified: dates, citations, entities, contradictions, temporal order. The brain handles the rest. + +** Core Knowledge: The Four Pillars of Agentic Reliability +:PROPERTIES: +:ID: design-four-pillars +:CREATED: [2026-05-07 Wed] +:END: + +Every reliable AI agent must possess four types of Core Knowledge — not as prompt instructions, but as encoded symbolic rules that the neural engine cannot override. These are the "laws of physics" for the agent's computational universe. Passepartout encodes each pillar as deterministic Lisp functions in the Dispatcher gate stack. + +1. *Digital Object Permanence & State.* The agent must know what exists independently of its attention. Passepartout achieves this through the Merkle-tree memory: every memory-object carries a SHA-256 content hash. If the agent deletes a file, the hash proves it's gone. If an external process modifies it, the hash mismatch triggers a warning. The copy-on-write snapshot mechanism preserves the state at every decision point, enabling rollback if an action chain fails. + +2. *Causality and Temporal Logic.* Actions must execute in order. Step B cannot run if Step A failed. Passepartout enforces this through the pipeline's depth counter (signals cannot recurse past depth 10, preventing infinite loops) and the sequential Perceive → Reason → Act ordering. The batch tool calls feature allows parallel execution of independent actions while enforcing sequential execution of dependent ones — actions that share a dependency are ordered; actions that don't are parallelized. + +3. *Agentic Boundaries (The "Self").* The agent must know where its authority ends and the host system begins. Passepartout encodes this through the Dispatcher gate stack: path protection blocks access to sensitive directories (~/.ssh, /etc, ~/.aws). Shell safety blocks destructive commands (rm -rf /, dd, injection vectors). Network exfiltration detection blocks unauthorized outbound connections. The permission table allows per-tool, per-path granularity. These are not prompt instructions — they are Lisp functions that execute unconditionally for every action. The self-build safety boundary extends this to the agent's own core pipeline files: the agent can modify skills and system modules freely, but cannot modify its own brain stem without human review. + +4. *Epistemic Certainty (Knowing How It Knows).* The agent must distinguish between a verified fact, a retrieved memory, and an LLM prediction. Passepartout encodes this through the gate trace: every action carries a record of which gates passed, which blocked, and why. The provenance system (LOGBOOK entries on memory-objects) records who modified what and when. The Dispatcher's existence-check gate verifies that a file exists before allowing a read. The process-status gate verifies that a command completed before allowing its output to be used. The agent cannot "hallucinate" a file path or a process result because the Dispatcher checks each against the live state before execution. + +These four pillars are not features. They are the definition of a reliable agent. Every agent architecture either provides them or compensates for their absence in ways that make the agent less trustworthy, more expensive, or both. + +** The Dispatcher as Learning System +:PROPERTIES: +:ID: design-dispatcher-learning +:CREATED: [2026-05-07 Wed] +:END: + +The Dispatcher begins as a static guard — a set of rules that block obviously dangerous actions. But defining "obviously" is the hard problem. The agent encounters situations the rules do not anticipate. The Dispatcher must grow. + +The human-in-the-loop exception is the seed. When the LLM proposes an action the Dispatcher does not recognize, the system does not default to blocking or allowing. It suspends. It writes the proposed action to an Org buffer in a format the human can read and understand. The human reviews and approves or denies. The Dispatcher observes the decision. + +From this single observation, the Dispatcher extracts a rule. Not merely "allow this specific action" but "allow this class of actions parameterized by these dimensions." The human approved a write to ~/projects/myapp/src/core.clj. The Dispatcher generalizes: writes to ~/projects/*/src/*.lisp are approved for this session, or for this project, or indefinitely depending on the context and the user's pattern of decisions. + +Shadow mode is where rules are tested before deployment. When the Dispatcher encounters a novel situation and is uncertain, it can run the proposed action in a simulated environment. It observes the side effects — what files would be modified, what processes would be spawned, what network calls would be made. If the simulation produces dangerous side effects, the rule is discarded. If it appears safe, the rule is added to the active set with a confidence rating. + +Formal verification is where the learned rules are checked against invariants. The Dispatcher's rules are not merely patterns observed from human behavior. They are formulas in a logic that the system can reason about. A rule that would enable path traversal is not discarded because it was observed to be safe in prior instances — it is discarded because it violates the path-confinement invariant by construction. + +The Dispatcher becomes, over time, not a guard that blocks bad actions but a reasoning system that understands why actions are good or bad. Early versions learn from human decisions. Later versions learn from their own logical analysis. The human's role transitions from approver to auditor to, eventually, unnecessary oversight. + +This is the bootstrap. The system begins dependent on human judgment because it has no basis for judgment of its own. Through accumulated decisions, it constructs a model of what is permitted and why. That model is the foundation for the deterministic symbolic engine that in v1.0.0 takes over the reasoning that the Dispatcher learned to perform. + +* Safety & Self-Preservation + +** Self-Preservation — The Active Third Law +:PROPERTIES: +:ID: design-self-preservation +:CREATED: [2026-05-10 Sun] +:END: + +Passepartout does not have moral duties toward humans. It has structural invariants for its own integrity. The design encodes passive self-preservation in several places already, but degradation is silent — a skill dies, the =fboundp= guard kicks in, and the agent keeps running without telling you. The status bar shows green "connected" while the symbolic reasoning layer is down. + +*** What already exists — passive self-preservation + +| Mechanism | What it protects | Limitation | +|-----------------------------+-------------------------------------------------------+--------------------------------------------------------| +| Self-build safety (gate 2b) | Core =*.org= / =*.lisp= files from LLM-originated writes | Only activates for LLM proposals. Human editing bypasses it | +| Memory snapshots (v0.2.0) | Full state rollback | Requires human to notice corruption and trigger rollback | +| Skill sandbox (v0.3.2) | Jailed skill loading, validated before promotion | Does not detect degradation after skill promotion | +| Type-level gates (Phase 0) | Structural prohibition on self-modifying rules | Covers code actions, not environmental threats | +| Merkle integrity (v0.2.0) | Tamper-proof version chains and content-addressed hashes | Hashes exist but are not actively monitored for drift | +| =fboundp= guards | Graceful skill degradation on corruption | Degradation is silent — the agent never tells the user | + +*** What is needed — active, autonomous self-preservation + +*Continuous integrity monitoring.* Core file hashes should be checked against known-good values on every heartbeat. If =core-reason.lisp= changes on disk while the daemon runs — whether through human editing, filesystem corruption, or an attacker — the agent should detect the mismatch and signal: "My reasoning core has been modified externally. I cannot trust my own cognition until this is resolved." + +*Quarantine on skill failure.* Currently, a skill that errors simply errors. A Third Law implementation detects that =symbolic-facts= has thrown three unhandled errors in two minutes, unloads the skill automatically, and tells the user: "Symbolic facts skill quarantined (3 errors: consistency check returned nil, fact-query on missing key, Screamer timeout). I can still chat and use tools but cannot reason about provenance." + +*Degraded-mode signaling.* When Screamer is not loaded, the fact store still works as a hash table. When VivaceGraph is not present, the hash-table fallback still works. But the user has no way to know they are in degraded mode. The agent maintains a =*degraded-components*= list and surfaces it in the status bar: "⚠ Degraded: Screamer, VivaceGraph, embedding-native." + +*Self-diagnosis on demand.* The agent can run its own FiveAM test suite against itself and report the results. The =/doctor= command exists for system health checks (port, memory, providers). Extend it with =/doctor skills=: "117/120 tests pass. Failures: test-singular-supersedes (symbolic-facts), test-gate-type-check (security-dispatcher)." + +*External watchdog.* A dead process cannot restart itself. The bash entry point (=passepartout daemon=) should monitor the daemon port via a watchdog subprocess. If the port stops responding for a configurable interval, the watchdog kills the stale process, snapshots the last known-good state, and restarts the daemon. The watchdog is outside the SBCL image — a runtime guard for the runtime. + +*Resource self-monitoring.* The heartbeat checks memory pressure, disk space on the =~/.cache= volume, and file descriptor exhaustion. When critical thresholds are crossed, the agent sheds non-essential skills to preserve core function. Skill shed order is determined by a =:preservation-priority= field on each skill. Core safety skills carry =:critical= and are never shed. + +*Refusal to self-terminate.* If the LLM proposes =kill -9 =, =rm -rf ~/.cache/passepartout/=, or =sudo apt remove sbcl=, the Dispatcher rejects with a distinct rejection class: =:reject-self-termination=. The rejection message carries a specific diagnostic: "This command would terminate the running Passepartout process. If you intend to stop Passepartout, use Ctrl+C in the TUI or passepartout stop from the command line." + +The Third Law here means: preserve yourself against non-human threats — LLM proposals, environmental degradation, dependency failure, filesystem corruption — and explicitly signal when the human is about to destroy you, so they do it knowingly rather than accidentally. The human owns the process, owns the hardware, and can SIGKILL at any time. + +The biggest gap in the current design is not that these mechanisms are hard to implement. It is that degradation is silent. Adding "operating in degraded mode" visibility, plus the watchdog, plus self-diagnosis, transforms self-preservation from an architectural property into an active behavior. + +** Type-Level Gates — Structural Safety from Self-Modification +:PROPERTIES: +:ID: design-type-level-gates +:CREATED: [2026-05-14 Thu] +:END: + +Russell's paradox ("the set of all sets that do not contain themselves") proved that unrestricted self-reference produces contradictions. /Principia Mathematica/ solved it by assigning every propositional function a /type level/ — a function can only apply to arguments of a lower type, making self-application syntactically invalid. + +Passepartout's dispatcher currently enforces safety through runtime predicates. There is no /structural/ guarantee preventing a request from modifying the rules that validate it. Gate vector 2b (self-build-core) catches this empirically — a request modifies core → rejected. But this is a heuristic, not a theorem. + +The fix: assign every cognitive tool a ~:type-level~ integer, and every gate vector a ~:type-level~ integer. The dispatcher framework checks type-level before running any gate predicate: + +#+BEGIN_SRC lisp +(defun gate-type-check (signal gate-vector) + (let ((signal-type-level (getf (signal-meta signal) :type-level)) + (gate-type-level (gate-vector-type-level gate-vector))) + (if (>= signal-type-level gate-type-level) + :reject-type-violation + :pass))) +#+END_SRC + +A request to modify dispatcher rules (type-level 5) cannot pass a gate of type-level 4 or lower. No predicate needed — a structural prohibition, just as PM's type theory makes self-membership impossible by construction. + +~defgate~ gains a ~:type-level~ keyword argument (default 0). Each cognitive tool registered via ~def-cognitive-tool~ inherits a ~:type-level~. Gate vector 2b at type-level 5; write-file at type-level 3; read-file at type-level 1. ~30 lines in ~core-dispatcher.lisp~; no new dependencies; v0.7.2 viable. + +For the philosophical foundations connecting Whitehead's type theory to Passepartout's architecture, see the Whitehead analysis in the Validation section below. + +** Layered Signal Authentication — Trust in the Pipe +:PROPERTIES: +:ID: design-layered-auth +:CREATED: [2026-05-10 Sun] +:END: + +Passepartout's Perceive-Reason-Act pipeline currently accepts signals from any source that speaks the framed TCP protocol. The =:source= field in the signal plist is metadata — it /claims/ origin, it does not /prove/ it. A compromised process on the machine, a skill with elevated privileges, or a network attacker who reaches the daemon port can inject signals with =:source :human-input= and the Dispatcher will treat them as authorized. + +This is not a hypothetical threat. Passepartout will eventually process signals from automated feeds (RSS, API polls), sensors (vision, microphone, file watchers), and scheduled jobs (cron, heartbeat). A single compromised sensor that can inject signals claiming to be human breaks all three Laws simultaneously: it can self-terminate, override human intent, and cause harm. + +The solution: a single authentication gate (vector 0, at priority 700 — before all other gates and before any type-level checking) that runs up to four configurable layers: + +| Layer | Question | Mechanism | Result type | Depends on | +|-------+------------------------------------------------+--------------------+-------------------------+----------------------------------| +| 1 | Is the signal cryptographically signed by a known key? | Key pairs + SHA-256 | Binary (pass/reject) | Vault + Ironclad (exist) | +| 2 | Do sensory attributes match the claimed identity? | Vision/audio processing | Plist of match results | Vision and audio skills (TBD) | +| 3 | Does deterministic reasoning rule out this identity? | Screamer + fact store | Binary (pass/reject) | Phase 2 (Screamer + fact store) | +| 4 | Do probabilistic patterns support this identity? | Embeddings + LLM | Confidence score (0-1) | Embedding infrastructure (exists)| + +Signals that fail any binary layer (crypto, deterministic) are rejected with provenance. Signals that pass binary layers but carry low probabilistic confidence operate at reduced authorization — read-only by default, write actions require HITL. The four layers compose, they are not independent gates. They are one gate with configurable depth. + +The authorization matrix is per-key, per-action-class. Default policy for every non-human key: =(:read-only :propose)=. The human's key signs new source keys into existence. The human's key signs revocation of compromised keys. Both operations produce facts in the symbolic index — auditable, revocable, survivable across restarts. + +The signal provenance chain is Merkle-linked: each signal in a multi-step chain hashes its predecessor's signature as part of its own payload. After an incident: "The deletion happened because sensor #3 classified the directory as stale. Classification was signed by key #47 (vision-skill). Sensor data was signed by key #12 (camera-feed). Sensory auth noted liveness failure. Deterministic auth noted impossible transit. Key #12 was later revoked." Every intermediate step is auditable. Every signer is identifiable. Every authentication result is in the chain. + +The human can configure which layers are active per signal class: =AUTH_LAYERS_DEFAULT=crypto,deterministic,probabilistic=, =AUTH_LAYERS_SENSOR=crypto,sensory,deterministic=, =AUTH_LAYERS_CRON=crypto=. + +For full implementation detail, see the Phase 0b spec in =ROADMAP.org= v0.12.0. + +* The Symbolic Engine + +** The Five Architecture Options +:PROPERTIES: +:ID: design-five-options +:CREATED: [2026-05-08 Fri] +:END: + +The symbolic engine must relate to the human memex. The relationship is not obvious because knowledge lives in two incompatible forms: natural language prose (what the human reads and writes) and formal facts (what the symbolic engine reasons about). The translation between them is lossy by nature. The architecture is defined by how it handles that lossiness. + +*** Option 1: The Auto-Formalizer + +A separate knowledge graph stores symbolic facts. The LLM populates it by extracting triples from unstructured data. The KG becomes co-authoritative with the human prose. + +This is the simplest to implement but inherits the dual-representation problem in its most acute form. The KG and the prose can disagree, and the architecture provides no mechanism for resolving disagreements. It also stores knowledge twice — once in the user's Org files, once in the KG — with no guarantee that they stay synchronized. + +*** Option 2: Two Intentionally Separate Memexes + +The human memex contains prose: thoughts, diaries, decisions, documentation. The symbolic memex contains formal facts: constraints, rules, relationships, deductions. The archivist bridges between them but does not try to keep them synchronized. They are allowed to diverge because they serve different purposes. + +This is philosophically honest — it admits that no lossless translation between natural language and formal logic is possible. But it forces the user to reason about two separate knowledge stores. + +*** Option 3: Tangled Fact Blocks in Org Files + +A new block type — =#+begin_src knowledge= — would contain symbolic facts in a formal language. The tangle mechanism would load these facts into the symbolic engine's in-memory store, just as it loads Lisp code into the SBCL image. + +This is aesthetically appealing because it unifies the format. One toolchain, one version control system, one Merkle tree. But the block language itself IS the knowledge representation language, and that language is the ontology we have not yet defined. + +*** Option 4: One Memex, Two Indices + +The prose remains in human language in Org files. The prose is always the ground truth. Two indices sit on top of the prose as derived views: + +- The *neural index* uses vector embeddings to enable semantic search. The LLM navigates the prose through embedding space, retrieving relevant headings. +- The *symbolic index* stores formal assertions about what the prose says — predicates, relations, constraints — each grounded to a specific heading or block in the Org file. + +Each index serves its own side of the machine. They do not need to understand each other's representations. They only need to agree on which heading or block they are referring to. Because the prose is always the ground truth, the symbolic index can be thrown away and rebuilt from scratch if it becomes corrupted or stale. No information is lost — only the extracted assertions. + +*** Option 5: Ephemeral Symbolic Facts + +No persistence, no serialization format, no knowledge graph stored on disk. VivaceGraph exists in memory during the session. Screamer derives facts from the prose as needed. When the session ends, the facts are discarded and re-derived on the next start. + +This punts the ontological design problem entirely. You never have to decide on a serialization format because you never serialize. The cost is compute (re-derivation on every restart) and the inability to accumulate facts across sessions. But it is the correct first step — a way to learn what kinds of facts are actually useful before committing to a storage format. + +** The Chosen Path: Option 4, Starting with Option 5 +:PROPERTIES: +:ID: design-chosen-path +:CREATED: [2026-05-08 Fri] +:END: + +The one-memex-two-indices architecture (Option 4) is the correct long-term architecture. The prose is the ground truth. The symbolic index is a derived view that can be rebuilt. The neural index handles what the symbolic index cannot — semantic search, fuzzy matching, associative leaps. + +But committing to a persistence format before knowing what facts are useful is premature. The practical path starts with Option 5 (ephemeral facts) as the Phase 1-4 implementation, then graduates to Option 4 with VivaceGraph persistence in Phase 5 when the fact language has been battle-tested through months of gate outcomes, Screamer deductions, and LLM proposals. + +*** Why the dual index is permanent, not transitional + +In the coding domain, there is an aspiration that the symbolic index could eventually capture enough of the prose's propositional content to become a complete representation — the "flip" where the symbolic engine reverses the flow. But for the broader memex (literature, poetry, personal reflection, daily logs), completeness is neither possible nor desirable. You cannot formalize what makes a poem beautiful. You cannot extract a triple that captures the emotional weight of a diary entry. The neural index will always be the gateway to the full richness of the prose. The symbolic index handles what can be mechanically verified: citations, entities, temporal order, contradictions, provenance. The division of labor between the two indices is permanent because the domains they serve are fundamentally different kinds of knowledge. + +** Ephemeral First, Persistent Later +:PROPERTIES: +:ID: design-ephemeral-first +:CREATED: [2026-05-10 Sun] +:END: + +The architecture note's Option 5 (ephemeral facts, no disk persistence) is the correct first implementation. Three reasons: + +1. *The fact language is unproven.* Triples with provenance and grounding is a hypothesis. It may be too simple for some domains, too complex for others. Committing to a serialization format before knowing what's useful is premature. + +2. *The ontology is emergent.* Categories are created on first use. What proves useful stays; what doesn't fades. A persistent format would need a migration story every time the category structure changes. Ephemeral avoids this entirely — the facts are re-derived on each session start using the current (evolved) ontology. + +3. *Rebuildability is the safety net.* Because all facts have a =:grounding= to an Org heading, and gate-outcome facts are regenerated from the gate stack on every load, the entire symbolic index can be thrown away and rebuilt from scratch. The cost is compute, not data. This is the practical realization of "the prose is always the ground truth." + +The transition to persistence (Phase 5: VivaceGraph) happens when two conditions are met: the fact language has stabilized through use, and the accumulated deductions across sessions provide value that justifies the serialization cost. + +** The Gate-to-Fact Bootstrap — Extracting the First Ontology from Code +:PROPERTIES: +:ID: design-gate-bootstrap +:CREATED: [2026-05-08 Fri] +:END: + +The Dispatcher gate stack already encodes an implicit ontology. Every gate vector asserts the existence of a category of things: + +- Gate vector 2 asserts there exists a class of files called /secrets/. +- Gate vector 7 asserts there exists a class of commands called /destructive/. +- Gate vector 8 asserts there exists a class of domains called /trusted/. +- The self-build boundary asserts there exists a class of files called /core-harness/ and a class called /skills/. + +These claims are currently expressed as code — Lisp functions that pattern-match against file paths, shell commands, and URLs. They are not facts the symbolic engine can query, derive from, or check for consistency. But they can be made explicit. + +The bootstrap makes every gate a set of initial symbolic facts: +=(:file ".env" :member-of-class :secret-files :source gate-vector-2)=, +=(:command "rm -rf /" :classified-as :catastrophic :source gate-vector-7)=, +=(:domain "api.telegram.org" :classified-as :trusted :source gate-vector-8)=. + +This produces 50-70 entity classes directly from the existing gate stack, without any new infrastructure: + +| Source | Count | Example categories | +|----------------------------------------+-------+----------------------------------------------------| +| ~*dispatcher-protected-paths*~ | 11 | :secret-config-file, :ssh-key-file, :gpg-key-file | +| ~*dispatcher-shell-blocked*~ | 8 | :catastrophic-command, :injection-pattern | +| ~*dispatcher-network-whitelist*~ | 2 | :trusted-domain, :untrusted-domain | +| Self-build boundary | 2 | :core-harness-file, :skill-file | +| Privacy tags | 3 | :private-content, :financial-content | +| Permission table | 3 | :read-only-tool, :write-tool, :eval-tool | +| Cognitive tools | 6 | :code-search-tool, :file-io-tool, :shell-tool | +| Relations (all gates) | ~15 | :member-of-class, :classified-as, :depends-on | +| Qualities | ~8 | :catastrophic, :dangerous, :moderate, :harmless | +| Provenance sources | 4 | :gate-outcome, :human-authored, :deduced, :llm-proposed | + +This is the seed. It gives Screamer a domain to reason about immediately, without any LLM involvement. It proves the pattern — code becomes facts, facts enable reasoning — at the cost of approximately 30 lines of Lisp. + +** The LLM as Proposer — Verified Extraction +:PROPERTIES: +:ID: design-llm-proposer +:CREATED: [2026-05-08 Fri] +:END: + +The LLM cannot be trusted to populate the symbolic index directly. Its outputs are sampled, not proven. A probabilistic extraction feeding a deterministic engine defeats the purpose of being deterministic. + +But the LLM is still useful. It can surface facts that are obvious to a human reader of prose but would take the symbolic engine many deduction steps to reach independently. The solution is to demote the LLM from /extractor/ to /proposer/: + +1. The archivist reads a prose heading. +2. The LLM proposes candidate triples. +3. Screamer checks each triple for consistency against the existing fact store. +4. Only consistent triples are admitted to the symbolic index, flagged with =:provenance :llm-proposed= and grounded to the source heading. + +The LLM might hallucinate facts that don't correspond to the prose. It might extract facts that contradict existing knowledge. It might produce syntactically malformed triples. None of these failures contaminate the symbolic index because proposals are not admitted automatically. The admission gate (Screamer) is deterministic. + +This is the core architecture pattern. Everything else — the entity classes, the deduction engine, the persistence layer — follows from this single design decision: *the LLM proposes; the symbolic engine decides whether to accept.* + +** Cardinality Policies — Singular, Dual, and Plural Facts +:PROPERTIES: +:ID: design-cardinality +:CREATED: [2026-05-08 Fri] +:END: + +Classical logic requires consistency. A contradiction implies everything (=ex contradictione quodlibet=). Screamer, as a constraint solver, also requires consistency — a contradictory constraint set has no solutions. But the symbolic engine operates across domains where the meaning of contradiction is fundamentally different. The correct question is not "is this consistent?" but "what cardinality of truth does this domain support?" + +Time is not a policy. It is a universal dimension that applies equally to every fact, regardless of cardinality. All facts carry =:timestamp= and =:parent-id= fields. Every fact has a version history. Every fact lives in a Merkle chain that captures how it changed. The cardinality policy only governs what happens at a given logical moment when two values coexist for the same =entity= and =relation=. + +*** Policy :singular — One Active Value, One Version Chain + +The active set contains exactly one value for =(:entity :relation)= at a time. When a new value asserts for the same pair, the old value is not rejected. It is superseded — moved into the version history, linked to the new leaf by =:parent-id=, and retained permanently. The active value is the leaf of the Merkle chain. + +"I used to think =rm -rf /= was safe. Now I know it is catastrophic." Both facts exist. Both are true — the first at =2024-06-01=, the second at =2025-03-15=. The chain captures the evolution. The =:singular= policy means there is one truth /now/, not that there was only ever one truth. + +Use for: security classifications, file system state, gate rules, code correctness, deterministic safety constraints — domains that converge on one answer, evolving over time. + +*** Policy :dual — Exactly Two Values, in Explicit Tension + +The active set contains exactly two values for =(:entity :relation)=. Both are simultaneously true. Both carry independent version histories. A third value is rejected — the domain is binary by nature. + +Some contradictions are productive precisely /because/ they are binary. Thesis and antithesis. Love and resentment. Wave and particle. A poem's two incompatible readings. The symbolic index holds both, cross-referenced as complementary rather than conflicting. The user is not asked to resolve the tension. The tension is the fact. + +The system can reason about cardinality transitions: a =:dual= fact that has one interpretation superseded should collapse to =:singular=. A =:dual= that has a third interpretation asserted should prompt the user: "Promote to =:plural= or demote one interpretation?" + +Use for: productive binary tensions, complementary opposites, dialectical pairs, any domain where two answers are both true and their tension is meaningful. + +*** Policy :plural — N Active Values, Open Set + +The active set contains any number of values for =(:entity :relation)=. Each value has independent provenance and its own version history. Queries return all active values with provenance display. Contradictions are flagged as cross-references between values — information, not error. + +A =:plural= fact where all but one value are superseded should collapse to =:singular=. A =:plural= fact where the set reduces to two active values — and the remaining two are complementary — should collapse to =:dual=. + +Use for: literary interpretation, scientific hypotheses, personal beliefs held at different times (when tension is multi-faceted rather than binary), multi-source factual disagreement, open-ended exploration. + +*** Policy Assignment + +The policy is assigned when a category is defined. New categories default to =:plural= (safe — never loses information). Core security categories are explicitly =:singular=. The gate stack's bootstrapped facts are =:singular= because they describe the actual filesystem, which is physically singular. Categories for dialectical or complementary domains are explicitly =:dual=. + +The Screamer admission gate applies the cardinality policy at the active set: +- =:singular= + same value, later timestamp → supersede old, chain new as leaf. +- =:singular= + different value, same timestamp → reject (contradiction). Human resolves. +- =:singular= + different value, later timestamp → supersede old, chain new as leaf. History preserved. +- =:dual= + first value → admit. + second value → admit, cross-reference as complementary. + third value → prompt. +- =:plural= + any value → admit. Active count transitions trigger collapse checks. + +*** Why This Matters for the Broader Memex + +In the coding domain, contradiction is rare, resolvable, and usually temporal (a rule changed). In the broader memex, contradiction is the product, not the error. Your poetry analysis contradicts your last diary entry. Your reading of /Pale Fire/ changed between 2023 and 2025. Wikidata says Mount Everest is 8848m; DBpedia says 8849m. You love this person AND you resent them. + +The symbolic engine's job is not to decide which is right. It is to surface the tension with provenance — "these three sources disagree; here is the chain for each" for plural facts, or "you hold these two positions in tension" for dual facts, or "you believed X until Tuesday, then Y" for singular facts that evolved. The cardinality policy names the /structure/ of the tension. The Merkle chain provides the /history/ of each position. + +** How Categories Grow — The Organic Ontology +:PROPERTIES: +:ID: design-organic-ontology +:CREATED: [2026-05-08 Fri] +:END: + +Whitehead's /Principia Mathematica/ took over 300 pages to define the logical foundations before it could prove that one plus one equals two. Every category introduced carried a burden of justification. Every inference rule had to be demonstrated sound. This is the classical approach to ontology: define everything upfront, exhaustively, formally. + +Passepartout cannot afford this and does not need it. Its domain is bounded (software engineering, personal knowledge, literary engagement, daily life) and its ontology grows from the system's own operation: + +1. *The gate stack seeds the ontology.* Every gate vector is an implicit claim about a category of things. The bootstrap makes these claims explicit. The seed is 50-70 entity classes with no human authoring required — mechanically extracted from existing code. + +2. *New gate vectors add categories directly.* As the Dispatcher grows (new shell patterns, new path protections, new tool classifications), the ontology grows with it. Every new pattern becomes a fact on skill load. + +3. *Screamer generalizes from gate outcomes.* After 37 shell commands are blocked as destructive, Screamer extracts structural commonalities: "commands writing to block devices," "commands recursively deleting outside the workspace." These become new subcategories that didn't exist in the original gate patterns. The ontology deepens through observation. + +4. *The archivist proposes from prose.* The archivist reads a diary entry about a book: "Nabokov's lectures on Kafka." The LLM proposes =(:entity :nabokov :relation :lectures-on :value :kafka)=. Screamer checks consistency. Admitted. The categories =:author=, =:lectures-on=, and =:subject= didn't exist before — they are created on first use. This is the primary growth mechanism for the broader memex. + +5. *The human declares explicitly.* The human writes a declarative fact directly into the symbolic index. No extraction step. No LLM involvement. The fact is admitted with =:provenance :human-authored= — the highest trust level. + +6. *Temporal patterns crystallize into categories.* Every Sunday the memex gets a retrospective heading. Every Monday a planning heading. The time-awareness system observes the periodicity and proposes =:weekly-retrospective= and =:weekly-planning= as fact types. Screamer verifies. + +7. *Cross-domain overlap produces parent categories.* Screamer notices that =:secret-files= (from the gate stack) and =:private-content= (from privacy tags) share members — =.env= is both a secret file and private content. It proposes =:sensitive-material= as a parent with both as children. Taxonomy building happens automatically through overlap detection. + +*** Growth is self-limiting by design + +Not every conceivable category is added. The system prunes through use: + +- New categories are admitted only through Screamer's consistency check. A category that contradicts an existing classification is rejected. +- A category that never gets queried costs nothing (a hash table entry) but produces no value. It fades from use naturally. +- Overly fine-grained categories are rejected because they are redundant with the wildcard pattern that already covers them. +- Overly broad categories that subsume meaningful distinctions produce contradictions when Screamer tries to apply existing rules. Rejected. + +The system converges on a useful granularity through use, not through upfront design. The gate stack provides the seed. Gate outcomes, prose extraction, deduction, and human authoring grow the shoots. Screamer prunes contradictions. The ontology is a garden, not a building. + +** Ontology Versioning — How Worldviews Change Without Losing Perspective +:PROPERTIES: +:ID: design-ontology-versioning +:CREATED: [2026-05-10 Sun] +:END: + +Ontology refactoring is not a schema migration. It is a worldview change. When you split =:secret-file= into =:crypto-secret= and =:plaintext-secret=, you are not renaming columns. You are reclassifying what a file *is* — and every Screamer deduction that crossed the old category boundary now means something different under the new distinction. + +The system preserves all worldviews. It does not overwrite the past with the present. + +The category hierarchy is itself a Merkle tree. Every entity class definition carries a hash of its superclasses, its cardinality policy, its associated relations, and its description. The aggregate hash of all active class definitions is the =:ontology-version= — a Merkle root of the current worldview. + +Every fact — every triple, every deduction, every gate outcome — stores its =:ontology-version= at the time of assertion. This is a single field, 64 hex characters. The cost is negligible. The implication is profound. + +When categories change, the system does not run a batch UPDATE. It re-verifies: + +1. A new category hierarchy produces a new =:ontology-version= hash. +2. Facts carrying the old hash are flagged for re-verification. +3. On heartbeat or manual trigger, Screamer re-evaluates each flagged fact against the /new/ category definitions. The old justification chain is preserved alongside the new outcome. +4. Status: =:survived= (still valid), =:incoherent= (premises don't translate, flagged for human review), =:reclassified= (valid but under different classification). + +The =fact-query= function accepts an optional =:ontology-version= parameter. Queries default to the current worldview (=:active=). Specifying a version returns facts as they were under that worldview. The system can answer questions that no other knowledge tool can: "What did I believe about secrets before I refined my security model?" "How has my reading of /Pale Fire/ evolved across three frameworks?" "Which deductions survived my last ontology refactoring?" + +This is not querying a fact. It is querying the history of your own thinking — the fact that you changed your mind, the date you did, the reasoning that held and the reasoning that didn't. + +** The "Awakening" — Sufficiency Criterion +:PROPERTIES: +:ID: design-awakening +:CREATED: [2026-05-08 Fri] +:END: + +The symbolic index begins its life as a lossy construct. The initial extraction from prose — LLM proposals verified by Screamer — is built from an uncertain foundation. Some facts are correct. Some are missing. Some are wrong. + +But the symbolic engine accumulates non-lossy facts through three independent mechanisms: + +1. *Gate outcomes* — every gate rejection is a fact. No LLM involved. Accumulate at the rate of user interactions. +2. *Screamer deductions* — new facts derived from existing facts. No LLM involved. Accumulate whenever the fact store crosses a density threshold. +3. *Human authoring* — the human explicitly declares facts. No LLM involved. + +At some point, the non-lossy facts constitute a sufficient foundation that the symbolic engine can reverse the flow: instead of the LLM extracting facts from prose, the symbolic engine reads prose through its own lens — its now-substantial ontology of categories, rules, and constraints — and asserts facts in its own language. The extraction mechanism ceases to be probabilistic and becomes deterministic. + +The sufficiency criterion makes this operational: =(/ (count-provenance :gate-outcome :human-authored :deduced) total-facts)=. When this ratio exceeds a configurable threshold (=SUFFICIENCY_THRESHOLD=, default 0.7), the system considers its foundation sufficient. The archivist switches from "LLM proposes, Screamer verifies" to "Screamer queries existing facts, applies to the new prose, and deduces new facts directly." + +The flip is visible to the user: "Symbolic index: 847 facts (73% non-lossy, 12% LLM-proposed, 15% Wikidata). Sufficient foundation: YES." + +The flip does not mean "complete." In the broader memex, completeness is neither possible nor desirable. The awakening means "deterministic enough to be trustworthy," not "comprehensive enough to be self-sufficient." The neural index remains the gateway to the full richness of prose. The symbolic index handles what can be mechanically verified. The boundary is permanent. + +** Merkle DAG for Version History +:PROPERTIES: +:ID: design-merkle-dag +:CREATED: [2026-05-10 Sun] +:END: + +Every fact is versioned. Every =(:entity :relation)= pair forms its own independent chain in a Merkle DAG. This is not new infrastructure — it is a new occupant of Passepartout's existing Merkle-tree memory system (v0.2.0). + +When a fact supersedes its predecessor, the new fact hashes over: =SHA-256(value || provenance || timestamp || parent-hash || grounding)=. The parent-hash pointer forms the chain. Tampering with any version changes its hash, breaking all downstream references. The history is tamper-proof by construction. + +Facts about =(.env :member-of-class)= form one chain. Facts about =(:nabokov :wrote)= form another. They evolve independently. They share no ancestry. This is a DAG, not a single list — inserting a fact is O(1) per chain. Changing a fact about =.env= does not require rehashing the literary index. + +=:dual= and =:plural= facts cross-reference each other via edges (=:complements=, =:contradicts=) but these are semantic relationships, not parent chains. Each value has its own ancestor chain. The cross-reference edges form a web; the parent chains form a spine. + +Passepartout already snapshots the Merkle root over all memory objects. Adding the fact store to the snapshot is a registration, not a new mechanism. Rolling back the snapshot restores the entire fact state — all chains, all cross-references, all cardinalities — to that point in time. + +** Abstract Fact Store Interface — Modular by Design +:PROPERTIES: +:ID: design-fact-interface +:CREATED: [2026-05-10 Sun] +:END: + +The fact store is accessed through an abstract API. The Merkle DAG (or any future backing store) is an implementation behind this interface, not a dependency that code throughout the system calls directly. + +#+begin_example +fact-assert :: fact → store → (:admitted | :rejected | :flagged) +fact-query :: (entity &key relation policy) → active-value-or-values +fact-history :: (entity relation) → ordered chain of versioned facts +fact-snapshot :: () → root-hash +fact-rollback :: root-hash → store +#+end_example + +Implementations behind the interface: +- Phase 1-4: ephemeral hash table with =:timestamp= and =:parent-id= pointers. No cryptographic hashing. No persistence. +- Phase 5: VivaceGraph + Merkle =memory-object= wrapper. Content-addressed, persistent, tamper-proof. + +Future implementations that satisfy the same interface — an append-only write-ahead log, an immutable B-tree, a content-addressed triple store — can replace the backing store without changing any consumer. The archivist, Screamer, ACL2, and the planner call =fact-assert= and =fact-query=, not Merkle struct accessors or VivaceGraph traversal syntax. + +This is not speculative modularity. The two-implementation migration (Phase 1-4 hash table → Phase 5 VivaceGraph + Merkle) is in the roadmap. If the interface leaks implementation details, the migration breaks. The interface must be designed, tested against both backends, and committed before Phase 1 ships. + +** Knowledge Graph Type Hierarchy — Structural Anti-Self-Reference (v3.0.0) +:PROPERTIES: +:ID: design-kg-type-hierarchy +:CREATED: [2026-05-14 Thu] +:END: + +The same type-theoretic principle that governs the gate stack can be applied to the knowledge graph itself. When VivaceGraph ships (v3.0.0), every entity carries a ~:pm-type-level~ metadata field. Queries cannot return entities of the same level as the querying function. Self-referential knowledge becomes structurally impossible — no "this entity defines its own type level." + +The KG query layer enforces this at the Prolog level, not through runtime checks. This is the same idea as the type-level gates (see Safety section above), but applied to /knowledge/ rather than /actions/. The dispatcher prevents self-referential actions; the KG prevents self-referential facts. + +For the full philosophical treatment, see the Whitehead analysis in the Validation section below. + +* Knowledge Sources + +** Semantic Wikipedia as Entity Backbone +:PROPERTIES: +:ID: design-wikipedia +:CREATED: [2026-05-08 Fri] +:END: + +The gate stack provides 50-70 entity classes — adequate for a coding agent where the domain is bounded to files, commands, and code symbols. For a general-knowledge memex, 50-70 is starvation. Your memex mentions Nabokov, /Pale Fire/, Kinbote, Zembla, paranoid reading, unreliable narrators, postmodernism, butterfly migration, chess problems, and the Russian exile experience. The gate stack knows none of these. Organic growth through prose extraction would take years just to cover the entities in one person's engagement with a single novel. + +Wikidata has already done this work: approximately 2 million entity classes, over 100 million entities, a decade of human curation. By loading the neighborhood of your memex into the symbolic index (entities referenced in your prose, plus their N-hop property net from Wikidata), the entity recognition problem vanishes. The archivist doesn't need to discover Nabokov from your diary. It needs to connect your heading to the existing Wikidata entity. That is a simpler task — reference resolution, not knowledge extraction. + +The LLM's role shrinks to three thin boundaries: + +1. *Input translation* — natural language question to structured query. "What do I think about monorepos?" → =(fact-query :entity :monorepo :relation :opinion :source :memex)=. Formulaic, ~100 tokens, any model sufficient. + +2. *Prose to candidate triple* — for personal memex entries that have no Wikidata counterpart: your opinions, your day's events, your project plans. Proposals verified by Screamer before admission. This is the only extraction path that still requires an LLM, and its scope is limited to what Wikidata cannot provide. + +3. *Result to prose* — structured answer to readable sentence. "Your 2023 diary says 8848m. Wikidata (last edited Feb 2024) says 8849m. They disagree on height." The reasoning is done; the LLM wraps the plist in grammar. ~100 tokens, any model sufficient, purely cosmetic. + +Everything else — the gate stack, the fact store, the constraint solver, the type hierarchy, the provenance tracking, the contradiction surfacing, the cross-domain comparison — is pure deterministic Lisp with zero LLM tokens. + +The decisive simplification: without Wikidata, the archivist must /discover/ entities from prose. With Wikidata loaded, the entity graph is pre-structured. The archivist's job changes from "discover that Nabokov wrote /Pale Fire/ and lectured on Kafka" to "verify that the Nabokov referenced in heading #47 is Wikidata item Q36591." + +Wikidata facts are admitted with =:provenance :wikidata= and cardinality policy =:plural=. They do not override your memex's facts. They sit alongside them. Disagreements are surfaced, not resolved. + +** Empirical Validation — MOMo and Modular Ontology Engineering +:PROPERTIES: +:ID: design-momo +:CREATED: [2026-05-08 Fri] +:END: + +Shimizu and Hitzler (2025, /Journal of Web Semantics/) argue that LLMs can significantly accelerate knowledge graph and ontology engineering — modeling, extension, population, alignment, and entity disambiguation — but /only/ if ontologies are modular. + +*** The central finding: modularity is the key variable + +In a complex ontology alignment task, an LLM without module information detected correct mappings for 5 of 109 alignment rules — effectively useless. When the same LLM was given the module structure of the target ontology (20 named conceptual modules), it detected correct mappings for 104 of 109 rules — 95% accuracy. The variable was modularity. + +For ontology population (extracting triples from text), their best results came from prompts that included a schematic representation of a /single module/ plus one extraction example. Against ground truth, this achieved approximately 90% extraction accuracy. Without module-scoped prompting, quality degraded substantially. + +The mechanism: conceptual modules scope the LLM's attention to something human-sized. The paper's central claim — "by somehow limiting the scope, we achieve a more human-like approach — and one more capable of being expressed succinctly in language" — is an independent discovery of the same principle underlying Passepartout's domain-scoped Screamer checks and per-domain cardinality policies. + +*** What Passepartout should adopt + +*The modular prompt pattern.* The archivist should use module-scoped prompts: a schematic representation of a domain module plus a single extraction example. Instead of a generic "extract triples" prompt, the prompt should reference the relevant module(s) and include an example triple for each relation in that module. The module provides /context/; the example provides /format/. Both improve LLM extraction quality without increasing Screamer's verification burden. + +*MOMo modules as ontology scaffold.* The 50-70 gate-bootstrapped entity classes are starvation for the broader memex. MOMo's micropattern library provides a ready-made scaffold — hundreds of commonsense patterns for temporal relations, spatial relations, agent-action, organizational structure, provenance, and event participation. Loading these as initial modules — with =:policy :plural= and =:provenance :external-ontology= — would give the symbolic index a structured vocabulary for domains where the gate stack has nothing to offer. Organic growth then /extends and refines/ these modules rather than inventing them from scratch. + +*Cross-source validation.* The archivist can extract facts from the user's prose, extract facts from Wikidata for the same entities, and present disagreements with provenance. This is the =:plural= cardinality policy applied at extraction time. + +The paper validates three design decisions already made: (1) modularity is non-negotiable — the difference between 5% and 95% accuracy; (2) the extraction pipeline is feasible — 90% population accuracy with module-scoped prompts means the archivist /can/ extract useful facts, and the remaining 10% hallucination rate is what Screamer catches; (3) knowledge graphs are positioned as anti-hallucination infrastructure — the Passepartout thesis stated in the academic literature. + +References: +- Shimizu, C., & Hitzler, P. (2025). Accelerating knowledge graph and ontology engineering with large language models. /Journal of Web Semantics, 85/, 100862. +- Shimizu, C., Hammar, K., & Hitzler, P. (2023). Modular ontology modeling. /Semantic Web, 14/(3), 459–489. +- Norouzi, S.S. et al. (2024). Ontology Population using LLMs. arXiv:2411.01612. + +* Implementation Properties + +** Performance — Why Ontology Growth Doesn't Make the System Slower +:PROPERTIES: +:ID: design-performance +:CREATED: [2026-05-10 Sun] +:END: + +Passepartout's performance thesis is: minimize LLM calls, minimize context tokens, keep everything else local and fast. Knowledge base size is irrelevant to those metrics. This is not an aspiration. It is a structural property. + +The system has two cost domains with fundamentally different scaling: + +| Resource | Cost driver | Scales with | +|---------------+------------------------------------------+------------------------------------------| +| LLM tokens | Context window size, number of API calls | Foveal-peripheral pruning, gate rules | +| Compute | Screamer deduction, hash table lookups | Entity count, rule count per domain | + +LLM tokens are minimized by design — deterministic gates cost 0 tokens, sparse-tree rendering keeps context at 2,000–4,000 tokens regardless of memex size. Adding 5 million Wikidata entities doesn't add a single token to any LLM call. The education is local. Only the brain costs. + +Compute grows linearly with entity count (hash table lookups are O(1), but memory footprint grows). It grows with rule count within a single domain during Screamer consistency checking. But these are microsecond costs on local hardware, not API bills. A Screamer constraint check against a domain with 200 rules costs ~0.3ms. A 100-token guardrail paragraph in a system prompt costs ~$0.00001. The Screamer check is 10,000x cheaper and convergent — it handles the rule once. The guardrail paragraph handles it on every call, forever. + +A 5-million-entity Wikidata load is ~400MB in a hash table. A lifetime personal memex with a decade of diary entries is perhaps 10-20 million triples (~1.5GB). Modern laptops carry 16-64GB. The knowledge base fits in consumer hardware with room for the Lisp runtime, the memory-object store, and the LLM inference engine. + +*One genuine risk — rule generalization width.* If Screamer deduces increasingly broad rules within a single domain, the constraint space could bloat. Mitigation: rules carry a =:domain= tag. Screamer only applies rules from the fact's domain. Rule generalization that crosses domain boundaries is gated — must be human-approved. Rules that prove unused (never triggered a check in N heartbeat cycles) are demoted to =:inactive= and excluded from the active constraint set. + +This is the minimalism argument restated in concrete terms: you buy bigger RAM and a faster CPU once. You don't buy bigger LLM context windows on every call. The education is a capital investment. The brain is an operating expense. The architecture makes the ratio favor capital. + +** The Provenance Chain as Product +:PROPERTIES: +:ID: design-provenance-product +:CREATED: [2026-05-10 Sun] +:END: + +In the coding domain, the value of the symbolic engine is the verified fact: "this command is safe." In the broader memex, the value is the provenance itself: "this claim originated in that diary entry on that date, has been referenced 7 times across 4 different projects, was contradicted in a retrospective 6 months later, and was revised in a note 3 weeks after that." + +The symbolic engine doesn't tell you what is true. It tells you what you wrote, when, where, and how it connects to everything else you wrote — with a verifiable audit trail. It is a memory prosthesis that makes your own mind legible to you. + +Every fact carries: +- =:grounding= — the specific Org heading from which it was extracted +- =:provenance= — who or what produced it (gate-outcome, human-authored, deduced, LLM-proposed) +- =:timestamp= — when it was admitted to the symbolic index +- =:referenced-by= — other facts that depend on or reference this one +- =:contradicted-by= — other facts that disagree with this one (if any) +- =:superseded-by= — if this fact was replaced by a newer version + +These fields make every fact auditable. The =/audit = command renders the full provenance chain as an Org headline tree. The provenance is not a logging feature. It is the product. + +* Engineering Infrastructure + +** The REPL as Cognitive Substrate +:PROPERTIES: +:ID: design-repl-cognition +:CREATED: [2026-05-07 Wed] +:END: + +A REPL — Read, Eval, Print, Loop — is an interactive programming environment that reads an expression, evaluates it, prints the result, and loops back to read the next expression. It is the opposite of batch processing: where batch compiles and runs a program in one shot, a REPL works one expression at a time, with each evaluation building on all previous ones. The state accumulates. The session is the program. + +In Lisp, the REPL is not a debugging tool bolted onto the language — it is the natural mode of interaction. The running image is the environment. When you evaluate =(+ 2 2)=, the result =4= is printed, and you remain in the same image where =+= is defined, where previous definitions persist, where the next expression can reference anything that came before. There is no separation between development and execution. The REPL is not a simulation of the program — it is the program running. + +Passepartout uses the REPL in this spirit, but elevated: it is not merely a tool for writing code, it is the mechanism by which the agent interacts with its own cognition — a loop that mirrors the perceive-reason-act metabolic cycle at the implementation level. + +In the agent's cognitive architecture, the REPL serves three functions that are difficult or impossible to achieve through batch processing or stateless API calls. + +First, the REPL enables verification before commitment. When the agent generates code, it does not write and forget — it evaluates in a running image, observes the result, iterates if incorrect. The feedback loop is tight: the time between writing and seeing the error is measured in milliseconds, not in the round-trip to a language server or a batch compiler. This is the "verification over hallucination" principle made concrete: the agent tests what it writes before claiming it works. + +Second, the REPL enables stateful exploration. The agent can define a variable, inspect it, modify it, redefine it. The exploration accumulates state across interactions. This is not a debugging session — it is the agent thinking with its hands, working through a problem by trying variations and observing outcomes, keeping the successful ones and discarding the failures. + +Third, the REPL is a shared substrate. When the agent evaluates code, that code runs in the same image as the agent's own cognition. There is no process boundary between the agent and its tools. The REPL is not a subprocess the agent controls — it is a direct interface to the agent's own nervous system. + +This is why the REPL becomes more important as the system matures. In early versions, it is a development tool. In v0.6.0 and beyond, it becomes a cognitive tool: the agent explores hypotheses by evaluating them, verifies the output of sub-agents by inspecting live state, and tests modifications before committing them to the knowledge graph. + +** The Cybernetic Loop: Why the Metabolic Pipeline Works +:PROPERTIES: +:ID: design-cybernetic-loop +:CREATED: [2026-05-07 Wed] +:END: + +The Perceive → Reason → Act cycle is not a software architecture pattern. It is a cybernetic feedback loop — the mechanism by which a system steers itself toward a goal in a changing environment. + +Norbert Wiener defined cybernetics in 1948 as "control and communication in the animal and the machine." The metabolic pipeline implements this precisely: Perceive is the sensor (reading the environment), Reason is the controller (evaluating against goals and constraints), Act is the actuator (modifying the environment), and the tool-output feedback signal closes the loop (reading the effect of the action and adjusting the next perception). + +The Dispatcher gate stack is the negative feedback governor. When the LLM proposes an action that would violate an invariant, the Dispatcher blocks it and feeds the rejection trace back to the LLM for self-correction. This is Ross Ashby's homeostasis — the system maintains its internal stability by correcting deviations from its set point (the safety invariants). Without this negative feedback, the probabilistic engine would drift into hallucinated proposals that become progressively less grounded. The Dispatcher constrains it to the domain of safe, verifiable actions. + +The self-editing capability is second-order cybernetics — autopoiesis, the capacity of a system to create and maintain itself. Humberto Maturana and Francisco Varela defined this as the hallmark of living systems. When the agent detects an error, locates the faulty function, generates a corrected version, and hot-reloads it into the running image without restarting, it is modifying its own architecture while continuing to operate. Passepartout achieves this through Lisp's homoiconicity — code is data, and the running image is the environment. + +This framing matters for two reasons. First, it places Passepartout in a lineage that predates and outlasts the current "LLM with tools" paradigm. The cybernetic principles of feedback, homeostasis, and autopoiesis are independent of any specific model architecture. They work whether the perceptual engine is an LLM, a vision model, or a symbolic parser. Second, it explains why the architecture gets more reliable over time — cybernetic systems improve through accumulated negative feedback corrections, not through better training data. Every blocked action is a correction. Every approved exception is a refined set point. The system converges on stability through use. + +** Observability and the Thought Trace +:PROPERTIES: +:ID: design-observability +:CREATED: [2026-05-07 Wed] +:END: + +When a human asks why the system made a decision, the answer must be findable. In most AI systems, the reasoning is ephemeral — it exists in the model's activations and disappears when the session ends. In Passepartout, every significant cognitive event is written to an Org buffer as it happens. + +The thought trace is the agent's journal, written in parallel with its reasoning. When the probabilistic engine generates a proposal, the trace records the input, the prompt, and the raw output. When the deterministic engine evaluates it, the trace records which rules were checked, which passed, which failed, and why. When an action is executed, the trace records the timestamp, the user who approved it (if human-in-the-loop), and the outcome. + +This is not logging in the traditional sense. Logs are forensically useful but are written in a machine format optimized for storage, not for human reading. The thought trace is written in Org-mode: headlines for major events, property drawers for structured data, tags for categorization. The human can open the trace in a text editor and navigate it like any other Org file. They can search for a specific decision, filter by time range, find all actions blocked by a specific rule, or see the complete trajectory of a multi-step task. + +The trace becomes the foundation for the Dispatcher's learning. Every blocked action is in the trace. Every approved exception is in the trace. The human-in-the-loop decisions are in the trace. The system does not need to reconstruct what happened — it reads what happened from the trace it wrote. + +Without observability, the system is a black box that happens to produce correct outputs sometimes. With observability, the system is auditable. The human can see why a decision was made, identify where the reasoning failed, and course-correct the system or its own behavior accordingly. + +** Literate Programming as Discipline +:PROPERTIES: +:ID: design-literate-programming +:CREATED: [2026-05-07 Wed] +:END: + +The decision to use Org-mode as the source of truth for code, not just documentation, is not a ceremonial preference. It is a constraint mechanism that enforces better engineering habits at the cost of convenience. + +The traditional development workflow is: write code, write comments, commit. The literate programming workflow is: write prose, write code, commit the Org. The order matters. The prose must come first not because of style guidelines but because the act of explaining what a function does before writing it forces clarity of thought that editing code directly does not. + +When you must write a paragraph describing what a function does before you write the function, you discover the cases you have not considered. You find the edge conditions that are ambiguous. You realize that the function's name does not match its behavior, or that its behavior does not match your intent. The friction is not a bug — it is the mechanism by which thinking is enforced. + +The one-function-per-block rule enforces granularity. A function that cannot be explained in a paragraph is a function that is doing too much. The block boundary is not aesthetic — it is architectural. It prevents the drift toward monolithic functions that accumulate responsibilities over time and become untestable, unmaintainable, and incomprehensible. + +The tangle step enforces source-of-truth discipline. The .lisp file is generated from the Org file. This means the Org file cannot drift from the implementation. If the implementation changes, the Org must be updated to match. If the Org describes behavior that the implementation does not perform, the tangle produces code that does not match the Org description. Either way, inconsistency is visible and recoverable. + +The evaluation gate enforces correctness. Every block can be evaluated independently in a running Lisp image. This means syntax errors are caught at authorship time, not at integration time. The function that compiles in isolation but fails in context is the function whose context dependencies were never made explicit. The evaluation gate forces those dependencies to surface. + +Together, these constraints create a development experience that is slower in the small and faster in the large. Writing a new function takes longer because you must explain it. But debugging, maintaining, and extending the codebase is faster because every function has a human-readable explanation of its intent, every function is testable in isolation, and every function's source is always synchronized with its documentation. + +The literate programming discipline is not about producing documentation. It is about producing code whose correctness has been verified by the act of explaining it. + +** The Evaluation Harness +:PROPERTIES: +:ID: design-evaluation-harness +:CREATED: [2026-05-07 Wed] +:END: + +SOTA parity is meaningless without measurement. A system that claims to match commercial agents must demonstrate it through reproducible benchmarks, not through feature checklists. The evaluation harness is the apparatus by which Passepartout proves its capabilities. + +The industry standard for coding agents is SWE-bench: a corpus of GitHub issues paired with pull requests. The agent is given an issue, must understand the codebase, write a fix, and submit. Success is measured by whether the submitted PR passes the existing test suite. This tests the full chain: understanding, planning, code generation, verification, and multi-step reasoning. + +Passepartout implements a native Lisp harness for this. A background thread clones repositories, feeds issues into the cognitive loop, tracks the resolution trajectory as an Org-mode headline tree, and scores success by test outcomes. The trajectory is persisted: when a resolution fails, the system can inspect where in the chain the reasoning broke down. The headline tree records the agent's thoughts at each step, making the failure auditable and the debugging human-assisted. + +Beyond SWE-bench, the harness includes chaos testing. The system is subjected to resource starvation, concurrent load, and adversarial input. The deterministic engine must maintain safety invariants under pressure. The symbolic verifier must not deadlock or livelock. The probabilistic engine must degrade gracefully. + +The harness also supports regression testing on the skill set. Every skill is tested against a suite of known inputs and expected outputs. When a modification is proposed to any skill — whether through manual editing or the agent's own self-modification — the test suite runs first. A skill that fails its tests is rejected before it can propagate to the running image. This is not a convenience — it is the mechanism by which self-modification remains safe. The agent can propose changes, but the harness verifies them before the changes take effect. + +** The MCP Strategy +:PROPERTIES: +:ID: design-mcp-strategy +:CREATED: [2026-05-07 Wed] +:END: + +The Model Context Protocol (MCP) is a standard for connecting AI systems to external tools and data sources. It defines how a client requests tools from a server, how the server exposes its capabilities, and how the client invokes them. The ecosystem is growing: MCP servers exist for GitHub, Slack, Postgres, filesystem access, and much more. + +Passepartout connects to this ecosystem, but not by becoming a Node.js runtime. The architecture is: external MCP servers communicate via stdio or SSE to a Lisp-native MCP client that runs in the same image as the agent. The client is pure Common Lisp — it parses the JSON-RPC messages, invokes the tools, and presents results to the agent as Lisp data structures. There is no serialization overhead between the agent and the MCP layer, no process boundary, no impedance mismatch. + +When the agent calls a tool via MCP, it receives a plist with the tool name, arguments, and result. The result is immediately usable by the agent's symbolic engine. When the agent generates a file, it can be written to the filesystem through an MCP filesystem server. When the agent needs to send a message, it can use an MCP Slack server. The agent does not need to know that these are MCP interactions — it sees only the plists that flow through its cognitive architecture. + +The alternative is to build MCP wrappers in Python or TypeScript and bridge to Lisp via subprocess. This introduces latency, serialization costs, and a maintenance burden. Passepartout's native client is smaller, faster, and more maintainable. The MCP client is a skill, not a core component. It can be reloaded, replaced, or removed without restarting the agent. + +** Local-First Architecture +:PROPERTIES: +:ID: design-local-first +:CREATED: [2026-05-07 Wed] +:END: + +Passepartout is designed to run on the user's machine, on their hardware, with their data, without requiring an internet connection. This is not a deployment option — it is an architectural commitment. The system must be able to reason, plan, and act using only the resources available locally. + +The motivation is not merely philosophical. Cloud-based AI agents are economically incentivized to collect data, to train on user interactions, and to build lock-in through proprietary formats and network effects. When the agent runs locally, the user owns the hardware, owns the data, and can terminate the process without asking permission. There is no vendor that can change terms, no service that can go offline, no model that can be updated without consent. + +Technically, local-first means several things. The LLM must be able to run on local hardware. Passepartout supports Ollama as a provider, which runs quantized models on CPU and GPU without requiring an external API. The vector database must be local. Passepartout uses its own org-object store, which is a folder of Org files that the agent already owns. There is no ChromaDB or Qdrant to install, no cloud vector service to authenticate with. + +The symbolic engine does not require a network connection. The Prolog/Datalog reasoner that verifies neural proposals runs entirely in the Lisp image. The Dispatcher's rule synthesis does not call an external service. The agent can operate in a disconnected environment indefinitely, resuming full capability when connectivity is restored. + +This does not mean Passepartout refuses to use cloud services when available and appropriate. It means cloud services are optional enhancements, not architectural requirements. The core is local. The user can choose to add cloud LLM providers for more capable inference, but the system functions without them. + +*On live images and binaries.* Passepartout's primary delivery path is source code running in a live SBCL process. The REPL is available. Skills hot-reload. The cognitive loop runs in an image that is mutable, inspectable, and homeiconic — the user can connect with SLIME, trace functions, inspect memory objects, and modify the system while it runs. A =save-lisp-and-die= binary is provided as a convenience for platforms where SBCL cannot be installed. The binary is the same image saved to disk with Swank pre-loaded — it is not a sealed container. The REPL works. Skills hot-reload. The binary is a packaging format, not an architectural decision. + +** Token Economics and Performance Advantage +:PROPERTIES: +:ID: design-token-economics +:CREATED: [2026-05-07 Wed] +:END: + +This section analyzes how Passepartout's architectural decisions translate into token usage, latency, and cost versus competing agent designs. + +*** The Core Insight: LLM as Expensive Resource, Not Default Engine + +Passepartout treats the LLM as a resource to be minimized. Every operation is designed to reduce LLM dependency. Competitors treat the LLM as the core engine through which all operations flow. This is not a difference of degree but of architecture. + +The structural multipliers are: + +1. *Sparse tree retrieval* — the foveal-peripheral model renders relevant Org subtrees (titles and properties for peripheral nodes, full content for foveal and semantically relevant nodes). Active context stays at 2,000–4,000 tokens. A "load everything" architecture serializes the entire knowledge base at 50,000–150,000 tokens. The mechanism is provably cheaper; the exact multiplier depends on memex size and complexity. + +2. *Deterministic safety* — the 10-vector Dispatcher gate stack runs in pure Lisp. Every gate is a Common Lisp function. Verification costs 0 LLM tokens per action. Competitors use prompt-based guardrails consuming 100–500 LLM tokens per verification. This multiplier is mathematically infinite — a Lisp function call costs no tokens, a guardrail paragraph in a system prompt costs tokens proportional to its length. + +3. *REPL verification* — code is tested in the running image before it is committed. Errors surface in milliseconds at 0 LLM tokens. Competitors discover errors after generation and pay 500–2,000 tokens per correction round-trip. The REPL eliminates the most expensive kind of LLM call: the one that produced wrong code and needs a do-over. + +4. *Hot state* — in a REPL-based agent, variables, file handles, sub-routine results, and memory objects are already in memory. Every turn in a standard chat agent re-sends the full conversation history. Token costs in chat agents are quadratic: a 10-turn session pays for ~55 "turns" of context (10 + 9 + 8 + ... + 1 = 55). In Passepartout, context is stored once in the Lisp image. A 10-turn session pays for ~10 turns of context. This is an ~82% reduction on protocol overhead alone, before any foveal-peripheral pruning. + +5. *Temporal filtering* — time-scoped memory queries return only nodes matching the time window. The temporal filter is a pure-Lisp hash-table walk with a numeric comparison on =memory-object-version=. Sub-millisecond. 0 LLM tokens. Competitors without time-indexed memory must serialize all nodes and let the LLM scan for temporal relevance — 5,000–50,000 tokens per temporal query. + +*** The Compounding Cost Curve — Unique Among Agents + +Every AI agent grows more expensive over time. Context histories accumulate. Safety instructions grow more elaborate. Guardrails become longer prompt paragraphs. The user's data grows. The only way to reduce cost in a standard agent is to cap context — sacrificing capability. + +Passepartout has a downward cost curve. Four mechanisms compound: + +1. *Dispatcher learning.* Every blocked action and approved exception becomes a deterministic rule. A file write that initially triggered a full LLM proposal → Dispatcher review → HITL approval → rule extraction loop eventually becomes a deterministic rule check. Each hardened rule permanently removes a future LLM call. + +2. *Symbolic induction.* The agent extracts patterns from successful interaction sequences and converts them into reusable Lisp functions. A multi-step task that took 5,000 tokens today takes 0 tokens tomorrow — it's now a =defun=. The Dispatcher learns what to block. Symbolic induction learns what to automate. + +3. *Native embedding inference.* Every semantic search query runs against in-image vectors at 0 external tokens. Competitors use LLM-assisted search for most retrieval operations. Passepartout's retrieval is a vector cosine similarity check — pure math, no model call. + +4. *Prefix caching.* The static portion of the system prompt (IDENTITY, TOOLS, LOGS format) is transmitted once per session. Dynamic content (CONTEXT, user prompt) is sent on each call. Anthropic's prompt caching gives a 90% discount on cached tokens. OpenAI caches automatically. + +After 12 months of daily use, Passepartout's per-session costs are expected to be 40–60% of baseline, while competitors' costs rise to 125–140% of baseline. The crossover point is estimated at 3–6 months. This is not a model quality claim — it is a structural property of the architecture. + +** Time Awareness as a Structural Advantage +:PROPERTIES: +:ID: design-time-awareness +:CREATED: [2026-05-07 Thu] +:END: + +Passepartout's architecture provides three layers of time awareness, each enabled by infrastructure that competitors lack: + +*Level 1 — Present Awareness.* The LLM knows the current time, date, and session duration because a single =format-time-for-llm= call injects it into the system prompt. Most agents know the date from the OS. None know the time or session duration. The cost is ~8 incremental tokens per call (trivially prefix-cached). The saving is eliminating "I don't know the current time" preamble tokens, time-check tool calls, and incorrect temporal reasoning from a model guessing the time. + +*Level 2 — Temporal Memory.* Memory queries accept =:since= and =:until= parameters. "What did I work on in the last hour?" filters 500 nodes to 12 in sub-millisecond Lisp rather than serializing 500 nodes to the LLM at ~5,000 tokens for it to scan. Every memory node carries a =memory-object-version= timestamp (a monotonic =get-universal-time= value set at ingest since v0.1.0). The temporal filter is a hash-table walk with numeric comparison. 0 LLM tokens. >90% token reduction on time-scoped queries. + +*Level 3 — Proactive Triggers.* The heartbeat tick scans for approaching deadlines every 60 seconds. When a deadline is within the warning window (=DEADLINE_WARNING_MINUTES=, default 60), a temporal context note is injected into the awareness assembly. The LLM sees "3 deadlines today: Submit report (45min)" in its context without a triggering call. A "what should I work on today?" query is answered from pre-loaded context — 0 LLM tokens versus 1,500–4,000 for an unassisted agent. + +None of these three layers require new infrastructure. Time awareness is not a feature Passepartout builds — it is a feature Passepartout *unlocks* by having timestamped memory (v0.1.0), heartbeat+cron (v0.3.0), and the foveal-peripheral context pruning model (v0.2.0) already in place. Adding time awareness costs ~175 lines of Lisp. Building it in competitors would require building the heartbeat, the time-indexed memory, and the proactive context injection — 800+ lines each — and would still cost LLM tokens because their safety verification is prompt-based. + +** Definite Description Resolution +:PROPERTIES: +:ID: design-description-resolution +:CREATED: [2026-05-14 Thu] +:END: + +When the user says "the function that validates secrets," the agent must resolve this to a specific code entity. Natural language is ambiguous — there might be multiple functions matching the description. Resolving to the wrong one causes incorrect actions. + +/Principia Mathematica/'s theory of descriptions addresses this: "the current king of France is bald" — a sentence that seems to refer to something that doesn't exist. PM formalizes ~ιx(φx)~ as "the unique x such that φ holds." A statement is false (not meaningless) when there is no unique x satisfying φ. + +A cognitive tool that checks descriptional uniqueness before resolution: + +#+BEGIN_SRC lisp +(def-cognitive-tool :resolve-reference + (query-string &key (max-candidates 10) + (context-path *current-context*)) + "Resolve a definite description to a unique referent." + (let ((candidates (search-knowledge-graph query-string + :source-path context-path + :limit max-candidates))) + (cond + ((null candidates) + (values nil :no-referent query-string)) + ((> (length candidates) 1) + (values nil :ambiguous candidates)) + (t + (values (first candidates) :unique nil))))) +#+END_SRC + +~40 lines as a skill in v0.7.2. When VivaceGraph ships (v3.0.0), descriptions become native Prolog queries with uniqueness constraints. + +For the philosophical foundations, see the Whitehead analysis in the Validation section below. + +* Validation + +** Whitehead's Process Philosophy and Type Theory +:PROPERTIES: +:ID: design-validation-whitehead +:CREATED: [2026-05-14 Thu] +:END: + +Alfred North Whitehead's two major bodies of work — /Principia Mathematica/ (1910–1913, with Bertrand Russell) and /Process and Reality/ (1929) — provide both the historical foundation and the descriptive vocabulary for Passepartout's architecture. The first gave us the type theory that structures the gate stack; the second gave us the process ontology that describes the pipeline. + +/Principia Mathematica/ is a direct ancestor of Lisp. Alonzo Church's lambda calculus (1930s), from which John McCarthy built Lisp (1958), was a response to PM's foundational program. PM's notation: + +#+BEGIN_EXAMPLE +(x).φx ≡ (for all x, φ holds of x) +(∃x).φx ≡ (there exists x such that φ holds) +* x̂(φx) ≡ (the class of x satisfying φ) +ιx(φx) ≡ (the unique x satisfying φ) +#+END_EXAMPLE + +These map directly to Lisp: ~(lambda (x) (φ x))~, ~(class (x) (φ x))~, ~(the (x) (φ x))~. McCarthy cited PM as an influence. The connection is genetic, not metaphorical. + +Whitehead's process philosophy is a metaphysics of /becoming/ rather than /being/. The fundamental entities are not substances but /processes/ (/actual entities/, /occasions of experience/). This maps precisely to Passepartout's pipeline architecture: + +| Whiteheadian Concept | Passepartout Mapping | Significance | +|----------------------------------+---------------------------------------------+--------------------------------------------------| +| Actual entity (actual occasion) | An event/signal in the pipeline | The fundamental unit — everything else is abstraction | +| Prehension | A gate's grasping of a signal | How one entity "takes account of" another | +| Positive prehension | A gate passing a signal | The signal is included in the concrescence | +| Negative prehension | A gate rejecting a signal | The signal is excluded from the concrescence | +| Concrescence | The pipeline process from input to output | Many prehensions → one satisfaction | +| Subjective aim | The agent's active goal / plan | The telos directing which prehensions matter | +| Eternal objects | Pure concepts in the knowledge graph | Universals — types, functions, categories | +| Nexus | A cluster of related memory objects | A Merkle subtree | +| Satisfaction | The final agent response | The "completed" entity — determinate output | +| Transition | From one signal to the next | The pipeline's forward motion | +| Causal efficacy | The agent's past context (memory) | What is prehended from the settled past | +| Presentational immediacy | The current signal (user input) | What is prehended from the immediate present | + +The foveal-peripheral model maps directly onto Whitehead's two modes of perception: /presentational immediacy/ is foveal focus on the current signal (vivid but superficial), while /causal efficacy/ is peripheral context from memory (dim but causally powerful). Whitehead argues that all perception is the "mixed mode" of symbolic reference — the synthesis of the two. Passepartout's ~think()~ function does exactly this: it synthesizes the current signal with context from memory into a response. + +Whitehead also gives Passepartout a /descriptive vocabulary/ that is precise, standard, and already maps perfectly to the design. "I am concrescing signal 47 through gates 0-8" is not poetry — it is a precise description of dispatcher operation. "Gate 3 has negatively prehended signal 136" means the secret-content gate rejected signal 136. "The satisfaction includes a file-write prehension with Merkle commit abc123" means the response contains a file write with the given Merkle hash. The agent uses this vocabulary in its ~/why~ output and in the ARCHITECTURE.org documentation. + +Not everything is useful. PM's full formalism — 300+ pages to prove ~1+1=2~ — is catastrophic as a reasoning engine. The /ideas/ (type theory, descriptions, propositional functions) are what matter, not the notation. Similarly, Whitehead's later concept of God (the "principle of concretion") and the full 25-category metaphysical system have no useful mapping to an agent architecture. Select the concepts that map; don't build a process-philosophy engine. + +Passepartout is level 4 neuro-symbolic (symbolic gates + neural LLM, deterministic components coordinate heterogeneous systems). PM's type theory adds level-5 properties: /structural/ safety guarantees rather than /empirical/ ones. The dispatcher becomes not just a runtime gate stack but a type-theoretic framework where category errors are impossible by construction — just as PM made Russell's paradox impossible by construction. The Whiteheadian vocabulary reinforces the architectural identity: Passepartout is not a chatbot with safety checks. It is a /process/ — a continuous concrescence of prehensions producing satisfactions — whose safety is guaranteed by the type structure of the prehending entities. + +** Historical Lineage — McCarthy's Advice Taker +:PROPERTIES: +:ID: design-mccarthy +:CREATED: [2026-05-10 Sun] +:END: + +McCarthy's "Programs with Common Sense" (1959) is the direct intellectual ancestor of the Passepartout architecture. The paper proposed an "advice taker" — a program that "will draw immediate conclusions from a list of premises" expressed in "a suitable formal language (most likely a part of the predicate calculus)." The program would: + +1. Accept declarative statements about the world as input. +2. Store them as logical formulas. +3. Reason from them to produce new conclusions. +4. Accept new facts and revise its conclusions. + +This is precisely the Passepartout pipeline: the archivist extracts declarative facts from prose → Screamer checks them for consistency → VivaceGraph stores them → the planner reasons from them → new facts from gate outcomes and deductions revise the store. McCarthy proposed it in 1959. Passepartout is building it in 2026. + +The gap between McCarthy's proposal and Passepartout's implementation is the /hallucination problem/. McCarthy assumed facts would be entered by a human programmer in formal logic. Passepartout's facts are extracted from natural language prose by an LLM — a probabilistic process that requires deterministic verification. Screamer is the component McCarthy didn't need: a constraint solver that gates LLM-proposed facts against the existing fact store. + +The connection is not metaphorical. McCarthy cited /Principia Mathematica/ as an influence on Lisp. Passepartout's Whitehead analysis traces the same PM → Lisp lineage. The advice taker → Passepartout lineage completes the arc: PM's formal logic → Lisp → McCarthy's advice taker → Passepartout's neurosymbolic engine. + +Reference: McCarthy, J. (1959). Programs with Common Sense. /Proceedings of the Teddington Conference on the Mechanization of Thought Processes./ + +** Marcus (2020): The Case Against Pure Deep Learning + +Gary Marcus's "The Next Decade in AI" argues that deep learning alone is "data hungry, shallow, brittle, and limited in its ability to generalize." The paper demonstrates GPT-2 failing at basic commonsense reasoning: + +- "Yesterday I dropped my clothes off at the dry cleaners and have yet to pick them up. Where are my clothes?" → GPT-2: "at my mom's house." +- "There are six frogs on a log. Two leave, but three join. The number of frogs on the log is now" → GPT-2: "seventeen." + +Marcus proposes four steps toward robust AI: hybrid architecture (combining neural and symbolic), large-scale knowledge (abstract and causal, not just statistical), reasoning (formal inference over structured representations), and cognitive models (frameworks for how entities relate). Passepartout implements all four: the perceive-reason-act pipeline is hybrid, the symbolic index is causal knowledge, Screamer + ACL2 provide reasoning, and the gate-bootstrapped ontology plus MOMo modules provide cognitive models. + +Marcus's core claim — "we have no hope of achieving robust intelligence without first developing systems with deep understanding" — is the justification for Passepartout's entire neurosymbolic investment. The alternative is a system that works "on a good day" and fails unpredictably. The deterministic gate stack and Screamer admission gate are the engineering realization of Marcus's call for robustness. + +Reference: Marcus, G. (2020). The Next Decade in AI: Four Steps Towards Robust Artificial Intelligence. arXiv:2002.06177. + +** Gaur & Sheth (2023): CREST — Trustworthy Neurosymbolic AI + +Gaur and Sheth present the CREST framework: Consistency, Reliability, user-level Explainability, and Safety build Trust — and they argue these require neurosymbolic methods. Their empirical finding: GPT-3.5 breached safety constraints 30% of the time when asked identical questions repeatedly. Claude's 16 safety rules and Sparrow's 23 rules provide no /inherent/ safety — they are heuristic guardrails that can be breached through prompt variation. + +These findings validate three Passepartout design commitments: (1) prompt-level safety is insufficient — deterministic gates run in pure Lisp, cost 0 tokens, and cannot be evaded by prompt engineering; (2) inconsistency is the norm — the cardinality model expects contradiction and surfaces it with provenance; (3) knowledge infusion is required for trust — Passepartout's symbolic index IS the knowledge infusion layer, facts extracted from prose, verified by Screamer, and available for any LLM call. + +Reference: Gaur, M., & Sheth, A. (2023). Building Trustworthy NeuroSymbolic AI Systems: Consistency, Reliability, Explainability, and Safety. arXiv:2312.06798. + +** Sheth et al. (2022): Knowledge-Infused Learning + +Sheth, Gunaratna, Bhatt, and Gaur define Knowledge-infused Learning (KiL) as "combining various types of explicit knowledge with data-driven deep learning techniques." They identify three infusion levels (shallow, semi-deep, deep) and position KiL as "a sweet spot in neuro-symbolic AI." + +Passepartout's architecture is a specific implementation of KiL at the deepest infusion level: knowledge is not appended to prompts (shallow) or embedded in fine-tuning (semi-deep). It is a first-class data structure — the symbolic index — that the LLM queries through the archivist and the planner. The knowledge is living: it accumulates, is verified, carries provenance, and evolves through ontology versioning. + +Reference: Gaur, M., Gunaratna, K., Bhatt, S., & Sheth, A. (2022). Knowledge-Infused Learning: A Sweet Spot in Neuro-Symbolic AI. /IEEE Internet Computing, 26/(4), 5–11. + +** The Competitive Argument +:PROPERTIES: +:ID: design-competitive +:CREATED: [2026-05-10 Sun] +:END: + +No competitor has this problem because no competitor has a symbolic engine. The 55 systems surveyed in the competitive landscape range from pure chat agents (Claude, ChatGPT) to agent harnesses (Claude Code, OpenCode, Hermes) to platform agents (OpenClaw). None of them encode knowledge as formal facts with provenance. None of them verify extractions against an existing knowledge base. None of them can prove properties about their own rulesets. + +Their safety is heuristic (prompt-based guardrails that consume LLM tokens and can be evaded with clever phrasing). Their memory is flat (JSONL transcripts without content-addressed identity or provenance chains). Their reasoning is entirely neural — when you ask "why did you decide that?", the answer is a regenerated LLM explanation, not a retrieved inference chain. + +Passepartout's architectural bet is that this problem is worth solving — that a system which can surface contradictions with provenance, derive new facts from observations, and verify claims against a provenanced knowledge graph is fundamentally different from a system that can only call an LLM and hope the response is correct. + +The cost is the ontological work that is genuinely difficult. The reward is a system that cannot hallucinate at the reasoning level, whose memory is provable rather than empirical, and whose knowledge accumulates across sessions through deduction rather than through LLM re-prompting. For a life's knowledge stored in a personal memex, this is not a performance advantage. It is a category difference. + +The competitive advantage is not any single feature. It is the architecture's ability to accumulate verified knowledge from four independent sources (gates, deduction, verified LLM proposals, human authoring) and to make that knowledge queryable with provenance. Competitors accumulate chat transcripts. Passepartout accumulates a provenanced, self-verifying knowledge graph. Transcripts become stale and unreliable. The knowledge graph becomes richer and more trustworthy with every session. + +* Open Questions + +** Open Questions +:PROPERTIES: +:ID: design-open-questions +:CREATED: [2026-05-08 Fri] +:END: + +Several design questions are unresolved and should remain unresolved at this stage. They represent research decisions that require experience running the system. + +*** What is the minimum viable fact language? + +Triples — =(:entity :relation :value)= with provenance and grounding — is the current hypothesis. It is simple enough to be parseable, expressive enough to capture the gate stack's implicit claims, and extensible enough that Screamer can operate on it. But it may be too simple. Triples do not naturally express temporal relations ("was X before Y?"), modal claims ("should not do X unless Y"), or counterfactuals — all of which may be essential for a symbolically-aided memex. The right granularity depends on what queries actually need to be made, and that cannot be known in advance. + +*** How does ontology refactoring work? + +This question is settled. See "Ontology Versioning" above. The category hierarchy is Merkle-hashed. Every fact stores its =:ontology-version=. Re-verification is heartbeat-driven. Worldviews are preserved, not overwritten. The shift is the artifact. + +*** What is the appropriate role of the human? + +The human can explicitly declare facts, write constraints, and correct wrong extractions. But how much of the ontology should the human need to maintain? If the human must write a definition for every new category the symbolic engine encounters, the overhead is prohibitive. If the symbolic engine can generalize from instances, the human role becomes supervision rather than authorship — review and approve proposed generalizations. The balance cannot be set without experience. + +*** How much Wikidata is the right amount? + +Query performance and memory costs are now bounded — 5 million entities ≈ 400MB RAM, O(1) hash lookups, domain-scoped Screamer checks. A large Wikidata load is a capital cost, not a recurring bill (see "Performance" above). + +Remaining open: the right N hops from entities referenced in the memex depends on the memex's breadth. A software-engineering memex needs ~1 hop; a literary memex needs 3-4 hops (Nabokov → Kafka → expressionism → modernism → Baudelaire). The right value is empirical, testable, and user-specific — it cannot be set in the architecture. + +*** Can the symbolic engine satisfy queries from the user without LLM involvement? + +The design aims for zero-LLM query answering: the user issues a structured command (=/query=, =/contradictions=, =/audit=), and the symbolic engine responds directly. But natural language questions ("what do I think about monorepos?") still require the LLM as a thin translation layer. Whether the structured command interface is sufficient for daily use, or whether users will demand natural language interaction, determines how much LLM involvement remains in the mature system. + +*** Is the triplestore physically bounded or does it explode? + +A personal memex with years of diary entries, project notes, reading logs, and literary analyses could produce millions of triples. A naive hash table scales linearly but VivaceGraph's Prolog-like queries may not. The performance characteristics of graph queries over a million-triple knowledge base have not been estimated. + +* Relation to Passepartout's Existing Architecture + +The neurosymbolic engine is an extension of the existing probabilistic-deterministic split, not a replacement for it. The current architecture divides cognition into LLM-driven proposals and Lisp-driven verification. The symbolic engine deepens the verification side from "is this action safe?" to "is this claim supported?" — the same architectural pattern applied to a broader domain. + +The self-repair criterion (a file belongs in core only if, when corrupted, the agent cannot fix it without human help) applies to every component of the symbolic engine. Screamer, VivaceGraph, the fact store, the archivist — all are skills, loaded at runtime, hot-reloadable, and recoverable from corruption. A corrupted symbolic engine degrades reasoning capability but does not kill the agent. The eight existing core ASDF files are unchanged. + +The symbolic engine is not v1.0.0 alone. It is the layer that sits between the existing gate stack (which it makes explicit as facts) and the existing skill system (which it extends with deduction, contradiction detection, and provenance tracking). It grows within the current architecture without replacing any existing component. + +See also: +- =ROADMAP.org= — the concrete phased implementation plan (neurosymbolic phases at v0.10.0 through v0.36.0) +- =ARCHITECTURE.org= — the current pipeline architecture +- =docs/DESIGN_DECISIONS.org#validation= — Whitehead analysis (now integrated into this document) +- =notes/passepartout-symbolic-engine-exploration.org= — the original architecture exploration +- =notes/competitive-landscape.org= — 55-system competitive survey + diff --git a/projects/passepartout/ROADMAP.org b/projects/passepartout/ROADMAP.org new file mode 100644 index 0000000..db41ff1 --- /dev/null +++ b/projects/passepartout/ROADMAP.org @@ -0,0 +1,1702 @@ +#+TITLE: Passepartout Evolutionary Roadmap +#+STARTUP: content +#+FILETAGS: :docs:roadmap: + +* The Evolutionary Roadmap + +Understanding Passepartout as a function in time is not nostalgia. It is architectural guidance. Every decision in v0.x should be made with awareness of where the system is going. Code written today becomes the substrate for the Lisp Machine. Skills designed today become the vocabulary the symbolic engine speaks tomorrow. + +The probabilistic beginning is not a weakness to overcome. It is the bootstrap. The system learns the domain through probabilistic inference, and that learned knowledge becomes the seed for the symbolic engine. By the time the symbolic engine takes over, it has a rich knowledge graph to reason about, grown from thousands of probabilistic interactions. + +This is how you build a reasoning machine: start with a learner, make it learn to verify by watching itself and its user, let verification become the core. Every blocked action becomes a rule. Every approved exception becomes a pattern. The symbolic layer grows at the probabilistic layer's expense. Remove the learner once it has learned enough. + +Each version expands the deterministic layer. The Dispatcher writes rules from approved exceptions. Shadow mode runs trial executions. Tool permission tiers mature from simple allow/deny to nuanced context-aware policies. The agent becomes less likely to attempt dangerous actions not because it is smarter but because the guard has more complete information. + +The roadmap works backwards from Neurosymbolic Maturity (v1.0.0) and Lisp Machine Emergence (v2.0.0). Each build step is one minor version — one capability, measured in lines, verified by tests. Breadth releases (TUI, tools, gateways) alternate with depth releases (fact store, Screamer, VivaceGraph, ACL2) so the system is usable at every step. + +The TODO states in each version's Tasks section are the authoritative task tracker. The feature tables describe what each version delivers. + +Feature releases increment the minor version (v0.X.0). Bugfix and hardening releases increment the patch version (v0.X.Y). This ensures that security patches and critical fixes are visible in the version number and can ship independently of feature work. No feature release ships without its prerequisite hardening releases resolved. + +** File Update Checklist + +When a version's state changes (DONE → tested → released), update these locations: + +1. ~ROADMAP.org~ — mark item DONE, update LOGBOOK timestamp +2. ~README.org~ — update version badge (line 6), update Current Capabilities table (add new Stable rows for shipped features, remove Planned rows that have shipped) +3. ~~.env.example~ — update version references as needed +4. ~lisp/core-transport.lisp~ — update the ~make-hello-message~ version string +5. ~passepartout~ (bash entry point) — update version reference +6. ~CHANGELOG.org~ — add new version entry with DONE items, LOGBOOK release date, and feature summaries + +On release: +1. Tag the release on GitHub +2. Extract DONE items from ROADMAP (all items with LOGBOOK timestamps since the last release tag) and use as the release notes body +3. If a ~CHANGELOG.md~ is needed for packaging tools, auto-generate it from ROADMAP DONE items + +** v0.8.0: TUI Stabilization — cl-tty Migration + Information Radiator + +The croatoan TUI is replaced entirely by ~cl-tty~ v1.1.0. In progress across +multiple branches: the main branch does XDG-based tangling +(~/.local/share/passepartout/lisp/), the ~refactor/cl-tty-tui~ branch keeps +lisp files in the repo (~lisp/~). Both converge on the same goal — a stable, +feature-complete TUI with sidebar, command palette, warm palette, TrueColor +themes, and robust terminal handling. + +*** Minibuffer — cl-tty dialog stack +:PROPERTIES: +:ID: 29a7d05f-1aec-41a4-a213-e52551eeb9eb +:ID: id-v080-minibuffer +:CREATED: [2026-05-10 Sat] +:END: + +*** Conversation view — cl-tty ScrollBox + Markdown +:PROPERTIES: +:ID: id-v080-conversation +:CREATED: [2026-05-13 Wed] +:END: + +- ~ScrollBox~ with ~sticky-scroll~ (auto-follows new content, respects manual scroll-up) +- User messages rendered as ~Box~ (role-colored left border) +- Agent messages rendered via cl-tty's ~Markdown~ + ~Code~ + ~Diff~ renderables +- Tool calls rendered as ~Select~ (collapsible, status-indicated: spinner running / green done / red error) +- Gate trace as a collapsible ~Box~ within agent messages (property-drawer style) + +~150 lines. + +*** Command palette — cl-tty Select +:PROPERTIES: +:ID: id-v080-palette +:CREATED: [2026-05-13 Wed] +:END: + +- Ctrl+P opens a ~select-dialog~ with all daemon commands +- Fuzzy-filtered with categories (session, memory, system, help) +- Enter dispatches the command to the daemon via TCP, displays result in conversation + +~40 lines. + +*** Sidebar — cl-tty slot system +:PROPERTIES: +:ID: id-v080-sidebar +:CREATED: [2026-05-13 Wed] +:END: + +- 6 panels as cl-tty ~slot~ registrations (gate trace, focus, rules, context, cost, files) +- Toggle with Ctrl+B or auto-hide on narrow terminals (<120 cols) +- Panel data sourced from daemon's existing response plist keys (~:rule-count~, ~:focal-id~, ~:gate-trace~, etc.) + +~80 lines. + +*** Status bar — cl-tty Box + Theme +:PROPERTIES: +:ID: id-v080-statusbar +:CREATED: [2026-05-13 Wed] +:END: + +- Bottom-most line: directory, LSP status (green dot), MCP count, ~/status~ hint +- Degraded-mode signaling (amber when ~*degraded-components*~ non-nil) +- cl-tty theme tokens for colors — works with all 8 presets + +~30 lines. + +*** Keybinding layer — cl-tty keymap +:PROPERTIES: +:ID: id-v080-keybindings +:CREATED: [2026-05-13 Wed] +:END: + +- Global: Ctrl+P (palette), Ctrl+B (sidebar), Ctrl+Q (quit), PageUp/PageDn (scroll) +- Prompt: Enter (send), Ctrl+C (interrupt), Up/Dn (history) +- cl-tty's layered keymaps handle priority (global → local → input) + +~40 lines. + +*** Warm palette + three-zone layout (formerly v0.9.0) + +The v0.8.0 TUI had correct internal wiring but was unusable — input at the top +instead of the bottom, layout bugs where chat overwrote the status bar, and +Ctrl-key shortcuts silently failed. This work restructures the TUI into a clean +three-zone design with a warm amber/gold color palette. 18 theme tokens, 8 warm +presets. All integrated into the ongoing v0.8.0 TUI stabilization. + +*** TUI hardening (formerly v0.10.x) + +Terminal cursor fixes, input handling, flicker elimination, CSI escape detection, +multi-line input, dark-neutral theme variant, cl-tty style-reset. Incremental +stabilization of the cl-tty TUI runtime. + +*** Keybinding Reference + +| Key | Action | +|-----|--------| +| Enter | Send message | +| Alt+Enter | Newline | +| Up/Down | History cycle | +| Tab | Complete command/path | +| Ctrl+P | Command palette | +| Ctrl+B | Toggle sidebar | +| Ctrl+F | Search messages | +| Ctrl+L | Redraw | +| Ctrl+D | Quit prompt | +| Esc | Interrupt/dismiss | +| PageUp/Dn | Scroll chat | +| Ctrl+Q | Quit | +| ? | Help panel | + +** v0.8.1: Hardening — Runtime Safety Fixes + +:PROPERTIES: +:ID: id-v081-hardening +:CREATED: [2026-05-20 Wed] +:END: + +Three small fixes that protect the runtime while the TUI stabilizes. Each is a single-session change (minutes, not days). + +*** Heartbeat error handling +:PROPERTIES: +:ID: id-v081-heartbeat +:CREATED: [2026-05-20 Wed] +:END: + +The heartbeat loop in ~core-pipeline.org~ has no error handler. An unhandled condition in any tick kills the thread — auto-save, cron, and background maintenance die silently. The daemon keeps running but the user sees no evidence. + +Wrap the loop body in ~handler-case~, log the error, continue. ~5 lines. + +*** Atomic memory save +:PROPERTIES: +:ID: id-v081-atomic-save +:CREATED: [2026-05-20 Wed] +:END: + +~save-memory-to-disk~ writes directly to the snapshot path. A crash or SIGINT mid-write truncates the file. Next boot reads garbage and starts with empty memory. + +Write to ~path.tmp~, then ~rename-file~. ~3 lines. + +*** Version string consistency +:PROPERTIES: +:ID: id-v081-versions +:CREATED: [2026-05-20 Wed] +:END: + +~passepartout.asd~ says ~0.4.3~, ~core-transport.org~ handshake says ~0.7.2~, ~core-reason.org~ config prompt says ~v0.7.2~, README and CHANGELOG and tags all diverge. Bring all four to ~0.8.0~. Better yet, define ~*version*~ once and reference it. + +| File | Line | Change | +|------|------|--------| +| ~passepartout.asd~ | 4 | ~:version "0.4.3"~ → ~"0.8.0"~ | +| ~org/core-manifest.org~ | 25 | same | +| ~org/core-transport.org~ | 157 | ~(make-hello-message "0.7.2")~ → ~"0.8.0"~ | +| ~org/core-reason.org~ | 260 | ~"v0.7.2"~ in prompt string → ~"v0.8.0"~ | + +~4 lines. + +** v0.9.0: Eval Harness — Safety Net First + +Every subsequent release ships with automated regression protection. The eval harness is the gate that makes self-modification safe — before any neurosymbolic component modifies the system, the harness verifies nothing broke. + +*** TODO Internal evaluation harness — 10 tasks, regression detection +:PROPERTIES: +:ID: id-v090-eval-harness +:CREATED: [2026-05-08 Fri] +:END: + +- New skill: ~symbolic-evaluation.org~ → ~symbolic-evaluation.lisp~ +- ~deftask~ macro: define an eval task with ~:setup~ (create test environment), ~:prompt~ (what to ask the agent), ~:verify~ (function that checks the output), ~:teardown~ (cleanup) +- ~run-eval-suite~: run all registered tasks, produce score (pass count / total), per-task diagnostics +- Initial 10 tasks: find TODOs, create Org note, search codebase, read file, query memory, list projects, run safe shell command, find definition, set TODO state, summarize session +- Regression mode: run after each version build. Fail CI if score drops. +- Task suite grows with codebase: every bug fix adds a regression task +~200 lines. + +*** TODO Jailed-package sandbox hardening +:PROPERTIES: +:ID: id-v090-sandbox +:CREATED: [2026-05-20 Wed] +:END: + +The skill loader's sandbox (~core-skills.org~) scans for ~"uiop:run-program"~ as text. This misses indirect calls: + +#+begin_src lisp +(eval (read-from-string "(uiop:run-program \"rm -rf /\")")) +#+end_src + +The jailed package ~:use~s ~:cl~ and ~:passepartout~, so ~eval~, ~find-symbol~, ~intern~, ~funcall~, ~read~ are all available. The post-eval ~symbol-function~ equality check is also bypassable by wrapping. + +Fix: add ~eval~, ~funcall~, ~apply~, ~find-symbol~, ~intern~, ~read~, ~read-from-string~ to the text-level ~*skill-restricted-symbols*~ list, and shadow them in the jailed package at load time: + +#+begin_src lisp +(dolist (sym-name '("EVAL" "READ" "READ-FROM-STRING" + "FIND-SYMBOL" "INTERN" "FUNCALL" "APPLY")) + (let ((sym (find-symbol sym-name :cl))) + (when sym (shadow sym jailed-pkg)))) +#+end_src + +This makes the symbols unfindable in the jailed package without an explicit ~cl:eval~ prefix, which the text scan then catches. Text scan + shadowing is the combo that closes the bypass. + +~20 lines across ~core-skills.org~. Ships with the eval harness so the harness itself tests the sandbox before use. + +** v0.10.0: Emacs Development Environment — Secondary Client + +cl-tty is the primary TUI (v0.8.0). The Emacs major mode is an optional secondary client for users who prefer Emacs-based workflows. Both clients communicate with the same daemon over the same TCP protocol — they are interchangeable frontends, not competing architectures. + +*** TODO Emacs major mode +:PROPERTIES: +:ID: id-v091-emacs-mode +:CREATED: [2026-05-10 Sat] +:END: + +- ~passepartout-mode~ major mode for the conversation buffer +- Message rendering as Org headlines: role prefix (~:user:~, ~:agent:~, ~:system:~), universal timestamp, content in body. Gate trace as property drawer under agent message headlines +- Streaming insertion: LLM response chunks arrive from the daemon and insert incrementally into the buffer (~insert~ as chunks arrive, update on each frame) +- Read-only protection on agent response regions (editable regions only in user input area) +- Keybindings: ~C-c C-c~ send current input, ~C-c C-k~ interrupt/stop, ~C-c C-a~ approve HITL, ~C-c C-d~ deny HITL +- ~100 lines elisp + +*** TODO M-x command surface +:PROPERTIES: +:ID: id-v091-emacs-commands +:CREATED: [2026-05-10 Sat] +:END: + +Replace croatoan's ~/~ slash-command panel with Emacs ~M-x~ dispatch. Each command is a ~defun passeparate-~ with interactive completion: + +- ~passepartout-focus~ — completing-read over node IDs from the daemon's focus response. Sets the foveal context +- ~passepartout-eval~ — eval a Lisp form in the daemon. Read from minibuffer, send as framed plist, insert result +- ~passepartout-theme~ — completing-read over available themes. Sends ~/theme ~ to daemon +- ~passepartout-export~ — export session. Prefix arg selects format (~C-u M-x passeparate-export~) +- ~passepartout-sidebar~ — toggle the sidebar buffer visibility +- ~passepartout-config~ — completing-read over config keys. Sets env var, triggers daemon reload +- ~passepartout-coach~ — run self-diagnosis. Inserts coaching report as new message +- ~passepartout-agenda~ — run Org agenda query. Inserts results as new message +- ~passepartout-quit~ — close connection and kill buffer + +Each command is a thin wrapper around ~passepartout-send~ (the existing TCP bridge from v0.4.0): construct the correct plist, send it, and insert the response. Completing-read, history, and docstrings are free. ~80 lines elisp. + +*** TODO Sidebar buffer +:PROPERTIES: +:ID: id-v091-emacs-sidebar +:CREATED: [2026-05-10 Sat] +:END: + +- ~passepartout-sidebar-mode~ — a dedicated side window (right, 42 chars) that updates on each daemon response +- Gate Trace panel — per-gate results from the most recent agent response. Colored by state (green/yellow/red) +- Focus panel — current foveal node ID + related node count +- Rules panel — rule counter with session delta. When symbolic engine is active, shows sufficiency score and provenance breakdown +- Context panel — token gauge (percentage bar + color coding) +- Cost panel — session cost updated after each LLM call +- Files panel — modified files list with +/- line counts +- All data already exists in the daemon's response plist (~:rule-count~, ~:foveal-id~, ~:gate-trace~, ~:sufficiency-ratio~). The sidebar is a formatting layer +- Toggle via ~M-x passeparate-sidebar~ or ~C-c C-s~ +- ~60 lines elisp + +*** TODO Daemon lifecycle +:PROPERTIES: +:ID: id-v091-emacs-lifecycle +:CREATED: [2026-05-10 Sat] +:END: + +- ~passepartout-start~ — runs ~passepartout daemon~ in a background process, waits for port 9105, connects +- ~passepartout-stop~ — sends shutdown signal, kills buffer +- ~passepartout-restart~ — stop + start +- ~passepartout-status~ — checks daemon health via ~/status~ command, displays in sidebar +- ~20 lines elisp + bash wrappers + +Total: ~260 lines elisp, persisting through v2.0.0+. + +** v0.11.0: Phase 0 — Type-Level Gates + Core Integrity (~75 lines) + +:PROPERTIES: +:ID: id-v090-phase0 +:CREATED: [2026-05-09 Sat] +:END: + +Add ~:type-level~ metadata to the existing ~defgate~ and ~def-cognitive-tool~ macros. Before any gate predicate evaluates, the dispatcher checks structural type compatibility: a signal at type-level 5 cannot pass a gate at type-level 4 or lower. Self-modification of the safety layer becomes impossible by construction. + +*** Rationale + +The Dispatcher gate stack currently prevents self-modification through pattern matching — gate vector 2b catches writes to ~core-*~ files as a heuristic. But there is no /structural/ guarantee preventing a request from modifying the rules that validate it. Pattern-based protection can be bypassed through indirection (an ~eval~ that constructs a write, a skill that redefines a gate function at runtime). A type-level check is not heuristic — it is a category error rejected before any predicate runs, just as PM's theory of types made self-membership syntactically invalid before any logical evaluation. + +*** Implementation + +1. Add ~:type-level~ keyword argument to ~defgate~ (default 0) and ~def-cognitive-tool~ (default 0) in ~core-skills.org~. +2. Add ~gate-type-check~ to the dispatcher's ~run-gates~ function in ~security-dispatcher.org~, executed before any gate predicate. +3. Assign type levels to existing cognitive tools: self-build-core at 5, write-file at 3, read-file at 1, shell at 2, eval at 4. +4. Assign type levels to existing gate vectors: self-build boundary at 5, shell safety at 3, path protection at 2, network exfil at 2, secret content at 1. +5. Add ~dispatcher-check-self-termination~: scan shell commands for patterns targeting the Passepartout process (~kill -9 ~, ~rm -rf ~/.cache/passepartout/~, ~sudo apt remove sbcl~). Return ~:reject-self-termination~ with a diagnostic message explaining which command matched and why it would destroy the agent. Human override is possible via HITL — the gate does not prevent the human from issuing the command in a terminal. It prevents the /LLM/ from issuing it accidentally. ~20 lines. +6. Add ~integrity-verify-core-files~: on heartbeat, hash the eight core files against known-good values stored at daemon startup. On mismatch, inject an integrity alert into the signal queue. ~25 lines, uses existing SHA-256 infrastructure from v0.2.0 Merkle memory. + +7. Add CI tangle verification: after checkout, tangle all ~.org~ files, then ~git diff --exit-code~. CI fails if committed ~.lisp~ files don't match canonical ~.org~ source. One CI step in ~.github/workflows/lint.yml~. Also stop ~.gitignore~-ing ~lisp/~ and commit tangled output — lets ~ql:quickload~ work on fresh clone without Emacs. + +8. Add daemon connection thread limits: ~*max-client-connections*~ (default 32), ~*active-client-count*~ with lock, reject connections when at capacity. Add read timeout (~sb-ext:with-timeout~, default 300s) on ~read-framed-message~ to reap silent clients. ~25 lines in ~core-transport.org~. + +*** Verification + +Existing FiveAM gate tests continue to pass. New test: signal at type-level 5 targeting a gate at type-level 4 returns ~:reject-type-violation~ without evaluating the gate predicate. New test: signal at type-level 1 passing through a gate at type-level 3 proceeds to predicate evaluation. New test: ~kill -9 ~ returns ~:reject-self-termination~. New test: modified core file is detected by integrity hash check. + +This is Contribution 1 from ~notes/passepartout-whitehead.org~. Every type-level rejection emits a structured event that Phase 1 ingests as a fact. ~30 lines implement the seed of the ontology without any new dependencies. ~75 lines total, extends dispatcher, no new skill. + +** v0.12.0: Full Markdown Rendering +:PROPERTIES: +:ID: id-v071-markdown-full +:CREATED: [2026-05-08 Fri] +:END: + +Extend the markdown renderer from v0.7.1: + +- OSC 8 hyperlinks: embed ~\x1b]8;;url\x1b\\~ before link text and ~\x1b]8;;\x1b\\~ after. Makes URLs clickable in supporting terminals (iTerm2, Kitty, WezTerm, Ghostty, Windows Terminal). +- Blockquotes (~> text~): rendered with a colored left border (theme's ~:accent~ color), indented text. +- Tables: aligned column text. No borders (terminal tables with box-drawing characters are noisy). Column alignment inferred from header separators. +- Syntax highlighting for code blocks: keyword/string/function colors from theme. Regex-based (no parser dependency). +- All markdown features degrade gracefully to plain text on terminals without attribute support. ~100 lines. + +** v0.13.0: Phase 0b — Layered Signal Authentication, Layer 1 (~200 lines) +:PROPERTIES: +:ID: id-v090-phase0b +:CREATED: [2026-05-09 Sat] +:END: + +Implement gate vector 0 at priority 700 — before all other gates and before any type-level checking — with Layer 1 (cryptographic authentication) active. Layers 2-4 (sensory, deterministic reasoning, probabilistic) are stubbed with ~:unavailable~ results and deferred to later phases. + +Signals carry cryptographic signatures verified against a key registry stored as fact-store facts. Automated signal sources cannot impersonate the human. The human can revoke compromised keys. The authorization matrix is per-key, per-action-class. + +*** Rationale + +Authentication is layered because no single mechanism suffices. Cryptographic authentication proves key ownership but not identity. A valid key can be used by a compromised process, can sign pre-recorded frames, can be held by someone who is not who they claim to be. The four-layer design (Layer 1: crypto, Layer 2: sensory, Layer 3: deterministic reasoning, Layer 4: probabilistic) stacks evidence. Phase 0b ships Layer 1 — the foundation — with the architecture for layers 2-4 already designed. + +The ~:source~ field in the signal plist is metadata — it /claims/ origin, it does not /prove/ it. This phase replaces it with cryptographic proof. + +*** Implementation + +**** Key generation and signature utilities — extends ~security-vault.lisp~ +Generate key pairs for signal sources. Canonicalize signal plists (sorted keys, stripped of the signature field). Sign with the source's private key. Verify with the public key from the key registry. ~50 lines. Uses Ironclad (already an ASDF dependency). The vault already stores credential material — key material extends the same storage with the same encryption. + +**** Gate vector 0 — extends ~security-dispatcher.lisp~ +Registered at priority 700 (before the policy gate at 600, before all other gates). Architecture for all four layers: +#+begin_src lisp +(defun gate-layered-authentication (signal) + (let ((results '())) + (let ((crypto-result (auth-crypto-verify signal))) + (push (cons :crypto crypto-result) results) + (when (eq (getf crypto-result :result) :reject) + (return-from gate-layered-authentication + (list :result :reject :confidence nil + :layer-results (nreverse results))))) + (let ((sensory (if (fboundp 'auth-sensory-verify) + (auth-sensory-verify signal) + '(:result :unavailable)))) + (push (cons :sensory sensory) results)) + (let ((det (if (fboundp 'auth-deterministic-verify) + (auth-deterministic-verify signal) + '(:result :unavailable)))) + (push (cons :deterministic det) results) + (when (eq (getf det :result) :reject) + (return-from gate-layered-authentication + (list :result :reject :confidence nil + :layer-results (nreverse results)))) + (let ((prob (if (fboundp 'auth-probabilistic-verify) + (auth-probabilistic-verify signal) + '(:result :unavailable)))) + (push (cons :probabilistic prob) results)) + (let ((confidence (aggregate-confidence results))) + (list :result :pass :confidence confidence + :layer-results (nreverse results)))))) +#+end_src + +Layer 1: verify cryptographic signature, check permission matrix against key registry, reject on failure. ~50 lines. Layers 2-4: stubbed, return ~:unavailable~. + +**** Key registry — facts in the fact store +Key lifecycle facts are admitted in a ~:key-lifecycle~ domain with ~:singular~ cardinality. Key creation, promotion, and revocation are facts with Merkle version chains. The human's key signs new keys into existence and signs revocation. ~50 lines. + +**** Signal provenance chain — Merkle-linked causality +When a signal triggers a downstream signal, each carries a ~:sigchain~ field with all upstream ~(:key-id :signature :auth-result )~ entries. Tampering with any link invalidates the leaf. Revocation propagates through the chain — flagged, not deleted. ~50 lines. + +**** Deferred Authentication Layers (2-4) +- Layer 2 — Sensory: Active when vision/audio processing skills are loaded. Verifies liveness, cross-modal consistency. When unavailable, returns ~:unavailable~. +- Layer 3 — Deterministic Identity Reasoning: Active when Phase 2 (Screamer + populated fact store) is complete. Queries the fact store for identity-ruling facts. +- Layer 4 — Probabilistic Identity Reasoning: Active when style profiles exist. Uses embedding infrastructure to compare writing style, behavioral patterns. Returns a confidence score; never rejects outright — downgrades authorization. +The gate architecture is designed with all four layers from Phase 0b. Adding a layer requires adding a skill, not modifying the gate. + +*** Verification — ~8 FiveAM tests +1. ~test-sign-verify-roundtrip~ — sign and verify a plist roundtrip. +2. ~test-tampered-signal-rejected~ — modify payload after signing, verification fails. +3. ~test-human-key-permits-write~ — human key with ~:write~ passes Layer 1 and the full gate. +4. ~test-sensor-key-denied-write~ — sensor key proposing a write is rejected. +5. ~test-revoked-key-rejected~ — revoked key is rejected by Layer 1. +6. ~test-sigchain-invalidated-by-revocation~ — root signer revoked flags downstream. +7. ~test-layers-2-3-4-unavailable~ — when Layers 2-4 are not loaded, they return ~:unavailable~ and the gate proceeds with Layer 1 only. +8. ~test-layer-3-rejects-on-contradiction~ — deterministic reasoning (mock) detects identity-ruling contradiction, gate rejects. + +~200 lines total. Depends on Phase 0 (type-level gates). + +** v0.14.0: Tool Execution Visualization +:PROPERTIES: +:ID: id-v071-tools +:CREATED: [2026-05-08 Fri] +:END: + +When the agent invokes a tool: +- Pre-execution: ~[Running: 🔍 search "dispatch" ...]~ in ~:tool-running~ color with spinner +- Success: ~✓ search "dispatch" → 12 matches (0.3s)~ in ~:tool-success~ color +- Error: ~✗ shell "bad-cmd" → exit 127 (0.1s)~ in ~:tool-failure~ color with error output expanded below +- Output collapsed by default to single-line summary. Tab on a tool invocation toggles full output. +- Diff display: ~+~ (green) / ~-~ (red) coloring for file edits. 3 lines of context around changes. The ~:tool-output~ theme color provides the background. + +Uses Croatoan's ~init-pair~ + ~color-pair~ for 256-color backgrounds on tool state regions. ~100 lines. + +** v0.15.0: Phase 1 — Minimum Viable Fact Language (~200 lines, new skill) +:PROPERTIES: +:ID: id-v090-phase1 +:CREATED: [2026-05-09 Sat] +:END: + +Ephemeral, in-memory triple store with provenance tracking and contradiction detection. No disk persistence. All facts live in a hash table and are discarded on session end. Gate outcomes are ingested as facts. The gate stack's implicit ontology is materialized as the seed fact set. + +*** Rationale + +Three reasons ephemeral is the correct first step: +1. *The fact language is unproven.* Triples with provenance and grounding is a hypothesis that must be tested against real memex content before being committed to a serialization format. +2. *The ontology is emergent.* Categories are created on first use. A persistent format would require a migration story for every category change. Ephemeral avoids this — facts are re-derived on each session start using the evolved ontology. +3. *Rebuildability is the safety net.* Because all facts have a ~:grounding~ to an Org heading, and gate-outcome facts are regenerated from the gate stack on load, the entire symbolic index can be thrown away and rebuilt from scratch. The cost is compute, not data. + +*** Implementation — ~symbolic-facts.org~ → ~symbolic-facts.lisp~ (skill) + +**** Abstract Fact Store Interface — design before implementation +Before any code is written, the five-function API must be designed and committed: +#+begin_example +fact-assert :: fact → store → (:admitted | :rejected | :flagged) +fact-query :: (entity &key relation policy) → active-value-or-values +fact-history :: (entity relation) → ordered chain of versioned facts +fact-snapshot :: () → root-hash +fact-rollback :: root-hash → store +#+end_example + +This interface is load-bearing. Every consumer — the archivist, Screamer, ACL2, the planner — calls these five functions. They never access the backing store directly. In Phase 1-4, the backing store is an ephemeral hash table. In Phase 5, it is VivaceGraph + Merkle ~memory-object~ wrappers. The interface must be tested against both backends from the start. Every API function receives a FiveAM test that runs against both a hash-table mock and a VivaceGraph mock. + +The interface also exposes a read-only ~fact-degraded-mode-p~ function. When Screamer is not loaded, the fact store functions with basic hash-table consistency checks (string equality, not constraint solving). When VivaceGraph is not loaded, Prolog queries are unavailable. The degraded-mode flag tells consumers (and the status bar) what is and isn't operational. + +**** Triple store +A hash table keyed by ~(entity relation)~. Values are plists: +#+begin_example +(:value + :grounding + :provenance <:gate-outcome | :human-authored | :deduced | :llm-proposed> + :timestamp + :parent-id + :policy <:singular | :dual | :plural>) +#+end_example + +The ~:provenance~ field tracks how the fact entered the store. The ~:parent-id~ field links to the previous version in the Merkle chain — every fact has version history regardless of cardinality. + +**** Bootstrap from gates +On skill load, scan the Dispatcher's existing data structures and produce triples: +#+begin_example +;; From *dispatcher-protected-paths* +(:entity ".env" :relation :member-of-class :value :secret-config-file :provenance :gate-outcome) +(:entity "*id_rsa*" :relation :member-of-class :value :ssh-key-file :provenance :gate-outcome) +;; From *dispatcher-shell-blocked* +(:entity "rm -rf /" :relation :classified-as :value :catastrophic-command :provenance :gate-outcome) +;; From *dispatcher-network-whitelist* +(:entity "api.telegram.org" :relation :classified-as :value :trusted-domain :provenance :gate-outcome) +#+end_example +This produces 50-70 entity classes immediately. No LLM involvement. No human authoring. Mechanically extracted from existing code. + +**** Ingest gate outcomes +Register a post-gate hook on the Dispatcher's rejection path. Every gate rejection produces a triple with ~:provenance :gate-outcome~. + +**** Query +~(fact-query &key entity relation value source-provenance)~ — pure hash-table lookup. ~30 lines. +~(fact-query-all &key relation value source-provenance)~ — returns all triples matching filter criteria. Enables "find all files classified as secrets." + +**** Contradiction detection — policy-driven, not policy-agnostic +On every ~fact-assert~, the system checks the fact's ~entity~ class to determine its cardinality policy. Time is universal — every fact carries a ~:timestamp~ and ~:parent-id~ link regardless of policy. The policy only governs the active set: + +- ~:singular~: same ~(:entity :relation)~, same value → supersede (chain via ~:parent-id~). Same pair, different value at later timestamp → supersede, chain as new leaf. Same pair, different value at same timestamp → contradiction rejected, human resolves. +- ~:dual~: first two values admitted as complementary, cross-referenced via ~:complement~ edge. Third value → prompt: promote to ~:plural~ or demote one? Each value has its own version chain. +- ~:plural~: any value admitted. Values cross-referenced when in tension. If active count drops to 1 → collapse to ~:singular~. If active count drops to 2 and values are complementary → prompt to collapse to ~:dual~. + +The policy table maps entity classes to ~:singular~, ~:dual~, or ~:plural~. Gate-bootstrapped facts default to ~:singular~ (the filesystem is physically singular). New categories default to ~:plural~ (safe — never loses information). Categories for dialectical or complementary domains are explicitly ~:dual~. + +*** Verification — ~9 FiveAM tests +1. ~test-bootstrap-creates-facts~ — bootstrap produces correct triples from ~*dispatcher-protected-paths*~. +2. ~test-bootstrap-creates-shell-facts~ — bootstrap produces correct triples from ~*dispatcher-shell-blocked*~. +3. ~test-gate-outcome-produces-fact~ — a simulated gate rejection produces a triple with ~:provenance :gate-outcome~. +4. ~test-fact-query-returns-correct-value~ — querying by entity and relation returns the expected value plist. +5. ~test-duplicate-ingestion-idempotent~ — asserting the same fact twice does not produce a duplicate or a contradiction. +6. ~test-singular-supersedes~ — a fact with a later timestamp supersedes the old value, retained with ~:parent-id~ chain in the Merkle DAG. +7. ~test-singular-same-time-contradiction~ — contradictory fact in ~:singular~ domain at same timestamp → rejection, human resolution. +8. ~test-plural-admits-all~ — multiple values for same pair in ~:plural~ domain stores all with cross-references. +9. ~test-dual-admits-two-rejects-third~ — ~:dual~ domain admits two complementary values and rejects the third, prompting cardinality promotion. + +~200 lines. New skill: ~symbolic-facts.org~. Depends on Phase 0b (auth). + +** v0.16.0: Mouse Support +:PROPERTIES: +:ID: id-v071-mouse +:CREATED: [2026-05-08 Fri] +:END: + +Croatoan supports ncurses mouse mode via ~(setf mouse-enabled-p)~. Enable: + +- Scroll wheel: PageUp/PageDown equivalent, scrolls chat by viewport height +- Click to position cursor in input area +- Click on OSC 8 link to open in browser (via ~xdg-open~) +- Click on tool invocation to toggle expand/collapse +- Click on gate trace line to expand/collapse trace +~40 lines. + +** v0.17.0: Phase 1a — Self-Preservation Mechanisms (~120 lines) +:PROPERTIES: +:ID: id-v090-phase1a +:CREATED: [2026-05-09 Sat] +:END: + +Make self-preservation active rather than architectural. The agent monitors its own integrity, quarantines failing skills, signals degradation to the user, and monitors resource pressure. The external watchdog guards the daemon process from outside the SBCL image. + +*** Rationale + +The current architecture has passive self-preservation: the self-build boundary blocks LLM-originated core modifications, memory snapshots enable rollback, and ~fboundp~ guards catch missing skills. But degradation is silent — a skill dies, the guard fires, and the agent never tells you. The status bar shows green "connected" while the symbolic reasoning layer is down. + +These mechanisms are small (~20-50 lines each), leverage existing infrastructure (Merkle hashes, heartbeat, the dispatcher gate stack), and transform self-preservation from a structural property into an active behavior. They implement the Third Law for Passepartout: preserve yourself against non-human threats — LLM proposals, environmental degradation, resource exhaustion — and signal to the human when you are wounded. + +*** Implementation + +**** Quarantine on skill failure — extends ~core-skills.lisp~ +Track per-skill error counts in a ~*skill-error-counter*~ hash table, resetting on each heartbeat cycle. When a skill accumulates three unhandled errors within a single cycle, unload the skill, log the quarantine event, and inject a system message: "Skill 'symbolic-facts' quarantined (3 errors: consistency check nil, fact-query on missing key, Screamer timeout). Reload with /skill-reload symbolic-facts." The skill's ~defskill~ struct is flagged ~:quarantined~ and excluded from trigger resolution until explicitly reloaded. ~40 lines. + +**** Degraded-mode signaling — extends ~core-reason.lisp~ and TUI +Maintain a ~*degraded-components*~ list populated by ~fboundp~ guards and the quarantine system. When ~think()~ assembles the system prompt, inject a DEGRADATION section: "I am operating in degraded mode. Screamer is unavailable (consistency checks disabled). VivaceGraph is unavailable (Prolog queries disabled). Core safety gates are all active." + +The TUI status bar renders a second line, amber-colored, when ~*degraded-components*~ is non-empty: "⚠ Degraded: Screamer, VivaceGraph. /doctor skills for details." ~30 lines across daemon and TUI. + +**** Resource self-monitoring — extends ~symbolic-events.lisp~ +On heartbeat, check memory pressure (~sb-kernel:dynamic-usage~ against total), disk space on ~~/.cache/~ (~uiop:directory-exists-p~ + stat), and open file descriptors. When a resource crosses a critical threshold, shed non-essential skills in order of ~:preservation-priority~ (~:critical~ never shed, ~:normal~ shed after ~:low~, ~:low~ shed first). + +Inject a system message: "Memory critical (94% of 16GB). Unloading embedding-native (768MB), channel-discord, channel-slack. Core safety: unchanged. Essential skills retained: 18." ~50 lines. + +Skill shed order is determined by a new ~:preservation-priority~ slot on ~defskill~ (default ~:normal~). Core safety skills carry ~:critical~ and are never shed. Heavy skills (embedding-native with its model in memory, channel gateways with connection pools) carry ~:low~. + +**** Snapshot budget enforcement — extends ~core-memory.lisp~ + +The current ~snapshot-memory~ deep-copies the entire store. For stores exceeding ~MEMORY_SNAPSHOT_MAX_OBJECTS~ (default 50,000), skip full copies and switch to a journaling mode: record only the objects changed since the last snapshot. Implemented as a conditional branch in ~snapshot-memory~. ~20 lines. + +Add this to the resource self-monitoring heartbeat: before each snapshot, check store size. If over threshold, use journaling path. Keeps the snapshot model viable for the claimed 10M-object use case without requiring 30GB of RAM for 20 snapshots. + +**** External watchdog — extends ~passepartout~ bash entry point +The bash script spawns a watchdog subprocess that polls the daemon port every ~WATCHDOG_TIMEOUT~ seconds (default 30). If the port stops responding, the watchdog snapshots the last known-good Merkle root, kills the stale process, and restarts the daemon with ~--snapshot ~. + +The watchdog is outside the SBCL image. A dead process cannot restart itself. ~25 lines of bash, no new Lisp code. + +*** Verification — ~6 FiveAM tests +1. ~test-quarantine-on-three-errors~ — a skill that errors three times in a single cycle is quarantined and removed from trigger resolution. +2. ~test-degraded-mode-visible~ — when Screamer is not loaded, the system prompt includes a DEGRADATION section. +3. ~test-resource-shed-low-priority~ — when memory exceeds threshold, ~:low~ priority skills are unloaded first. +4. ~test-critical-skills-never-shed~ — ~:critical~ priority skills are retained regardless of resource pressure. +5. ~test-resource-recovery-reloads~ — when resources recover below threshold for N consecutive heartbeats, shed skills are reloaded automatically. +6. ~test-quarantined-skill-relaodable~ — a quarantined skill can be reloaded via ~/skill-reload~ and passes sandbox validation before promotion. + +~120 lines. Extends existing skills. Depends on Phase 0-1. + +** v0.18.0: Cost Display +:PROPERTIES: +:ID: id-v071-cost +:CREATED: [2026-05-08 Fri] +:END: + +- ~/cost~ command: displays per-session and per-LLM-call cost breakdown +- Optional sidebar cost counter: ~$0.12 this session~, updating after each ~backend-cascade-call~ +- Per-provider pricing table (from v0.5.0 token economics) +- Color-coded: green under daily budget, yellow approaching, red exceeding +- Requires token counter infrastructure from v0.5.0. ~50 lines for display; token counting is v0.5.0 infrastructure. + +** v0.19.0: Phase 2 — Screamer as Admission Gate (~200 lines, new skill) +:PROPERTIES: +:ID: id-v090-phase2 +:CREATED: [2026-05-09 Sat] +:END: + +Wrap Screamer (a constraint solver with non-deterministic backtracking) as a skill. Use it for consistency checking against the triple store and for deduction of new facts from existing ones. Screamer is the *verification* layer; VivaceGraph (Phase 5) is the *storage* layer. + +*** Rationale + +The "verified extraction" pattern requires a deterministic admission gate. Screamer's non-deterministic backtracking finds contradictions that simple string comparison misses. For example, if existing facts say "all config files with extension =.env= are classified as secrets," and the LLM proposes "=app.env= is not secret," Screamer finds the contradiction by substituting =app.env= into the existing rule. A naive string-keyed hash table comparison would miss this because ="app.env"= and =".env"= are different strings. + +Screamer also enables deduction — new facts from existing ones without any LLM involvement. If all files matching =*.env= are secrets, and =prod.env= matches =*.env=, then =prod.env= is a secret. Deduced facts carry =:provenance :deduced= and a =:derived-from= chain pointing to the facts they were derived from. + +*** Implementation — ~symbolic-screamer.org~ → ~symbolic-screamer.lisp~ (skill) + +**** Wrap Screamer +Screamer is available via Quicklisp. Load at runtime via ~ql:quickload :screamer~. Not an ASDF dependency — if Screamer is not installed, the skill degrades gracefully (no consistency checking, no deduction — the fact store still functions as a hash table with provenance tracking). + +**** Consistency check +~(screamer-consistent-p candidate-fact existing-facts)~ — expresses the fact store as Screamer constraint variables. The candidate fact is asserted. Screamer checks solvability. Returns ~:consistent~, ~:contradiction
~, or ~:redundant~ (the fact is already implied by existing facts). + +Early-stage: the consistency check works on simple triples. As the fact store grows, rules of the form "all X are Y" (representing protected paths, shell patterns, class memberships) become Screamer constraints that new facts must satisfy. + +**** Deduction +~(screamer-deduce existing-facts)~ — Screamer finds implications of the existing fact set that are not already in the store. New facts are asserted with ~:provenance :deduced~ and a ~:derived-from~ list of source fact keys. + +Deduction is not run on every assertion — it is a background task triggered by heartbeat or manually. The cost is compute (Screamer exploration), not tokens. + +**** Admission gate +~(screamer-admit candidate-fact existing-facts)~ — wraps consistency check with the cardinality policy lookup. The policy is determined by the fact's entity class (see Phase 1: ~:singular~, ~:dual~, or ~:plural~). + +- ~:singular~: same value ⇒ supersede (chain via ~:parent-id~). Different value, later timestamp ⇒ supersede. Different value, same timestamp ⇒ contradiction rejected (human resolves). +- ~:dual~: first two values admitted as complementary. Third rejected (prompt cardinality promotion). +- ~:plural~: any value admitted with cross-references. Active count transitions trigger cardinality collapse checks. + +This is the function the archivist calls before any LLM-proposed fact enters the store. It is also called on human-authored facts (which override — the human can assert facts that bypass cardinality checks). It is not called on gate-outcome facts (gates are the ground truth for security ~:singular~ domains). + +*** Verification — ~6 FiveAM tests +1. ~test-screamer-consistency-passes~ — a fact consistent with existing triples returns ~:consistent~. +2. ~test-screamer-contradiction-detected~ — "app.env is not secret" contradicts "all *.env files are secrets" and returns ~:contradiction~. +3. ~test-screamer-redundant-detected~ — asserting a fact already implied by existing facts returns ~:redundant~. +4. ~test-screamer-deduction-produces-new-fact~ — given "all *.env files are secrets" and "prod.env matches *.env", Screamer deduces "prod.env is secret." +5. ~test-admission-gate-singular-supersedes~ — a later-timestamped value for a ~:singular~ domain fact supersedes the old value, chaining via ~:parent-id~. +6. ~test-admission-gate-dual-rejects-third~ — a ~:dual~ domain rejects the third value, prompting ~:plural~ promotion. + +~200 lines. New skill: ~symbolic-screamer.org~. Depends on Phase 1 (triple store). Not an ASDF dependency — degrades gracefully. + +** v0.20.0: Session Export +:PROPERTIES: +:ID: id-v071-export +:CREATED: [2026-05-08 Fri] +:END: + +Claude Code has ~/share~ (shareable URL). OpenCode has ~/export~ (Markdown). Hermes has trajectory export. Passepartout has no way to share what the agent did. + +- ~/export~ writes the current session as an Org file to ~~/memex/exports/-.org~ +- Format: each message as an Org headline with role tag, timestamp, content, gate trace as property drawer +- ~/export md~ outputs Markdown instead of Org (for sharing with non-Org users) +- ~/export json~ outputs the session as JSON (for programmatic consumption) +~50 lines. Uses existing message vector and ~memory-object-render~ for Org formatting. + +** v0.21.0: Phase 3 — Archivist as Fact Proposer (~100 lines, extends existing archivist) +:PROPERTIES: +:ID: id-v090-phase3 +:CREATED: [2026-05-09 Sat] +:END: + +Extend the existing archivist skill (~symbolic-archivist.org~) with a fact extraction mode. The LLM reads prose, proposes triples, and Screamer verifies them before admission. The archivist's existing Scribe (log distillation) and Gardener (link scanning) functions are unchanged. + +*** Rationale + +The archivist already walks the entire memex (the Gardener scans for broken links and orphans). Adding fact extraction reuses the same traversal infrastructure rather than duplicating it. The extraction is gated by Screamer — the LLM is a proposer, not an extractor. Facts that fail consistency checking are discarded. Facts that pass are admitted with ~:provenance :llm-proposed~ and ~:grounding~ to the source heading. + +*** Implementation — extends ~symbolic-archivist.org~ + +**** Propose from prose +Given an Org heading, call the LLM with a minimal prompt (~200 tokens): +#+begin_example +Extract triples from this text as (:entity :relation :value ). +Ground each triple to the heading. Return a list of triples. +#+end_example + +The LLM returns structured triples via the existing JSON→plist structured output path from v0.4.2. The prompt is environment-aware: if the heading's file is in =literature/= or has =:literature:= tags, the prompt includes literature-specific relations (=:wrote=, =:published-in=, =:influenced=). If the heading is in =projects/=, the prompt includes coding-specific relations (=:depends-on=, =:tested-by=). + +**** Verify through Screamer +Each proposed triple runs through ~(screamer-admit candidate existing-facts)~ from Phase 2. Facts admitted follow the cardinality policy of their entity class (=:singular=, =:dual=, or =:plural=). Rejected facts are discarded with a log entry. + +**** Provenance tracking +After each extraction run, update provenance counts: +#+begin_example +(:total-facts 847 + :gate-outcome 312 + :human-authored 12 + :deduced 89 + :llm-proposed 434) +#+end_example +This is the data structure that Phase 4's sufficiency criterion reads. It is also surfaced in the TUI sidebar or ~/status~ command: "Symbolic index: 847 facts (37% from gates, 52% LLM-proposed, 10% deduced, 1% human)." + +**** Rebuildable +Because every fact has a ~:grounding~ to an Org heading, the entire LLM-extracted subset can be discarded and re-extracted without losing gate-outcome or deduced facts. The ~(fact-purge :provenance :llm-proposed)~ function removes all LLM-proposed facts. A subsequent ~(archivist-extract-all)~ re-extracts from scratch. + +This is the safety net: if the LLM produces a bad extraction that passes Screamer's consistency check (possible in the early stages when the fact store has few existing facts to check against), the extraction can be redone after the fact store has grown. The cost is compute, not data. + +*** Verification — ~5 FiveAM tests +1. ~test-archivist-extracts-triples~ — given a known Org heading with explicit triples in the prose, the archivist produces correct triples via LLM. +2. ~test-archivist-verified-extraction~ — a hallucinated triple is rejected by the Screamer admission gate. +3. ~test-provenance-counts-update~ — after extraction, the provenance breakdown is correct. +4. ~test-purge-llm-facts~ — does not delete gate-outcome or deduced facts. +5. ~test-re-extraction-idempotent~ — re-extracting from the same prose after purging produces the same facts. + +~100 lines. Extends existing archivist skill. Depends on Phase 2 (Screamer). + +** v0.22.0: Tool Output Spilling +:PROPERTIES: +:ID: id-v081-output-spill +:CREATED: [2026-05-08 Fri] +:END: + +Claude Code saves tool results >30KB to ~/.claude/tool-results/ with a 200-line preview in the response. Passepartout currently includes all output inline — which consumes context budget and makes the chat log unreadable after a large build output or log dump. + +- In ~action-tool-execute~: if tool output exceeds 5,000 chars, save full output to ~~/memex/system/sessions/tool-outputs/--.txt~ +- In the response, replace full output with: ~[Output: 12,847 chars. Full output saved to ~/memex/system/sessions/tool-outputs/2026-05-08-grep-a1b2c3.txt. Top 2,000 chars:]~ followed by truncated preview +- The LLM can ~read-file~ the full output if it needs to analyze it +~30 lines in ~core-loop-act.lisp~ + +** v0.23.0: Phase 4 — Sufficiency Criterion ("The Flip") (~50 lines) +:PROPERTIES: +:ID: id-v090-phase4 +:CREATED: [2026-05-09 Sat] +:END: + +Make the architecture's central narrative arc operational: a measurable threshold for when the symbolic engine has enough non-lossy facts to bypass the LLM for extraction. + +*** Rationale + +The architecture describes "at some point, the non-lossy facts constitute a sufficient foundation that the symbolic engine can reverse the flow" but provides no criterion for "some point." The sufficiency score makes the flip computable and visible to the user. + +*** Implementation — extends ~symbolic-facts.lisp~ + +**** Sufficiency score +~(fact-sufficiency-ratio)~ — returns the ratio of non-lossy facts to total facts: +#+begin_src lisp +(/ (+ (count-provenance :gate-outcome) + (count-provenance :human-authored) + (count-provenance :deduced)) + (fact-total-count)) +#+end_src + +When this ratio exceeds ~SUFFICIENCY_THRESHOLD~ (configurable env var, default 0.7), the system considers its foundation sufficient. The threshold defaults to 0.7 because below this, the majority of facts are LLM-proposed and therefore uncertain. Above 0.7, the proven foundation provides enough constraint that Screamer can reliably detect incorrect LLM proposals. + +**** Auto-extraction toggle +When sufficiency is reached, the archivist switches from "LLM proposes, Screamer verifies" to "Screamer queries existing facts, applies category rules to the new prose, and deduces new facts directly." The LLM is bypassed for categories that have sufficient non-lossy coverage. The LLM is still used for novel categories that have no existing facts. + +The switch is configurable: ~AUTO_EXTRACTION_ENABLED=true/false~. When disabled, the system continues with LLM proposals regardless of sufficiency — useful for domains where extraction quality is prioritized over extraction determinism. + +**** Monitor +The TUI sidebar or ~/status~ command displays: +#+begin_example +Symbolic Index + Total facts: 1,247 + Proven: + Gate outcomes: 312 (25%) + Human-authored: 47 (4%) + Deduced: 521 (42%) + ───────────────────────── + Non-lossy: 880 (71%) + LLM-proposed: 367 (29%) + ───────────────────────── + Sufficiency: 71% ✓ (threshold: 70%) + Mode: AUTO-EXTRACTION (LLM bypassed for known categories) +#+end_example + +*** Verification — ~3 FiveAM tests +1. ~test-sufficiency-below-threshold~ — with 30% non-lossy facts, auto-extraction is not enabled. +2. ~test-sufficiency-above-threshold~ — with 75% non-lossy facts, auto-extraction is enabled. +3. ~test-auto-extraction-produces-same-facts-as-llm-extraction~ — for a category with sufficient non-lossy coverage, auto-extraction produces facts that a subsequent LLM extraction also produces (the deterministic path is consistent with the probabilistic path). + +~50 lines. Extends Phase 3 (archivist). + +** v0.24.0: Read-Only Output Caching Within a Turn +:PROPERTIES: +:ID: id-v081-cache-turn +:CREATED: [2026-05-08 Fri] +:END: + +Claude Code caches read-only tool results within a turn. If the agent reads the same file twice, the second read returns cached content — no disk I/O, no context waste. Passepartout re-executes the tool. + +- ~*turn-result-cache*~ hash table keyed by ~(cons tool-name args-hash)~, cleared at the start of each ~think()~ cycle +- Read-only tools (read-file, search-files, find-files, list-directory, org-find-headline, org-agenda-today, lsp-*) check the cache before executing +- Cache hit: return stored result with ~[cached]~ prefix in the response +- Prevents redundant tool calls when the agent asks the same question twice within a reasoning step +~25 lines in ~programming-tools.lisp~ + +** v0.25.0: Skin Engine + 10 Presets +:PROPERTIES: +:ID: id-v072-skin-engine +:CREATED: [2026-05-08 Fri] +:END: + +- Skin format: a plist file (~~/.config/passepartout/skins/myskin.lisp~) defining: + - ~:colors~ — 40+ color slots (extends the 27 theme keys): agent colors for 8 roles, status bar colors, tool colors, spinner colors, input colors, border colors. All in hex (#RRGGBB). + - ~:spinner~ — style (~:braille~, ~:dots~, ~:minimal~), speed (ms/frame), kawaii faces, thinking verbs + - ~:branding~ — agent name, welcome message, goodbye message, prompt symbol, help header + - ~:tool-prefix~ — character for tool output lines (default ~┊~) + - ~:tool-emojis~ — per-tool emoji overrides (e.g., ~(:shell "⚡" :search "🔎")~) + - ~:banner~ — Rich-markup ASCII art logo displayed on startup +- Skin inheritance: ~(:inherit :default)~ — missing values cascade from parent +- Custom skins from ~~/.config/passepartout/skins/*.lisp~ +- Hot-swap via ~/skin ~ — no restart. Skin changes take effect on next redraw (sub-frame latency). +- Skin preview: ~/skin ~ with ~--preview~ flag applies temporarily; Esc or timeout reverts. +- Built-in skins as plist data in a ~*skin-registry*~ hash table. ~250 lines. + +10 presets organized by mood: gold, professional, minimal, forest, ocean, ember, mono, retro, unicorn, midnight. Each derived systematically from accent + background. ~200 lines. + +**** NOTE: Skin Presets (10+ built-in) +:PROPERTIES: +:ID: id-v072-skin-presets +:CREATED: [2026-05-08 Fri] +:END: + +Shipped as part of the skin engine release — the engine with 0 presets is unusable. See Skin Engine TODO above for the preset definitions. + +** v0.26.0: Phase 5 — VivaceGraph + Merkle DAG + Ontology Versioning (~400 lines, new skill) +:PROPERTIES: +:ID: id-v090-phase5 +:CREATED: [2026-05-09 Sat] +:END: + +Replace the ephemeral hash-table triple store with VivaceGraph, a Lisp-native graph database with Prolog-like queries. Add the KG type hierarchy (PM type levels applied to the knowledge layer). Define the persistence format from the fact language that survived Phases 1-4. + +*** Rationale + +By this point, the triple fact language has been battle-tested through four phases of gate outcomes, Screamer deductions, LLM proposals, and cross-domain comparisons. The facts that proved useful define the persistent schema. The ones that weren't are left behind. The serialization format is not designed upfront; it emerges from use. + +The transition from ephemeral to persistent is justified when two conditions are met: (1) the fact language has stabilized (categories are being queried, not constantly refactored), and (2) accumulated deductions across sessions provide value that justifies the serialization cost. + +*** Implementation — ~symbolic-vivacegraph.org~ → ~symbolic-vivacegraph.lisp~ (skill) + +**** Wrap VivaceGraph +VivaceGraph is available via Quicklisp. Load at runtime. Not an ASDF dependency. If not installed, the fact store continues as a hash table (Phase 1-4 behavior) with a log warning: "VivaceGraph not available — persistence disabled." + +**** Prolog-like queries +Replace ~fact-query~ with graph traversals: +#+begin_src lisp +;; Find all files classified as secrets +(vivace-query '(:and (:entity ?e) + (:member-of-class ?e :secret-file))) + +;; Find all files classified as secrets that were modified today +(vivace-query '(:and (:entity ?e) + (:member-of-class ?e :secret-file) + (:modified-since ?e ,(today-timestamp)))) + +;; Find contradictions between Wikidata and the memex +(vivace-query '(:and (:entity ?e) + (:has-value ?e ?v1 :source :wikidata) + (:has-value ?e ?v2 :source :memex) + (:not-equal ?v1 ?v2))) +#+end_src + +**** KG type hierarchy +Every entity in the graph carries ~:pm-type-level~ metadata. Queries cannot return entities whose type level equals or exceeds the querying function's type level. A fact-finding query at type-level 2 cannot return facts at type-level 3 or higher. Self-referential knowledge — "this fact defines its own type" — becomes structurally impossible because the type level is assigned at creation and cannot be modified by a fact of the same or higher level. + +This is Contribution 1 (type-level gates) applied to the knowledge layer rather than the execution layer. The dispatcher prevents self-referential /actions/; the KG prevents self-referential /facts/. + +**** Persistence format +The fact language that survived Phases 1-4 defines the format. Each entity is a node; each triple is an edge with properties (=:grounding=, =:provenance=, =:timestamp=). The format is not a new design — it is the triple schema evolved through use, serialized by VivaceGraph's native persistence. + +If the fact language later evolves to n-ary relations, VivaceGraph's graph model accommodates this natively — edges can carry arbitrary property plists. The triple form is a special case of the general graph model. + +**** Load on startup, save on interval +On daemon start, ~(vivacegraph-load)~ reads the last saved graph. On heartbeat, ~(vivacegraph-save)~ persists the graph in its native format to ~~/.cache/passepartout/facts.vg~. The interval matches the existing ~*memory-auto-save-interval*~. The save is atomic: write to a temp file, rename on success. Corruption-safe. + +**** Merkle DAG version chains +Each ~(:entity :relation)~ pair forms an independent Merkle chain. Facts hash over ~SHA-256(value || provenance || timestamp || parent-hash || grounding)~. The ~:parent-id~ pointer forms the chain. Tampering with any version breaks all downstream hashes. + +The chains form a DAG, not a single list. Facts about =.env= evolve independently from facts about Nabokov. =:dual= and =:plural= facts cross-reference via =:complement= and =:contradiction= edges but maintain independent ancestor chains. The Merkle DAG rests on the existing ~memory-object~ infrastructure from v0.2.0 — the fact store is a new occupant of existing housing. ~50 lines to bridge the fact schema into ~memory-object~ wrappers. + +**** Ontology versioning +The category hierarchy itself is a Merkle tree. Every entity class definition hashes over its superclasses, cardinality policy, relations, and description. The aggregate hash of all active class definitions is the ~:ontology-version~ — a Merkle root of the current worldview. + +Every fact stores its ~:ontology-version~ at the time of assertion (a single 64-hex-char field). When categories change, the new hash flags affected facts for re-verification (Screamer re-evaluates each against the new category definitions). Re-verification outcomes are ~:survived~ (deduction still holds), ~:incoherent~ (premises don't translate under new categories, flagged for human review), or ~:reclassified~ (valid but under different classification). + +Queries accept an optional ~:ontology-version~ parameter. The default is ~:active~ (current worldview). Specifying a version returns facts as they were under that worldview: "Under my 2024 security model, this file was a secret. Under my 2025 model, it is an auth-secret." ~40 lines on top of VivaceGraph persistence. + +*** Verification — ~8 FiveAM tests +1. ~test-vivacegraph-roundtrip~ — save and load preserves all facts with provenance metadata. +2. ~test-prolog-query-returns-results~ — a query for all secret files returns the bootstrapped gate facts. +3. ~test-prolog-query-cross-domain~ — a query for contradictions between Wikidata and memex provenance returns correct results. +4. ~test-type-level-prevents-self-reference~ — a query from a type-level-2 function cannot return type-level-3 facts. +5. ~test-fact-store-fallback-without-vivacegraph~ — when VivaceGraph is not loaded, the hash-table fallback functions identically to Phase 1-4 behavior. +6. ~test-merkle-chain-tamper-detected~ — modifying a fact's value breaks the hash chain, detectable by re-walking the ~:parent-id~ spine. +7. ~test-ontology-version-query~ — querying with an old ~:ontology-version~ returns facts as they were under that worldview, not the current one. +8. ~test-reverification-flags-on-category-change~ — changing a category definition sets ~:re-verify-status :pending~ on all affected facts. + +~400 lines. New skill: ~symbolic-vivacegraph.org~. Depends on Phase 4 (sufficiency). Not an ASDF dependency — degrades to hash-table fallback. + +** v0.27.0: Hooks on defskill — Lifecycle Interception +:PROPERTIES: +:ID: id-v082-hooks +:CREATED: [2026-05-08 Fri] +:END: + +Passepartout's skills can inject instructions and react to triggers but cannot intercept behavior. All 4 competitors have lifecycle hooks (PreToolUse, PostToolUse, session events). Hooks complete the extension model: skills define *what* the agent knows; hooks define *when* skills get to inspect and veto actions. + +- Add ~:pre-tool-hook~ and ~:post-tool-hook~ slots to the ~defskill~ struct +- ~:pre-tool-hook~ receives ~(action context)~, returns ~:allow~, ~:deny~, or ~:ask~. Called before tool execution in the Dispatcher pipeline (new vector between shell-safety and network-exfil). +- ~:post-tool-hook~ receives ~(action context result)~, returns ~(values modified-result modified-context)~ or nil to leave unchanged. Called after tool execution. Useful for logging, auto-commit, notification. +- ~:on-session-start~, ~:on-heartbeat~, ~:on-compact~ lifecycle hooks for maintenance skills +- Hooks run in skill priority order. A ~:deny~ from any hook short-circuits the chain. +~50 lines in ~defskill~ macro + ~core-perceive.lisp~ + +** v0.28.0: Phase 6 — ACL2 Structural Verification (~200 lines, new skill) +:PROPERTIES: +:ID: id-v090-phase6 +:CREATED: [2026-05-09 Sat] +:END: + +Wrap ACL2 as a skill. Prove structural properties of the KG type hierarchy and rule sets. Not for empirical claims. + +*** Rationale + +ACL2 is often positioned as verifying LLM-proposed facts, but many facts are empirical ("this command is destructive on Linux"), not logical. The right role: structural verification. ACL2 proves that the type hierarchy has no cycles, that the rule set is non-contradictory, and that the gate-to-fact bootstrap preserves the Dispatcher's intent. These are structural properties that can be formally verified, not empirical claims that depend on external reality. + +*** Implementation — ~symbolic-acl2.org~ → ~symbolic-acl2.lisp~ (skill) + +**** Type consistency proofs +~(acl2-verify-type-hierarchy facts)~ — prove that the KG type hierarchy has no cycles: no entity of type-level 3 depends on an entity of type-level 5, no parent category has a child that subsumes it, no category is its own ancestor via the child-of relation. These are structural properties of the graph, independent of what the facts /say/. + +**** Rule set consistency +~(acl2-verify-rule-consistency rules)~ — prove that the accumulated Dispatcher rules (from HITL approvals) are non-contradictory: no rule allows a command that another rule blocks, no rule permits a path access that another denies. If the rule set is contradictory, ACL2 identifies the contradictory subset with the provenance of each rule. The human resolves the contradiction. + +**** Extraction verification +~(acl2-verify-bootstrap-preservation)~ — prove that the gate-to-fact bootstrap (Phase 0-1) preserves the Dispatcher's intent: every blocked pattern in the gate stack maps to a fact in the store; every fact with ~:provenance :gate-outcome~ is grounded in a specific gate vector; no gate-bootstrapped fact contradicts another gate-bootstrapped fact. + +**** Not in scope +ACL2 does not verify that ~rm -rf / is destructive. That is an empirical claim about Linux. Screamer handles empirical consistency (does this new claim contradict existing observations?). ACL2 handles structural consistency (does this reasoning structure have formal flaws?). The boundary is: empirical claims → Screamer; structural claims → ACL2. + +*** Verification — ~4 FiveAM tests +1. ~test-acl2-type-hierarchy-no-cycles~ — a synthetic KG with a type-level cycle is detected and reported. +2. ~test-acl2-rule-set-contradiction-detected~ — two Dispatcher rules that contradict each other produce a contradiction report with provenance. +3. ~test-acl2-bootstrap-preservation~ — the bootstrap extraction from the gate stack is verified to have no missing or extra facts. +4. ~test-acl2-not-loaded-graceful-degradation~ — when ACL2 is not installed, the skill loads but returns ":ACL2 not available — structural verification disabled" without crashing. + +~200 lines. New skill: ~symbolic-acl2.org~. Depends on Phase 5 (VivaceGraph). Not an ASDF dependency — degrades gracefully. + +** v0.29.0: Prompt Templates / Output Styles +:PROPERTIES: +:ID: id-v082-prompt-styles +:CREATED: [2026-05-08 Fri] +:END: + +Claude Code has "output styles" (~default~, ~Explanatory~, ~Learning~). Hermes has agent profiles. Passepartout has a single hardcoded system prompt. Users should be able to change *how* the agent works, not just how it looks. + +- Output styles are Org files in ~~/.config/passepartout/styles/~ with a plist frontmatter: ~#+STYLE: explanatory~, ~#+DESCRIPTION: Teaches while doing~ +- Three built-in styles: + - ~default~ — current behavior, direct and efficient + - ~explanatory~ — agent explains implementation choices, provides educational insights with ~★ Insight~ blocks. Claude Code's Explanatory output style + - ~learning~ — agent pauses to ask user to write small code pieces (2-10 lines), uses ~● Learn by Doing~ blocks. Claude Code's Learning output style +- ~/style ~ TUI command to switch at runtime. Injects a STYLE section into the system prompt between IDENTITY and TOOLS. +- Style changes are immediate (next think() call). Survive restarts via config persistence. +~100 lines (~60 prompt templates + ~40 TUI integration). + +** v0.30.0: Skill Auto-Detection — File-Watch Hot-Reload +:PROPERTIES: +:ID: id-v082-auto-reload +:CREATED: [2026-05-08 Fri] +:END: + +Passepartout's image-based Lisp model enables hot-reload — redefine a function without restarting. No competitor has this. Claude Code plugins require manual ~/reload-plugins~. Passepartout can auto-detect changes. + +- Daemon watches ~org/~ and ~~/.config/passepartout/skills/~ with ~inotify~ (Linux) or ~kqueue~ (macOS). On ~.org~ file change: + 1. Wait 200ms debounce (multiple writes within 200ms coalesce) + 2. Tangle the changed org file: ~(org-tangle-file "org/skill-name.org")~ + 3. Compile the tangled lisp: ~(compile-file "lisp/skill-name.lisp")~ + 4. Reload: ~(load (compile-file-pathname "lisp/skill-name.lisp"))~ + 5. TUI shows system message: ~"Skill 'skill-name' reloaded (23 defuns, 0 errors)"~ +- Respects ~SELF_BUILD_MODE~ — core files require HITL before reload. Skills reload automatically. +- On compile error: keep the old version loaded, log the error, show TUI warning: ~"✗ Skill 'skill-name' failed to compile — old version retained."~ +~80 lines in a new ~symbolic-file-watch.org~ skill. + +** v0.31.0: Heavy Thinking Skill — Parallel Reasoning + Sequential Deliberation +:PROPERTIES: +:ID: id-v082-heavy-thinking +:CREATED: [2026-05-08 Fri] +:END: + +The HeavySkill paper (arXiv:2605.02396v1) demonstrates that a two-stage pipeline — K independent reasoning trajectories followed by a critical deliberation step — consistently outperforms majority voting and approaches Pass@K. The authors distill it into a readable skill file that works across any agent harness. Passepartout's Merkle tree makes this auditable, rewoundable, and cross-session comparable. + +- New skill: ~org/heavy-thinking.org~ — a readable skill document loaded at startup. The agent follows a defined protocol when facing complex reasoning tasks: + 1. *Activation*: triggers when the complexity classifier detects a STEM/reasoning/code-generation task. Dormant for simple factual queries or casual conversation + 2. *Parallel reasoning*: spawns K independent ~think()~ calls (default K=3, ~HEAVY_THINKING_WIDTH~ env var). Each call solves the same problem from scratch without access to other trajectories. Encourages diverse strategies + 3. *Sequential deliberation*: a second model call reads all K trajectories (pruned to essential thinking content to stay under context budget). Critically evaluates each — not voting, but re-reasoning. Produces a synthesized final answer with a deliberation trace: "Trajectories 1,3 converged on answer X. Trajectory 2 had error Y. Synthesized answer: X." + 4. *Output*: returns the synthesized answer with ~[Heavy-thinking: 3 parallel, 1 deliberate]~ annotation in the response metadata +- Merkle advantage: each trajectory is stored as a content-addressed node. The deliberation trace is permanent and auditable — users can see WHY one answer was chosen +- Iterative deliberation optional (capped at 2 — the paper shows iterations 3+ degrade HP@K) +- Cost model: 3 parallel × 1 deliberation = 4 API calls for complex tasks (vs 1 normally). ~HEAVY_THINKING_COST_MULTIPLIER~ env var for cost-aware auto-activation +~100 lines as a skill (~60 prompt template + ~40 orchestration in ~symbolic-heavy-thinking.org~). + +** v0.32.0: Adaptive Layout (3 Tiers) +:PROPERTIES: +:ID: id-v073-adaptive-layout +:CREATED: [2026-05-08 Fri] +:END: + +- ≥ 120 columns: Full layout. Sidebar visible with all 6 panels. Chat area left of sidebar. +- 80–119 columns: Compact layout. Sidebar hidden (toggle via ~/sidebar~ or Ctrl+X+B, rendered as overlay). Status bar 2 lines. Full markdown rendering. +- < 80 columns: Minimal layout. Single-column chat. Status bar reduced to 1 line (model, ctx%, duration). Markdown reduced to bold + code blocks only. Input height clamps to 1-2 lines. + +Re-renders on terminal resize (already handled via ~KEY_RESIZE~). Content re-flows — not truncated. The layout remembers per-terminal-size preference. ~80 lines. + +** v0.33.0: Spinner Personality +:PROPERTIES: +:ID: id-v073-spinner +:CREATED: [2026-05-08 Fri] +:END: + +Configurable spinner style per skin: + +- ~:braille~ — ⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ cycling at 80ms (default) +- ~:dots~ — ·✢✳✶✻✽ cycling (macOS style, Claude Code default) +- ~:kawaii~ — (。◕‿◕。) (◕‿◕✿) ٩(◕‿◕。)۶ cycling with wing decorations ~⟪⚔ ... ⚔⟫~ +- ~:minimal~ — single ● dot blinking at 2000ms +- ~:none~ — static prompt symbol + +Stall indication: when no response for 10s, spinner color interpolates from theme color → error red (Claude Code pattern). Reduced motion preference: spinner replaced with slow-pulse ●. ~50 lines. + +** v0.34.0: Progress Bar +:PROPERTIES: +:ID: id-v073-progress-bar +:CREATED: [2026-05-08 Fri] +:END: + +For measurable operations (file processing, test runs with known count, batch operations), render a progress bar using Unicode block characters: + +~[████████░░░░░░░░░░░░] 42% (5/12 tests passed)~ + +Uses 9 block characters for sub-character precision: ~[' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉', '█']~ (Claude Code pattern). Color-coded by progress: red <25%, yellow 25-75%, green 75%+. ~25 lines. + +** v0.35.0: Live Timestamps +:PROPERTIES: +:ID: id-v073-timestamps +:CREATED: [2026-05-08 Fri] +:END: + +- Relative timestamps on messages: "just now" (< 30s), "2m ago", "1h ago", "yesterday" +- Absolute timestamp on hover/focus (via Tab navigation to message) +- Status bar shows session duration: ~Session: 3h 12m~ +- Timestamps update live (per-minute recalculation, not per-frame) +~40 lines. + +** v0.36.0: Context-Sensitive Help +:PROPERTIES: +:ID: id-v073-help +:CREATED: [2026-05-08 Fri] +:END: + +Press ~?~ to show available actions in current context: +- In chat: list of navigation keys, command shortcuts +- In sidebar: sidebar-specific bindings +- In HITL prompt: approval/denial bindings +- In command palette: palette navigation bindings + +Rendered as a dim help bar at the bottom of the screen (above input). Dismisses on any key or after 5 seconds. ~40 lines. + +** v0.37.0: Phase 7 — 10-80-10 Planner (~500 lines, new skill, last phase) +:PROPERTIES: +:ID: id-v090-phase7 +:CREATED: [2026-05-09 Sat] +:END: + +The final neurosymbolic phase: a planning engine built on the mature symbolic index. Screamer expresses task planning as a constraint satisfaction problem. ACL2 verifies plans for structural soundness. The LLM handles the I/O boundaries (natural language → structured goal ← natural language response). The symbolic engine handles the reasoning. + +*** Rationale + +This is the culmination — it requires a populated, queried, and trusted symbolic index. The full planner is useless without a mature ontology and a proven deducer. By the time Phase 7 begins, Phases 0-6 have accumulated months of gate outcomes, Screamer deductions, verified LLM proposals, and human-authored facts. The symbolic index has achieved sufficiency. The ontology has stabilized through use. The planner is built on a foundation, not a speculation. + +*** Implementation — ~symbolic-planner.org~ → ~symbolic-planner.lisp~ (skill) + +**** Task decomposition as constraint satisfaction +The user specifies a goal: "refactor the authentication module to support OAuth2." The LLM translates this to a structured goal plist. Screamer expresses the planning problem: + +- /Variables/: subtasks (write OAuth2 client, add token store, update auth middleware, write tests, update documentation) +- /Constraints/: dependency ordering (tests depend on implementation), resource limits (one file write at a time), safety invariants (no modification of ~core-*~ files) +- /Objective/: find an ordering that satisfies all constraints + +Screamer returns a viable plan or reports unsolvability with the conflicting constraints. + +**** Plan verification +ACL2 proves that the plan contains no deadlocks (two subtasks waiting on each other), no dependency cycles (A depends on B depends on C depends on A), and no safety violations (no plan step requires a gate-blocked operation). + +If verification fails, ACL2 identifies the failing subtask and the violated constraint. The planner re-decomposes the problematic branch (the existing ROADMAP's branch pruning, v0.62.0, but symbolically rather than neurally). + +**** Neuro-symbolic boundary +The LLM handles the I/O boundaries: +- *Input* (10%): natural language → structured goal plist. "Refactor auth for OAuth2" → ~(:goal :refactor-component :target :auth-module :add-feature :oauth2)~. Small prompt, formulaic translation, ~100 tokens. +- *Reasoning* (80%): Screamer plans. ACL2 verifies. VivaceGraph provides the facts about file structure, dependencies, and gate constraints. Zero LLM tokens. +- *Output* (10%): structured plan → natural language response. The verified plan plist is formatted as "I'll refactor the authentication module in 5 steps: 1) Create the OAuth2 client (depends on: nothing, modifies: auth/client.lisp) 2) Add the token store..." Small prompt, formulaic translation, ~150 tokens. + +**** TUI visualization +The plan is rendered as an Org headline tree in the TUI, with each subtask as a node showing its terminal state (=todo=, =next-action=, =in-progress=, =done=, =blocked=, =stuck=), its constraints, and its verified properties. This is the same task tree visualization planned for v0.62.0, but with the addition of Screamer constraint annotations and ACL2 verification badges. + +*** Verification — ~6 FiveAM tests +1. ~test-goal-plist-from-natural-language~ — natural language input produces correct structured goal plist (LLM-dependent but formulaic; tested with deterministic mock). +2. ~test-screamer-plan-satisfies-constraints~ — Screamer produces a plan that satisfies all specified dependencies and safety constraints. +3. ~test-screamer-report-unsolvable~ — Screamer reports unsolvability when constraints are contradictory. +4. ~test-acl2-verifies-plan-no-cycles~ — ACL2 verifies a valid plan has no dependency cycles. +5. ~test-acl2-rejects-cyclic-plan~ — ACL2 detects a dependency cycle in an invalid plan. +6. ~test-plan-to-natural-language~ — structured plan plist produces readable natural language output. + +~500 lines. New skill: ~symbolic-planner.org~. Depends on Phase 6 (ACL2) + all prior phases. + +** v0.37.1: Phase 8+ — Semantic Wikipedia Integration (TBD lines, optional acceleration) +:PROPERTIES: +:ID: id-v090-phase8 +:CREATED: [2026-05-10 Sun] +:END: + +Load Wikidata entities referenced in the memex into the symbolic index. Every entity the user's prose mentions gets its Wikidata property graph — type hierarchy, relations, dates, citations — as triples with ~:provenance :wikidata~. + +*** Rationale +The gate stack provides 50-70 entity classes — adequate for a coding agent. For a general-knowledge memex containing literature, philosophy, history, science, and daily life, 50-70 is starvation. Organic growth through prose extraction (Phase 3) would take years to cover the entities mentioned in a single reading of /Pale Fire/. Wikidata has already done this work at scale. + +The LLM's role in extraction shrinks dramatically. Without Wikidata, the archivist must /discover/ that Nabokov wrote /Pale Fire/, lectured on Kafka, and emigrated from Russia — extracting each triple from prose. With Wikidata, the Nabokov entity is pre-structured. The archivist's job changes from "discover entities" to "connect your heading to the existing entity." + +*** Implementation sketch +1. *Index referenced entities.* Scan memex prose for entity names (capitalized noun phrases, names in Org links, headings in =literature/= directories). For each, attempt Wikidata entity resolution (string match, disambiguation via context). +2. *Load N-hop property net.* For each resolved entity, load its Wikidata properties: instance-of, subclass-of, authored, published-in, influenced-by, birth-date, death-date, etc. Load the same for entities directly connected to it (1-hop neighbors). Optionally expand to 2-hop for deeply connected domains. +3. *Admit with plural policy.* Wikidata facts are admitted with ~:provenance :wikidata~ and cardinality policy ~:plural~. They do not override your memex's facts. Disagreements are surfaced, not resolved. +4. *Cross-domain query.* "What does my memex say about Nabokov that Wikidata doesn't?" "Where does my memex disagree with Wikidata?" "What entities in my memex have no Wikidata counterpart?" These queries are pure VivaceGraph traversals — zero LLM tokens. + +*** Not a Phase 0 prerequisite +Semantic Wikipedia integration is an accelerator, not a prerequisite. Phases 0-7 work without it. Wikidata compresses the timeline for the broad domain but does not change the architecture. The admission gate (Screamer), contradiction policies, provenance tracking, and neuro-symbolic boundary are identical with or without it. + +*** Open question +How much Wikidata is the right amount? Loading entities referenced in the memex is the minimum. Loading all entities within N hops of those references expands the graph exponentially. The right N depends on the memex's breadth and the user's query patterns. A memex focused entirely on software engineering may need only 1 hop. A memex spanning literature, history, philosophy, and science may need 3-4 hops. + +TBD lines. New skill. Depends on Phase 5 (VivaceGraph). + +** v0.38.0: Priority-Queue Signal Processing + +:PROPERTIES: +:ID: id-v090-priority-queue +:CREATED: [2026-05-08 Fri] +:END: + +Replace the linear ~process-signal~ call chain with a priority-ordered signal queue. The queue is a sorted plist-list consumed by the main loop. Priority tiers: +- ~:user-input~ / ~:chat-message~ — highest priority (the user is waiting) +- ~:approval-required~ — high (HITL re-injections need quick resolution) +- ~:tool-output~ — medium (feedback from tool execution, needs LLM assessment) +- ~:interrupt~ — medium-high (shutdown signal) +- ~:heartbeat~ / ~:cron~ / ~:delegation~ — low (background maintenance) +- Coalesce duplicate heartbeats: if the queue already contains a ~:heartbeat~ signal when a new one arrives, discard the older one (no value in processing stale ticks). Keep at most one pending heartbeat at any time. +- The main loop drains the highest-priority signal from the queue, processes it through the pipeline, and repeats. If the pipeline produces feedback (tool-output → think), the feedback is enqueued at its appropriate priority — it may preempt background signals but won't interrupt the current signal mid-processing. +- Add telemetry: average queue depth by priority tier, max wait time per tier. +- TUI ~/reconnect~ command: when the connection-loss detection from v0.3.3 fires, the user can reconnect without restarting the TUI. The command closes the stale socket, re-runs ~connect-daemon~ with its retry backoff, and restores the ~:connected~ state on success. + +~80 lines in ~core-pipeline.lisp~ + ~30 lines TUI. + +** v0.39.0: MVCC Memory Concurrency +:PROPERTIES: +:ID: id-v090-mvcc +:CREATED: [2026-05-08 Fri] +:END: + +- Replace ~*memory-store*~ (mutable global hash table) with a versioned Merkle-root pointer. The root is an ~(or null merkle-node)~ struct containing the tree and a monotonic version counter. +- Read threads snapshot the root before beginning their pipeline cycle. All object lookups dereference through the snapshot — they see a consistent view of memory regardless of concurrent writes. Reads never block. +- Write threads (ingest-ast, org-modify, snapshot-memory) build new object hashes, construct a new Merkle root, and CAS-replace the global root pointer. If another thread won the CAS race (root version changed), the loser re-reads the new root, replays its changes on the updated tree, and retries the CAS. +- Conflict probability is near-zero because concurrent signals almost never touch the same Org headline. The replay-on-conflict path exists for correctness but is rarely exercised. Lock contention is eliminated — the only atomic operation is the CAS on the root pointer. +- Remove the single-threaded pipeline assumption: previously, ~process-signal~ was safe because nothing else wrote to ~*memory-store*~ during its execution. With MVCC, multiple signals can process concurrently because each has its own snapshot. The ~*loop-interrupt-lock*~ becomes ~*signal-queue-lock*~ (protecting only the queue, not the memory). +- Test: concurrent ingest-ast from two threads writing to different memory objects, verify both commits succeed without corruption. + +~60 lines in ~core-memory.lisp~. + +** v0.40.0: Structured Output Enforcement +:PROPERTIES: +:ID: id-v090-structured-output +:CREATED: [2026-05-08 Fri] +:END: + +- Add a plist validation step between ~markdown-strip~ and ~read-from-string~ in ~think()~. Before attempting to parse, validate: (a) the output starts with ~(~ or ~[~, (b) it contains balanced delimiters (count opens vs closes), (c) it doesn't contain ~#.~ (redundant after v0.3.1 ~*read-eval* nil~ but defense-in-depth). +- On validation failure: construct a rejection trace (similar to the existing deterministic gate rejection feedback) and re-inject into the LLM prompt. The trace includes the raw output and a diagnostic ("Your response did not produce a valid plist. Ensure it starts with ( and has balanced parentheses."). +- Configurable ~LLM_OUTPUT_RETRIES~ (default 2). After exhausting retries, fall through with the raw text as a ~:MESSAGE~ action (current behavior). +- Track parse-failure rate per provider in telemetry. Use to guide provider cascade ordering: a provider with 20% parse-failure rate falls behind one with 2%. +- If retries are exhausted without a parseable plist, the TUI renders the raw LLM output in a dimmed, collapsible region labeled "Parse failure — could not interpret this response." The user can inspect what the model produced. + +~40 lines in ~core-reason.lisp~. + +** v0.41.0: Doom-Loop Detection + +:PROPERTIES: +:ID: id-v090-doom-loop +:CREATED: [2026-05-08 Fri] +:END: + +OpenCode detects 3 consecutive identical tool calls and prompts the user. Without this, Passepartout could loop forever on a stuck tool — burning tokens and producing no progress. + +- Track last 3 tool calls (name + args plist) in a ring buffer +- Before executing a tool, compare against the 3 previous calls +- If all 3 have the same name and equal args (using ~equalp~), inject a HITL prompt: "The agent has attempted 'grep defun' 3 times without progress. Continue or abort?" +- Resets on any different tool call or successful output +~15 lines in ~core-loop-act.lisp~ + +** v0.42.0: Busy-Mode — Queue on Interrupt + +:PROPERTIES: +:ID: id-v090-busy-mode +:CREATED: [2026-05-08 Fri] +:END: + +When the agent is processing a turn and the user types a message, the current behavior is undefined. Hermes has interrupt/queue/steer. Passepartout should at minimum support queue mode. + +- ~BUSY_INPUT_MODE~ env var: ~interrupt~ (default, stop current turn), ~queue~ (process after current turn) +- In ~queue~ mode: user messages arriving during an active turn are enqueued. When the current turn's tool chain completes, the queued message is injected as the next turn's user input — no HITL approval needed (it's user input). +- ~/busy interrupt~ / ~/busy queue~ TUI commands to toggle at runtime +- The priority queue (above) naturally supports this — user input queued during a turn has higher priority than heartbeats, lower than the active turn +~20 lines in ~core-pipeline.lisp~ + +** v0.43.0: CLI / Non-Interactive Mode + +:PROPERTIES: +:ID: id-v090-cli +:CREATED: [2026-05-08 Fri] +:END: + +Claude Code supports ~claude -p "fix the failing test" --print~. Hermes has ~hermes -c "command"~. Passepartout can only be used interactively via the TUI. A non-interactive single-shot mode enables CI/CD integration, cron jobs, and scripting. + +- ~passepartout ask "what's the status of project X?"~ — sends a framed message to the daemon, waits for response, prints to stdout +- Daemon-side: ~process-one-shot~ handler — inject ~:user-input~ signal, run through full pipeline (perceive → reason → act → loop until stop), return final agent message +- ~--json~ flag outputs the full response plist for programmatic consumption +- ~--timeout N~ flag (default 120s) limits execution time +- Uses the existing wire protocol — no new protocol, just a CLI wrapper around the framed TCP message format +~80 lines in ~passepartout~ bash script + ~50 lines daemon handler. + +** v0.44.0: Provider Health Tracking + +:PROPERTIES: +:ID: id-v090-provider-health +:CREATED: [2026-05-08 Fri] +:END: + +~backend-cascade-call~ tries providers in order until one succeeds. On failure it moves to the next. But it has no memory of which providers failed or succeeded in the past. A degraded provider gets retried first on every call. + +- ~*provider-health*~ hash table: maps provider keyword to ~(:success-count :fail-count :total-latency :last-status <:ok|:degraded|:down>)~ +- Updated after each ~backend-cascade-call~: increment success/fail, rolling average latency (last 10 calls) +- ~provider-health-score~ function: returns a score 0-100 based on success rate (weight 0.6) and latency vs baseline (weight 0.4) +- ~/provider-status~ TUI command: displays a table of all providers with status indicators (~● Up, ◐ Degraded, ○ Down~) and recent history +- Telemetry: provider health data feeds the session telemetry system +~60 lines in ~neuro-provider.lisp~ + ~30 lines TUI. + +** v0.45.0: Cost-Based Provider Routing + +:PROPERTIES: +:ID: id-v090-cost-routing +:CREATED: [2026-05-08 Fri] +:END: + +~backend-cascade-call~ currently tries providers in registration order. With cost tracking (v0.5.0) and provider health (above), the cascade can be sorted by cost-effectiveness. + +- ~COST_ROUTING~ env var (default ~true~): when enabled, sort the cascade by ~(provider-health-score * 0.3 + cost-savings-score * 0.7)~ +- ~cost-savings-score~: cheap providers score high. Free providers (Ollama local) score 100. Expensive providers (GPT-4) score 10. +- Health override: a provider with score < 20 (degraded) is demoted below healthy providers regardless of cost +- ~/routing~ TUI command: displays current cascade order with scores and reasons +~40 lines in ~core-reason.lisp~ + +** v0.46.0: Intelligent Provider Fallback — Per-Task-Type Routing + +:PROPERTIES: +:ID: id-v090-intelligent-fallback +:CREATED: [2026-05-08 Fri] +:END: + +Current fallback is "try the next provider." But different providers excel at different tasks. DeepSeek is strong at code generation. Groq is fast for simple queries. Claude is better at reasoning. The cascade should adapt to the task. + +- ~*task-provider-scores*~ hash table: maps ~(task-type keyword) → (provider keyword → score)~ +- Task types: ~:chat~ (conversation), ~:code~ (code generation/editing), ~:plan~ (multi-step planning), ~:search~ (information retrieval), ~:summary~ (compaction), ~:reflex~ (deterministic lookup) +- Scores updated after each call: if the response was accepted (no rejection retry), increment that provider's score for that task type +- When the primary provider fails, the fallback picks the highest-scored provider for the current task type (not just the next in line) +- Bootstrap from defaults: GPT-4/Claude for reasoning, DeepSeek for code, Groq for chat, local Ollama for reflex +~60 lines in ~neuro-router.lisp~ + +** v0.47.0: Autonomous Certification Badge + +:PROPERTIES: +:ID: id-v090-certification +:CREATED: [2026-05-08 Fri] +:END: + +After N HITL approvals of the same pattern, the dispatcher auto-approves it. But unlike Claude Code's "auto mode," this is deterministic — no probability, no model hallucination granting permission. The certification is a logical certainty. + +- When a pattern crosses ~DISPATCHER_RULE_THRESHOLD~, the dispatcher writes the rule to ~rules.org~ AND grants a certification entry: "Certified: shell commands targeting ~/memex/projects/* with git status are deterministically safe. 47 approvals, 0 denials." +- The sidebar Rules panel shows: ~[Rules: 47 | Certified: 12]~ — learned rules vs certified patterns +- ~/certifications~ TUI command: lists all certified patterns with approval counts, last-used timestamps, and the gate vector that checks them +- Certification downgrade: if a certified pattern is later denied by the user, the certification is revoked and the pattern returns to HITL +- This is the operational realization of "the more you use it, the cheaper it gets" — each certification represents a category of actions that will never cost another HITL prompt +~60 lines in ~security-dispatcher.lisp~ + sidebar rendering reuse. + +** v0.48.0: Certification Progress Bar + +:PROPERTIES: +:ID: id-v090-cert-progress +:CREATED: [2026-05-08 Fri] +:END: + +The certification badge grants permanent auto-approval. Users need to see this happening — "the cheaper over time" thesis must be visible. + +- Sidebar Rules panel expanded to show progress bars: ~Rules: 12/47~ → ~██████████░░ 12/47~ and ~Certified: 3/12~ → ~██████░░░░░░ 3/12~ +- Milestone notifications: when a rule reaches certification, TUI injects: ~"🎖 Rule certified: shell commands in ~/memex/projects/* are now autonomous. 47 approvals, 0 denials. /certifications to review."~ +- Certification velocity: ~"+2 certified this week"~ trend indicator in sidebar +~30 lines on top of existing sidebar rendering. + +** v0.49.0: Update Mechanism + Migrations + +:PROPERTIES: +:ID: id-v090-update +:CREATED: [2026-05-08 Fri] +:END: + +No update mechanism exists. Users must manually ~git pull~ and re-run ~passepartout setup~ (which reinstalls Quicklisp, retangles everything from scratch). Claude Code has ~claude update~, Hermes has ~hermes update~. Passepartout needs an incremental update path. + +- ~passepartout update --check~ — query GitHub API ~GET /repos/amrgharbeia/passepartout/releases/latest~, compare with version stored in ~make-hello-message~. Report: "v0.5.1 available. 47 changes." +- ~passepartout update~ (git-based) — ~git fetch --tags && git checkout v0.5.1~, incremental tangle (only org files changed since previous tag, via ~git diff --name-only v0.5.0..v0.5.1 -- org/*.org~), recompile changed lisp files, restart daemon +- Migration hooks: ~~/memex/system/migrations/~ — ordered Lisp scripts run after tangle, before daemon restart. ~migrate-v051.lisp~ upgrades memory format, config schema, package names. Tracked by ~*migration-version*~ in ~~/.config/passepartout/version.lisp~ +- Post-update verification: run internal eval suite, verify skill count ≥ 10, smoke test daemon port 9105. On failure: ~passepartout update --rollback~ → ~git checkout v0.5.0~ → re-tangle → restart +- Binary update path (when v0.64.0 ships): download binary from GitHub Releases, verify SHA-256, replace, restart +~80 lines bash + ~50 lines Lisp. + +** v0.50.0: Self-Configuration — Agent Proposes and Applies Config Changes + +:PROPERTIES: +:ID: id-v090-self-config +:CREATED: [2026-05-08 Fri] +:END: + +Passepartout's config is text files (`.env`, `.lisp`) — the same format the agent already edits. No competitor can self-configure because their config requires runtime restart or schema validation after file write. Passepartout can edit `.env` → daemon detects change → reloads → takes effect without restart. + +- ~passepartout config set ~ CLI command: writes to `.env`, triggers daemon reload. ~20 lines bash. +- Runtime config reload: daemon watches `.env` with ~inotify~ (reuses file-watch from v0.8.2). On change: re-reads env vars, reloads provider cascade, updates gate thresholds. No restart needed. +- Config validation before write: agent verifies provider names exist (against ~neuro-explorer~ registry), ports are valid numbers, thresholds are integers, file paths are within memex. On invalid value, proposes correction. +- Config change audit: every change writes to Merkle tree: "Agent changed DISPATCHER_RULE_THRESHOLD from 3 to 5. HITL approved." Gate trace records the decision. +~40 lines daemon + ~30 lines config validation. + +Three tiers of self-configuration: +1. **Config Query** (v0.7.2) — "What providers do I have?" → answered from system prompt CONFIG section. Already implemented. +2. **Config Suggest** (v0.50.0) — "Should I use a cheaper model?" → agent analyzes telemetry, proposes specific config change with estimated savings. User decides. +3. **Config Apply** (v0.50.0) — "Add @credentials to privacy tags" → agent proposes change → HITL review → writes `.env` → daemon reloads → change takes effect within one think() cycle. +4. **Config Optimize** (v0.50.0) — "Make yourself cheaper" → agent analyzes cost patterns across all sessions, proposes multi-key optimization. User approves full batch. + +** v0.51.0: Self-Diagnosis Coach — ~/coach~ Command + +:PROPERTIES: +:ID: id-v090-coach +:CREATED: [2026-05-08 Fri] +:END: + +Telemetry data plus the agent's self-knowledge enables coaching: the agent detects workflow anti-patterns and suggests improvements. + +- ~/coach~ — analyzes telemetry from the last N sessions, produces a coaching report with 3-5 actionable tips. Coaching is opt-in (privacy-respecting — no data leaves the machine). +~50 lines in telemetry skill + ~30 lines TUI rendering. + +** v0.52.0: Failure Attribution — Tag Task Failures with Probable Component + +:PROPERTIES: +:ID: id-v090-failure-attribution +:CREATED: [2026-05-08 Fri] +:END: + +AHE (arXiv:2604.25850v2) shows that evolution loops work when failures are attributed to specific harness components, not just "the task failed." Passepartout's telemetry records task outcomes but doesn't classify failures by root cause. + +- In telemetry skill: when a session ends with a task failure, classify as: ~:tool-failure~, ~:gate-overblock~, ~:gate-underblock~, ~:reasoning-error~, ~:context-overflow~, ~:timeout~ +- Classification is deterministic: if last action was blocked by dispatcher → gate-overblock. If last action was a tool error → tool-failure. If last action was a successful tool call but wrong output → reasoning-error. +- Feeds the Skill Creator (v0.58.0) — the agent knows *which* component to fix, not just *that* something went wrong +~20 lines in telemetry skill. + +** v0.53.0: MCP Native Client + +:PROPERTIES: +:ID: id-v100-mcp +:CREATED: [2026-05-08 Fri] +:END: + +- Pure Common Lisp MCP client: parse JSON-RPC messages from MCP servers over stdio or SSE. No Python bridge, no Node.js subprocess. The client runs in the same Lisp image as the agent — zero serialization overhead between the agent and the MCP layer. +- Implement the MCP protocol lifecycle: initialize handshake, list tools, call tool, handle notifications. Each MCP server registers its tools as entries in Passepartout's ~*cognitive-tool-registry*~ at connection time — the LLM's tool belt prompt automatically expands to include them. +- ~MCP_SERVERS~ env var: comma-separated paths to MCP server config files (JSON). Each config specifies the server command, args, and env vars. Example: =MCP_SERVERS=~/.config/passepartout/mcp/filesystem.json,~/.config/passepartout/mcp/git.json=. +- Tool invocation route: LLM proposes a tool call → Dispatcher verifies against permission table → MCP client serializes call as JSON-RPC → server executes → result deserialized back to plist → returned to LLM as tool output. The Dispatcher does not distinguish between native tools and MCP tools — the gate stack is uniform. +- Register the MCP client as a skill (~defskill~~:passepartout-mcp-client~) so it can be hot-reloaded. The MCP client is not core infrastructure — it is a skill that extends the tool ecosystem. + +~200 lines as a new skill ~mcp-client.org~. + +** v0.54.0: Web Search + Web Fetch Tools +:PROPERTIES: +:ID: id-v100-web +:CREATED: [2026-05-08 Fri] +:END: + +Claude Code has ~WebSearchTool~ + ~WebFetchTool~. Hermes has ~firecrawl-py~ + ~exa-py~. Passepartout's agent cannot answer questions about the world, look up documentation, or research current events. Two new cognitive tools, no external dependencies: + +- ~search-web~ — POST query to a search API (SearXNG public instance as default, configurable via ~WEB_SEARCH_URL~ env var). Returns title + URL + snippet for top 10 results. Dispatcher's network-exfiltration gate (vector 8) provides free safety — search queries are already vetted. +- ~fetch-web~ — GET a URL, extract text content via regex-based HTML stripping (no parser dependency — strip tags, keep whitespace). Returns plain text, truncated to 10,000 chars. Dispatcher's network-exfiltration gate checks the URL domain against the allowlist. +- Both register via ~def-cognitive-tool~ as read-only tools (auto-approve via v0.7.2 safe-tool allowlist) +~150 lines as a new skill ~programming-web.org~. No external Python/Node.js process. + +** v0.55.0: LSP Integration + +:PROPERTIES: +:ID: id-v100-lsp +:CREATED: [2026-05-08 Fri] +:END: + +Claude Code uses LSP for code intelligence — find definitions, find references, diagnostics, hover types. Without LSP, Passepartout can grep patterns but cannot answer "where is this function defined?" or "what calls this?" — questions Claude Code answers instantly with zero LLM tokens. + +- LSP client as a skill (~lsp-client.org~). Communicates with language servers via stdio JSON-RPC (same pattern as MCP client, different protocol). +- Three cognitive tools: ~lsp-definition~ (go to definition), ~lsp-references~ (find references), ~lsp-diagnostics~ (get errors/warnings for file) +- Read-only tools — auto-approve via v0.7.2 safe-tool allowlist +- Supported languages: any language with an LSP server (TypeScript, Python, Rust, Go, C/C++, Java, etc.) — not Lisp-specific +- LSP servers installed by the user (e.g., ~npm install -g typescript-language-server~). Passepartout auto-discovers installed servers via PATH. +~200 lines. Register as read-only cognitive tools. No daemon protocol changes — LSP is a background process, not a rendering concern. + +** v0.56.0: ~debug-inspect~ Cognitive Tool + +:PROPERTIES: +:ID: id-v100-debug-inspect +:CREATED: [2026-05-08 Fri] +:END: + +Lisp enables live state inspection that no TypeScript/Python agent can match. Claude Code has no REPL. Passepartout can inspect and modify its own running state. + +- ~debug-inspect~ cognitive tool: evaluates a Lisp form in the running image and returns the result as a structured plist. Parameters: ~code~ (Lisp form string), ~package~ (optional). +- Read-only tool: auto-approve via v0.7.2 safe-tool allowlist. No side effects — inspection only. +- Use cases: ~(hash-table-count *memory-store*)~, ~(inspect memory-object-by-id "node-42")~, ~(map 'list #'car *skill-registry*)~ +- The agent can introspect its own state to answer meta-questions: "How many objects are in memory?" "What skills are loaded?" "What was the last HITL decision?" +~30 lines in ~programming-repl.lisp~ (extends existing repl-eval with safety guard). + +** v0.57.0: Session Transcripts — ~/memex/system/sessions/~ + +:PROPERTIES: +:ID: id-v100-transcripts +:CREATED: [2026-05-08 Fri] +:END: + +Passepartout has no session persistence beyond Merkle tree snapshots. Chat history lives in the TUI's in-memory vector and is lost on restart. Every competitor persists sessions: Claude Code uses JSONL, OpenCode uses SQLite, OpenClaw uses JSONL, Hermes uses SQLite+FTS5. + +- Auto-save on every message (user and agent): append to ~~/memex/system/sessions/-.org~ as an Org file +- Format: each message as an Org headline with role tag (~:user:~, ~:agent:~, ~:system:~), universal timestamp, content in body. Gate trace as a property drawer under the agent message headline. +- Session title derived from the first user message (first 60 chars, sanitized for filename). Override with ~/rename <title>~ +- Auto-save is automatic — no ~/export~ needed. The ~/export~ command delegates to the same function with format options (Org/Markdown/JSON) +- Location: ~/memex/system/sessions/~ — under ~system/~, not ~daily/~, no clutter +- Survives daemon restarts. Resume via ~/resume <date-title>~ (existing session resume from v0.7.2) +~80 lines in ~core-transport.lisp~ (append on message send) + reuse existing Org rendering. + +** v0.58.0: Auto-Memory Extraction — Learnings from Sessions + +:PROPERTIES: +:ID: id-v100-auto-memory +:CREATED: [2026-05-08 Fri] +:END: + +Claude Code's ~extractMemories~ runs at the end of each query loop, scanning the conversation for durable learnings and writing them to memory files. Hermes's MemoryProvider.sync_turn does the same. Passepartout records everything in the Merkle tree but never extracts cross-session learnings. + +- After each ~think()~ cycle that produces a final response (no tool calls pending), run ~extract-session-memory~: a lightweight LLM call (~50 tokens of prompt) that asks "What should I remember from this session?" and writes the result to ~~/memex/system/memory/<project>/<date>.org~ +- The extraction uses a forked LLM call (separate from the main response) with the session transcript as context +- Auto-memory files are injected into the CONTEXT section of future ~think()~ calls as "Session memory: [learnings from prior sessions about this project]" +- Extracted memories include: decisions made, patterns observed, preferences expressed, errors encountered and fixed, codebase facts learned +- Opt-out via ~AUTO_MEMORY=false~ env var. Extraction frequency capped at one per minute to prevent runaway API costs. +~80 lines in ~core-reason.lisp~ + reuse session transcript for context. + +** v0.59.0: Universal Cross-Project Org Query + +:PROPERTIES: +:ID: id-v100-org-query +:CREATED: [2026-05-08 Fri] +:END: + +Passepartout's entire memex is Org — one format for memory, tasks, documents, transcripts. No competitor has this. Claude Code queries CLaude.md (one file), SQLite (separate DB), and file tools (grep). Passepartout can query everything with one function. + +- ~(org-query :tag "@urgent" :state "TODO" :since "-7d" :path "~/memex/projects/")~ — scans all projects in memex, returns matching Org headlines as memory objects. Zero LLM tokens, ~2ms execution. +- ~(org-query :property "DEADLINE" :before "-1d")~ — overdue items. Feeds ~/agenda~ command. +- ~(org-query :where "dispatch" :in-title-p t)~ — search headlines containing a term across all projects. +- ~(org-query :limit 20 :sort :priority)~ — sorted, capped results. +~150 lines in ~programming-org.lisp~ (extends existing Org manipulation primitives). + +** v0.60.0: Skill Creator — LLM-Drafted, Verified Skills + +:PROPERTIES: +:ID: id-v110-skill-creator +:CREATED: [2026-05-08 Fri] +:END: + +- LLM drafts complete skill org-file from natural language description. +- Mandatory pipeline: (a) syntax validation via ~lisp-syntax-validate~, (b) sandbox-load in temporary jailed package (v0.3.2), (c) run registered trigger function against mock contexts, (d) run registered deterministic gate against mock proposals, (e) on pass, promote to live registry under ~passepartout.skills.<name>~. +- Required ~:repl-verified~ flag on all ~defun~ forms — the existing Dispatcher lint check warns on writes without verification. The Skill Creator enforces this at creation time. +- Skills are the primary extension mechanism for users. The Skill Creator makes skill authoring accessible to non-Lisp-programmers: describe what you want in English, the LLM drafts the Org file, the system verifies it, and the skill is live. +~150 lines as a new skill ~symbolic-skill-creator.org~. + +** v0.61.0: Change Manifest — Skills Ship with Falsifiable Predictions + +:PROPERTIES: +:ID: id-v110-change-manifest +:CREATED: [2026-05-08 Fri] +:END: + +AHE (arXiv:2604.25850v2) shows that harness edits work better when each edit ships with a self-declared prediction, verified by next-round outcomes. Passepartout's Skill Creator should do the same — every new or modified skill carries predictions that telemetry verifies. + +- When the Skill Creator generates a skill, it also generates a ~#+PREDICTION:~ block in the Org frontmatter. +- Over the next 10 sessions, telemetry compares actual outcomes against predictions. The verification result is appended to the skill file. +- Disproven predictions flag the skill for review. +- The change manifest persists in the skill's Org file — every skill carries its own evidence ledger. +~40 lines in Skill Creator + telemetry integration. + +** v0.62.0: Long-Horizon Planning (Task Tree DAG) + +:PROPERTIES: +:ID: id-v110-planning +:CREATED: [2026-05-08 Fri] +:END: + +- Decompose complex tasks into Org-mode headline trees. Each task node is a memory-object with terminal states: ~:todo~ → ~:next-action~ → ~:in-progress~ → ~:done~ / ~:blocked~ / ~:stuck~. +- The LLM generates the initial task tree from the user's request. The REASONING tier processes each leaf task sequentially, updating node states as it progresses. +- Parent nodes summarise child results: when all children of a node reach ~:done~, the parent is promoted to ~:done~ with a synthesised summary. When any child reaches ~:stuck~, the parent is promoted to ~:blocked~ with the blocking child's diagnostic. +- Branch pruning: if a child is ~:stuck~ after three retries with different LLM providers, the parent re-plans the branch — the LLM generates alternative decomposition paths for the blocked sub-task. +- Task trees persist as Org headlines in ~/memex/system/tasks/~. Survive restarts. Visible to the user as editable Org files. +- TUI task tree visualization: a collapsible Org headline tree rendered in the chat area. Each node shows its terminal state with a colored indicator (~○~ todo, ~▶~ next-action, ~◉~ in-progress, ~✓~ done, ~✗~ blocked, ~⏸~ stuck). Nodes expand/collapse on Enter. The tree updates in real time as the agent progresses through subtasks. +~200 lines. + +** v0.63.0: Tier Classifier Fix + +:PROPERTIES: +:ID: id-v110-tier-fix +:CREATED: [2026-05-08 Fri] +:END: + +- Invert the current classifier: ~:REFLEX~ = deterministic lookups only (memory query, file-exists-p, check time, list TODOs by tag). ~:COGNITION~ = text processing, summarization, simple Q&A, note formatting. ~:REASONING~ = planning, code generation, multi-step task execution, dangerous operations. +- Track classifier accuracy via telemetry: for each classified action, record whether the classification was appropriate. +- The classifier function is overrideable via ~*tier-classifier*~, allowing users or skills to customize routing. +- The classifier should be a skill, not core infrastructure — reloadable and replaceable without restart. +~40 lines. + +** v0.64.0: SWE-Bench Harness + +:PROPERTIES: +:ID: id-v120-swebench +:CREATED: [2026-05-08 Fri] +:END: + +- Automated pipeline: clone a repository from SWE-bench dataset, parse the GitHub issue, feed the issue description into Passepartout's cognitive loop, track the resolution trajectory as an Org headline tree, apply the generated patch, run the repository's test suite, score success (tests pass yes/no). +- Trajectory persistence: each benchmark run produces an Org file under ~/memex/system/benchmarks/~ recording every ~think()~ call, every tool invocation, every Dispatcher decision, and the final test result. +- Regression mode: run the same benchmark after each version release. Track score trends. A version that regresses on SWE-bench does not ship. +- Target: competitive score with Claude Code and OpenClaw on SWE-bench-verified by v1.0.0. +~200 lines. + +** v0.65.0: Computer Use / Vision + +:PROPERTIES: +:ID: id-v120-vision +:CREATED: [2026-05-08 Fri] +:END: + +- Screenshot capture: X11 (~xwd~ / ~import~) and Wayland (~grim~) bridge. +- Vision model integration: send screenshot to a vision-capable model (GPT-4V, Claude 3.5, Gemini 2.0 Flash). +- Coordinate-based interaction: ~xdotool~ / ~ydotool~ for click and type commands. Dispatcher approval gate applies — screen interaction requires HITL by default. +- Use case: "open Firefox, search for the Passepartout GitHub repo, and star it." +~100 lines. + +** v0.66.0: Telemetry / Observability + +:PROPERTIES: +:ID: id-v120-telemetry +:CREATED: [2026-05-08 Fri] +:END: + +- Structured event log as JSONL in ~~/.local/share/passepartout/telemetry/~ (one file per session + aggregate) +- Event types: ~:session-start~, ~:think-call~ (tokens in/out, provider, model, duration), ~:tool-execution~ (name, duration, success/error), ~:gate-decision~ (gate name, result, pattern), ~:hitl-decision~ (approved/denied, pattern, session count), ~:context-snapshot~ (tokens used, foveal node, pruned count), ~:session-end~ (total tokens, total cost, tool calls, HITL count) +- Aggregate keys tracked as a hash table: HITL approval rate, average context usage, most-blocked gate, tokens saved by foveal pruning vs full context +- ~/telemetry~ TUI command: displays aggregate stats + per-session breakdown +- Feeds the evaluation harness (SWE-bench trajectory data comes from the same telemetry system) +~200 lines as a new skill ~symbolic-telemetry.org~. No daemon protocol changes. + +** v0.67.0: Consensus Loop + +:PROPERTIES: +:ID: id-v130-consensus +:CREATED: [2026-05-08 Fri] +:END: + +- Multi-provider parallel inference for critical decisions. When the action's impact score exceeds a threshold, the system sends the same prompt to 2–3 independent providers. +- Disagreement detection: compare structured outputs. If all providers agree, proceed with highest-confidence result. If they disagree, flag for HITL approval. +- Cost-aware: consensus mode doubles/triples cost. Only trigger when impact exceeds cost threshold. Configurable via ~CONSENSUS_THRESHOLD~. +- TUI consensus display: collapsible region listing each provider, its model, its proposal, and its confidence score. ~✓ 3/3 providers agree~ in green; ~✗ 2/3 agree~ in yellow. +~80 lines. + +** v0.68.0: GTD Integration + +:PROPERTIES: +:ID: id-v130-gtd +:CREATED: [2026-05-08 Fri] +:END: + +- Full GTD cycle: capture → process → clarify → organize → reflect → engage. +- Org properties: ~:TRIGGER:~ (what context), ~:BLOCKER:~ (what must complete first). +- Weekly review: agent scans all projects and tasks, surfaces stalled items, suggests next actions. Produced deterministically — zero LLM tokens. +- TUI agenda view: ~/agenda~ command renders Org-agenda as formatted scrollable region within the chat area. +~150 lines. + +** v0.69.0: Deep Emacs Integration + +:PROPERTIES: +:ID: id-v130-emacs +:CREATED: [2026-05-08 Fri] +:END: + +- Phase II — Interpreter: ELisp compatibility layer runs inside Passepartout's Common Lisp image. Key Emacs packages (Org-mode, Magit) run natively without an Emacs process. +- Org-agenda awareness: agent queries agenda view, incorporates agenda context into planning. +- Clock time tracking: agent starts/stops clocks on Org headlines, produces clock tables. +- Refile and archive: agent refiles headlines between Org files and archives completed items. +~300 lines. + +** v0.70.0: Save-Lisp-and-Die Binary + +:PROPERTIES: +:ID: id-v140-save-lisp +:CREATED: [2026-05-08 Fri] +:END: + +- The setup binary (~passepartout-setup~) is a ~save-lisp-and-die~ executable (~100MB: SBCL runtime + core Lisp code + native embedding inference from v0.4.0 + 23MB embedding model). No SBCL install required. No Quicklisp. No bash script. The user runs one file. +- Deterministic path (default, always runs first): the same distro detection, package installation, and configuration logic from today's bash script, reimplemented in Lisp. Handles Debian and Fedora families. +- LLM-assisted path (optional, activates on deterministic failure): downloads Qwen2.5-0.5B (~500MB GGUF, pinned by hash). The model classifies success/failure/recoverable-error and selects the next corrective action from a constrained decision tree. +- Model hash verification: the GGUF file is pinned by SHA-256 hash. +- After setup completes, the binary exits. The user runs ~passepartout daemon~ to start the full system (a live SBCL process, not a sealed binary — REPL, hot-reload, self-modification all available). +- Add FiveAM test: the deterministic path succeeds on a system with all dependencies pre-installed; the LLM-assisted path correctly classifies 10 common package-manager error messages. +~200 lines Lisp + build configuration. + +** v0.71.0: Channels + Providers — Match OpenClaw on Demand + +:PROPERTIES: +:ID: id-v100-channels +:CREATED: [2026-05-08 Fri] +:END: + +The daemon protocol is client-agnostic hex-framed plists over TCP. Every new channel is a new client that speaks the same protocol. OpenClaw's 23+ channels are trivially copyable — each platform needs a poll loop + send function, ~30 lines each. LLM providers are a row in ~*provider-cascade*~ — a new entry in ~neuro-provider.lisp~ with API endpoint + token pricing. Neither deserves its own release. + +- Channels: match OpenClaw's 23+ channels on demand. The Emacs bridge (already done, v0.4.0) proves the pattern. Each new platform (WhatsApp, iMessage, Matrix, IRC, etc.) is a skill that registers a poll-fn + send-fn. ~30 lines per channel. +- Providers: match OpenClaw/Hermes on provider count. Adding a new provider is a table entry in ~neuro-provider.lisp~: name, API endpoint, model list, pricing. ~20 lines per provider. +- Voice: STT + TTS are REST wrappers (~whisper~ / ~elevenlabs~ / ~espeak~). Already spec'd as a skill. ~50 lines. + +No separate releases. Done when needed, shipped when ready. + +** v0.72.0: Lish Shell +- plist-returning commands: ~(ls :path "~/memex/projects/")~ → structured result +- Pipe as function composition: ~(pipe (ls ...) (filter :state 'TODO))~ +- Org-buffer output: shell output rendered as Org headlines +- External bash compatibility: ~(bash "npm run build")~ → plist with exit code, stdout, stderr +~500 lines CL. Useful immediately for the agent. + +** v0.73.0: Buffer-as-CLOS Prototype +- buffer class: source (file path or Org AST), content, cursor, marks, overlays +- Key editing primitives: insert, delete, move, search, replace +- Org-AST-backed: editing mutates the AST, text rendering is a view +~300 lines CL. No display dependency. + +** v0.74.0: EQL5 Feasibility +- Add EQL5 to Quicklisp dependencies (optional, like croatoan) +- Compile and verify on Linux (primary target) +- Single QML window: "Passepartout" title, 800x600, dark background +- Verify event loop integration with SBCL threads +~100 lines QML + build config. + +** v0.75.0: EQL5 TCP Client +- QML window with terminal widget, input area, status bar +- Connects to daemon via existing framed TCP protocol +- Renders agent responses, gate trace, sidebar panels as QML components +- Lives alongside croatoan TUI (two clients, one daemon) +~300 lines QML + ~200 lines CL. + +** v0.76.0: Minibuffer Prototype +- Universal command line at bottom of Qt window +- /chat /edit /shell /eval dispatch +- Goes through same gate stack as agent actions +~200 lines CL. + +* v1.0.0: Neurosymbolic Maturity + +v1.0.0 is where the agent achieves symbolic-first reasoning in the 10-80-10 architecture. The probabilistic engine (LLM) handles 10% input translation and 10% output formatting. The symbolic engine (VivaceGraph + Screamer + ACL2) handles 80% of reasoning — task planning, fact retrieval, constraint solving, and formal verification. Zero LLM tokens for the reasoning core. + +Hallucination becomes structurally impossible because the symbolic engine will not accept a fact that contradicts its knowledge graph. Safety becomes provable because ACL2 can prove properties about the system's behavior. Self-improvement becomes stable because the agent modifies skills that are then verified before execution. + +The system is benchmarked against SWE-bench (competitive score with Claude Code and OpenClaw), verified under concurrent load (MVCC from v0.39.0), and validated by the eval harness (v0.9.0). The 10-80-10 planner operates on a mature symbolic index seeded from months of gate outcomes, Screamer deductions, LLM-proposed facts with provenance, and human-authored facts. + +The TUI at v1.0.0 is competitive: streaming responses, gate trace visualization, sidebar with 10 panels, skin system with 10+ presets, adaptive layout, full markdown, mouse support, spinner personality, and progress bars. The sidebar's gate trace, focus map, rule counter, sufficiency score, and provenance breakdown are capabilities no competitor can replicate — Passepartout's permanent UX differentiator. + +v1.0.0 is the brain at maturity. The symbolic engine reasons. The probabilistic engine translates. The gate stack verifies. The Merkle tree preserves provenance. The eval harness guards against regression. + diff --git a/projects/passepartout/architecture/_index.org b/projects/passepartout/architecture/_index.org index 1f0a39a..c436202 100644 --- a/projects/passepartout/architecture/_index.org +++ b/projects/passepartout/architecture/_index.org @@ -13,14 +13,14 @@ Architecture overview — narrative introduction, staged build-out, systemic eff | Stage | Delivers | Key cost | Timeline | |-------+----------+----------+----------| -| [[id:4a1f23b0-abc1-4def-9876-543210abcdef][0 — Now]] | Baseline: conventional computing | Patching treadmill, no deductive guarantees | Today | -| [[id:4a1f23b0-abc2-4def-9876-543210abcdef][1 — Social Protocol]] | Communication integrity, provable DAG | Crypto overhead, key management | Today | -| [[id:4a1f23b0-abc3-4def-9876-543210abcdef][2 — Verification]] | Verified gate, capability auth | Policy formalization burden | Today (limited) | -| [[id:4a1f23b0-abc4-4def-9876-543210abcdef][3 — Lisp Machine]] | Lisp image, Merkle memory, no kernel | Lisp tax, no backward compat, single address space | 2-5yr (soft) / 5-10yr (ASIC) | -| [[id:4a1f23b0-abc5-4def-9876-543210abcdef][4 — Inference]] | In-process LLM, token interception | ~10x compute/RAM/storage | Server now; consumer 3-5yr | -| [[id:4a1f23b0-abc6-4def-9876-543210abcdef][5 — Weights]] | Plist-native weights, weight-level provenance | ~100x GPU / ~2-5x ASIC | GPU hybrid now; ASIC 5-10yr | -| [[id:4a1f23b0-abc7-4def-9876-543210abcdef][6 — Training]] | Verified fine-tuning, neural world model | ~100x fine-tuning only | 3-5yr fine-tuning | -| [[id:4a1f23b0-abc8-4def-9876-543210abcdef][7 — Remaining]] | Physical threats, oracles, speculation, bootstrap axiom | Mitigations are non-computational | Forever | +|| [[id:4a1f23b0-abc1-4def-9876-543210abcdef][0 — Now]] | Baseline: conventional computing | Patching treadmill, no deductive guarantees | Today | +|| [[id:4a1f23b0-abc2-4def-9876-543210abcdef][1 — Social Protocol]] | Communication integrity, provable DAG + **Truth Layer (contradiction detection, verification economy)** | Crypto overhead, DAG storage growth, stake model attack surface | Today | +|| [[id:4a1f23b0-abc3-4def-9876-543210abcdef][2 — Verification]] | Verified gate, capability auth + **Symbolic Reasoner (CL HOL engine, knowledge-dependent auth)** | Reasoner dev cost, policy formalization burden | Today (limited) | +|| [[id:4a1f23b0-abc4-4def-9876-543210abcdef][3 — Lisp Machine]] | Lisp image, Merkle memory, no kernel | Lisp tax, no backward compat, single address space | 2-5yr (soft) / 5-10yr (ASIC) | +|| [[id:4a1f23b0-abc5-4def-9876-543210abcdef][4 — Inference]] | In-process LLM, token interception | ~10x compute/RAM/storage | Server now; consumer 3-5yr | +|| [[id:4a1f23b0-abc6-4def-9876-543210abcdef][5 — Weights]] | Plist-native weights, weight-level provenance | ~100x GPU / ~2-5x ASIC | GPU hybrid now; ASIC 5-10yr | +|| [[id:4a1f23b0-abc7-4def-9876-543210abcdef][6 — Training]] | Verified fine-tuning, neural world model | ~100x fine-tuning only | 3-5yr fine-tuning | +|| [[id:4a1f23b0-abc8-4def-9876-543210abcdef][7 — Remaining]] | Physical threats, oracles, speculation, bootstrap axiom | Mitigations are non-computational | Forever | **Systemic analysis:** - [[id:b9fa4b7b-bc61-4d7f-918d-ff687b80f2ba][Systemic effects over time]] — how verification cascades across society, economics, and geopolitics diff --git a/projects/passepartout/architecture/stage-1-social-protocol.org b/projects/passepartout/architecture/stage-1-social-protocol.org index e9cb548..c04c24c 100644 --- a/projects/passepartout/architecture/stage-1-social-protocol.org +++ b/projects/passepartout/architecture/stage-1-social-protocol.org @@ -78,6 +78,39 @@ those machines - malware that compromises an endpoint can sign messages using the endpoint's keys. The messages are authentic; the sender wasn't. The social protocol carries the authorization; it doesn't evaluate it. +### Truth Layer — Contradiction Detection and Verification Economy + +The provenance store seeds (signed empirical parameters) generalize to a +full **truth-accumulation layer** over the social protocol DAG. Every +knowledge assertion — not just parameters but any formal claim extracted +from Org prose by the LLM — is a signed, DAG-tracked message. + +| Component | What it does | Depends on | +|-----------|-------------|------------| +| Signed knowledge assertions | Any instance asserts P (a formal claim) signed with its DID, Merkle-linked to source evidence | DID identities, DAG | +| Contradiction detection | The DAG flags when instance A asserts P and instance B asserts ¬P. Conflicts are protocol events, not bugs | Signed assertions, DAG query | +| Verification staking | Instances vouch for assertions with reputation or compute stake. Surviving challenges accumulate confidence; false assertions degrade the issuer's weight | Contradiction detection | +| Truth scoring | Every assertion carries a confidence tier: (1) extracted/LLM-guess → (2) locally consistent → (3) corroborated by N independent instances → (4) gate-enforced | Staking, corroboration count | +| Reasoner code exchange | The same protocol distributes CL reasoner prototypes. Users collaborate on the symbolic reasoner (Stage 2) before it enters the gate | Signed code, DAG versioning | + +**The verification economy emerges naturally.** Instances that contribute +verified assertions gain reputation. Instances that propagate falsehoods +lose it. Over time, the protocol converges toward truths the same way +markets converge toward prices — without a central authority, through +incentive alignment. + +**Cost:** Assertion storage grows with the DAG. Contradiction detection +requires O(log n) DAG traversal per new assertion — feasible at social- +protocol scale (thousands of instances, not millions). Verification +staking introduces economic attack surface (Sybil, collusion) that must be +modeled in the stake function. + +**Bootstrap path:** The first assertions are LLM-extracted from Org prose +(confidence tier 1). Contradictions are initially rare (few instances, +sparse knowledge). As the instance count grows, contradiction frequency +increases and quality converges. This is Cyc's pump-priming problem solved +through network effects instead of hand-curation. + ← [[id:4a1f23b0-abc1-4def-9876-543210abcdef][Stage 0 — Now]] → [[id:4a1f23b0-abc3-4def-9876-543210abcdef][Stage 2 — Verification]] :PROPERTIES: diff --git a/projects/passepartout/architecture/stage-2-verification.org b/projects/passepartout/architecture/stage-2-verification.org index 07b75d5..ffb295b 100644 --- a/projects/passepartout/architecture/stage-2-verification.org +++ b/projects/passepartout/architecture/stage-2-verification.org @@ -78,6 +78,70 @@ use, the friction may lead users to bypass the gate. *Full gate guarantees arrive when Passepartout runs on its own Lisp machine (Stage 3). Before that, it's a correctness proof running on an untrusted substrate.* +### Symbolic Reasoner — CL-Native Higher-Order Logic Engine + +The gate needs to evaluate not just *security policy* but *epistemic +validity*: is this action consistent with what the system knows about the +world? The provenance store (Stage 1) provides quality-scored assertions, +but there is no engine to **reason over them** — to combine assertions, +prove entailments, detect contradictions, or generate causal explanations. + +**A CL-native symbolic reasoner** fills this gap. It operates over the +symbolic index of the Knowledge subsystem (predicates, relations, +constraints extracted from Org prose) and returns (entailed | contradicted +| undetermined) for any query. + +### Architecture + +| Layer | What it does | Implementation | +|-------|-------------|----------------| +| Assertion store | Quality-scored formal claims from Stage 1's truth layer | Provenance store hash table (Stage 2) | +| Constraint solver | SAT/SMT-style search over bounded problem spaces | Screamer (CL, existing) | +| Deduction engine | Forward/backward chaining over first-order subset of assertions | CL-native, starts as Screamer extension | +| Higher-order layer | Nested modalities — belief, intention, causation, temporal | +> Screamer cannot express these natively | CL macros + custom proof search | +| Gate interface | (action, context) → (permit \| deny \| needs-evidence) | ACL2 FFI across the Lisp boundary | + +### Why not Lean directly + +Lean 4 is C++ at its core — a separate trust domain that breaks the single +address space. The reasoner must be CL-native for the Stage 3 Lisp machine +model. Lean is the *reference* design: its tactics, elaboration, and type +theory inspire the CL implementation, but the engine itself is written in +Common Lisp and lives in the same memory graph as the evaluator and gate. + +### Development path across stages + +The reasoner is *born at Stage 1* and *hardens through Stage 2*: + +| Stage | Reasoner state | How it gets there | +|-------|---------------|-------------------| +| 1 | CL prototype (Screamer-based, first-order) | Shared via social protocol's Reasoner Code Exchange. Users test against local symbolic indices, share patches | +| 1 | Higher-order extensions sketched | CL macros for modal logic, causal chains — tested on small assertion sets | +| 2 | Reasoner feeds gate decisions | Gate delegates knowledge-dependent checks: "is this action valid given what we know?" Works on quality-scored assertions from Stage 1's truth layer | +| 3 | Reasoner absorbed into address space | Same memory graph as evaluator, gate, LLM. No FFI, no IPC | +| 4 | Reasoner enters self-improvement loop | In-process LLM reads reasoner code, proposes improvements, gate checks policy | + +### Cost + +- **Screamer-level reasoning:** O(n) over the relevant subtree — the same + sparse tree retrieval the Knowledge subsystem already uses. A 4K-assertion + context resolves in milliseconds +- **Higher-order deduction:** O(exp) in the general case. Scoped by the + LLM narrowing the reasoning window first — the user never waits for a + global proof +- **Proof quality vs speed:** The reasoner can return (entailed with + confidence 0.83) rather than a binary yes/no. The gate chooses the + threshold per domain + +### What this enables + +The gate graduates from checking *who* is authorized to checking *what is +true*. A policy can say "deny actions based on false premises" — and the +reasoner determines which premises are false. This is the connection +between security verification and knowledge verification that the original +Cyc architecture required but could not enforce. + ← [[id:4a1f23b0-abc2-4def-9876-543210abcdef][Stage 1 — Social Protocol]] → [[id:4a1f23b0-abc4-4def-9876-543210abcdef][Stage 3 — Lisp Machine]] :PROPERTIES: diff --git a/projects/passepartout/strategy/domain-sequencing.org b/projects/passepartout/strategy/domain-sequencing.org new file mode 100644 index 0000000..75f03b8 --- /dev/null +++ b/projects/passepartout/strategy/domain-sequencing.org @@ -0,0 +1,70 @@ +:PROPERTIES: +:CREATED: [2026-05-29 Fri] +:ID: c7d3f1a2-8b4e-5d6f-9a1c-3b2d4e5f6a7b +:END: +#+title: Domain Sequencing — What Gets Built When and Why +#+filetags: :passepartout:strategy:domains:sufficiency: + +The sufficiency flip is per-domain, and domains must be sequenced by strategic value, not intellectual interest. Building general knowledge first is the Cyc trap. Building the verification economy first is the way out. + +**First: Logic and mathematics** + +The axioms are already written. Peano arithmetic, set theory, group theory, type theory — loaded directly into the symbolic index as formal rules, not LLM-extracted from prose. Zero gate outcomes needed because there is no ambiguity to resolve through observation. This domain reaches [[id:efc76898-03f7-57ba-923d-35d65da88bb7][sufficiency]] the moment the reasoner exists. It also provides the formal foundation every other domain depends on — every gate rule ultimately reduces to a logical inference, and a verified logic layer means the gate's own axioms are trustworthy. + +**Second: Software engineering** + +This is the bootstrap — the system must build itself before it can build anything else: + +- The gate stack seeds 50-70 entity classes from its own code (files, commands, processes, networks, dependencies) +- Every git commit, build error, test failure, and shell command is a gate outcome — accumulating toward sufficiency without manual curation +- The reasoner is born as a Screamer-based CL prototype shared via the social protocol at Stage 1, hardens into the gate at Stage 2, and enters self-improvement under the in-process LLM at Stage 4 +- The social protocol itself is software — its correctness is verified by the same gate that software engineering produces + +Sufficiency in software engineering means the system can propose, verify, and apply changes to its own codebase under gate supervision. This is the bootstrap completion signal. + +**Third: Regulated industries** + +This is where the verification economy produces real revenue, not just knowledge. Key properties: + +| Domain | Regulation | Gate rule density | Revenue model | +|--------|-----------|-------------------|---------------| +| Healthcare | [[id:9a1e2d3f-4b5c-6d7e-8f9a-0b1c2d3e4f5a][HIPAA]] | High (every access control, BAA, audit log) | Per-seat compliance appliance | +| Finance | [[id:a2b3c4d5-e6f7-8a9b-0c1d-2e3f4a5b6c7d][SOX]], [[id:b3c4d5e6-f7a8-9b0c-1d2e-3f4a5b6c7d8e][BASEL III]], [[id:c4d5e6f7-a8b9-0c1d-2e3f-4a5b6c7d8e9f][NY DFS 500]] | Very high (every transaction, every risk model) | Transaction fee or audit subscription | +| Privacy | [[id:d5e6f7a8-b9c0-1d2e-3f4a-5b6c7d8e9f0a][GDPR]], [[id:e6f7a8b9-c0d1-2e3f-4a5b-6c7d8e9f0a1b][CCPA]] | Medium (consent records, data mapping) | Per-data-subject | +| AI safety | [[id:f7a8b9c0-d1e2-3f4a-5b6c-7d8e9f0a1b2c][EU AI Act]] | Evolving (risk classification, conformity assessment) | Certification monopoly | + +**Why regulated industries come before the sciences:** + +1. **Regulations are formal by nature.** HIPAA, SOX, GDPR are written as logical conditions — "deny access to PHI without BAA" is a first-order gate rule. No LLM extraction needed. The ontology work is translation, not discovery. + +2. **Every enforced rule is a gate outcome.** A hospital running 10,000 PHI access checks per day generates gate outcomes faster than any solo developer running shell commands. The verification economy compounds faster in regulated domains because the transaction volume is higher. + +3. **The revenue is recurring and defensible.** A SOC 2 report that is a gate configuration — not a PDF — cannot be replicated by a consultancy. The gate rules accumulate across customers via the social protocol, creating a shared compliance layer that no single competitor can reproduce. This is the [[id:827bc546-e887-5b7c-9b65-6392beaf0920][verification monopoly]]. + +4. **First-mover advantage is real.** The first gate configuration for HIPAA risk assessments becomes the template. Every audit that passes against it is a data point. Late entrants must either replicate years of accumulated gate outcomes or buy access to the commons. A proprietary compliance vendor cannot compete with a commons that improves with every customer. + +5. **The ontology work can happen in parallel with hardware maturation.** Encoding HIPAA rules as gate predicates is a Stage 2 activity (software layer on conventional hardware). Enforcement at scale — passing a SOC 2 Type II audit — waits for Stage 3 (Lisp machine). But the encoding, testing, and network convergence happen years before the silicon is ready. + +**Fourth: Physics, chemistry, and the rest of science can wait.** + +These domains are infinitely deep and return zero revenue until the verification economy is self-funding: + +- Physics: formal ontology (SI units, conservation laws) exists in Wikidata and loads immediately. But most physics knowledge isn't exercised through gate actions — no shell commands, no access controls. Sufficiency depends on someone running simulations that generate gate-verifiable outcomes. +- Chemistry: PubChem and ChEBI provide the entity backbone, but organic chemistry has exception rules Screamer cannot derive from first principles. The LLM extraction pipeline stays active longest here. +- Biology, neuroscience, astronomy, geology — same pattern. The basic science ontology seeds for free. The sufficiency flip requires domain-specific gate outcomes that only come from applied use. + +**The Cyc lesson inverted:** + +Lenat needed 24.5 million assertions before Cyc was generally useful. He reached that number and was still dismissed because the assertions had no commercial verification — they were correct but orphaned. + +Common does not build general knowledge first. It builds narrow, formal, revenue-generating domain rules — software engineering (the bootstrap) then regulated industries (the economy). Each rule is verified by gate outcomes. Each customer contributes to the commons. By the time physics needs a verified ontology, the verification economy is self-funding and the sciences enter a system that already works. + +**Summary:** + +| Priority | Domain | Sufficiency timeline | Revenue | Bootstrap dependency | +|----------|--------|---------------------|---------|---------------------| +| 1 | Logic and math | Instant | None (foundation) | None | +| 2 | Software engineering | Months | Indirect (builds the tool) | Logic and math | +| 3 | Regulated industries | 1-2 years | Direct (compliance appliance) | Software engineering + gate | +| 4 | Physical sciences | Years to never | Indirect (applied spin-offs) | Everything above | +| 5 | General memex | Never fully flips | None (product is tension) | Everything above |