5. Honcho

The idea in one screen. Honcho, from Plastic Labs, treats memory as reasoning about a person. Every stored item is a conclusion with a level, and a derived conclusion keeps the ids of the conclusions it was drawn from.

Level Means Written by
explicit what the person said the deriver, as messages arrive
deductive what follows from it, and updates when a fact changes the dreamer, later, in the background
inductive a pattern across several conclusions the dreamer
contradiction two statements that cannot both be true nothing in this release (section 6)

Two background jobs write the memory. The deriver makes one model call per batch of new messages and stores what was said. The dreamer runs from time to time: two agents with tools look through the store, add conclusions, delete outdated ones and keep a short peer card. Two read paths give the memory back: the dialectic, an agent that searches and writes an answer, and the representation, a list of conclusions with no model call.

Honcho's architecture, with the running example.

Five questions. Reading and cost, the other two stages every notebook in this series looks at, are sections 8 and 9.

  1. Extraction. What does the deriver keep from a session, and what does saving do with near-duplicates?
  2. The dream. What do the two agents look at, and what do they write?
  3. Updating. When the user changes a fact, what happens to the old conclusion, and to the conclusions drawn from it?
  4. What the code checks. Which rules about premises are enforced by code, and which only requested in a prompt?
  5. Reading. What do the two read paths hand to the model that answers?

What is run here

Honcho's own text, driven by small local functions.

When a dream runs. Honcho starts one on its own only when a peer has at least 50 new explicit conclusions, at least 8 hours have passed since the last dream, and the user has then been quiet for 60 minutes. This conversation is short on purpose and produces about 15. In real use many other conversations would fall between the first session in March and the second in July, so a dream between them is what would happen. Here a dream is started by hand after each session. (The experiment started one dream after the whole history.)

Setup

The model is set in config.py, which also reads GEMINI_API_KEY from the .env at the top of the repository.

The outputs below are from one run. Model replies vary between runs, even at temperature 0 and with the same prompt, so a rerun can differ in details from what is shown here, and a different model can change more. The mechanism stays the same.

[1]
Code · 28 lines
import json
from dataclasses import dataclass, field
from datetime import datetime, timedelta

import numpy as np
import pandas as pd
from pydantic import BaseModel, Field

import honcho_source as hs
from config import CHAT_MODEL, embed, generate

pd.set_option("display.max_colwidth", None)
pd.set_option("display.width", 200)


def table(frame):
    """A table with text on the left and numbers on the right, each header over its column."""
    numbers = frame.select_dtypes("number").columns
    return (frame.style.hide(axis="index").format(precision=3, thousands=",", na_rep="")
            .set_table_styles([{"selector": "th", "props": "text-align: left;"},
                               {"selector": "td", "props": "text-align: left; white-space: pre-wrap;"},
                               {"selector": "caption", "props": "text-align: left; font-weight: bold;"}])
            .set_table_styles({column: [{"selector": "", "props": "text-align: right;"}] for column in numbers},
                              overwrite=False))


print(f"chat model: {CHAT_MODEL}")
print(f"Honcho source: v3.3.0, commit {hs.HONCHO_COMMIT[:7]}")
chat model: gemini-3.1-flash-lite
Honcho source: v3.3.0, commit 608aec8

Every model call goes through one log, with its token counts.

[2]
Code · 13 lines
CALLS = []


def log_call(step, reply):
    CALLS.append({"step": step,
                  "tokens in": reply.usage_metadata.prompt_token_count,
                  "tokens out": reply.usage_metadata.candidates_token_count or 0})


def cost_so_far():
    tokens_in = sum(c["tokens in"] for c in CALLS)
    tokens_out = sum(c["tokens out"] for c in CALLS)
    return f"{len(CALLS)} model calls so far   {tokens_in:,} tokens in / {tokens_out:,} out"

The conversation

The conversation from notebook 0, repeated here so that this notebook runs on its own. Two sessions four months apart, then a question in a third. Session 2 changes something from session 1 (the diet) and adds two people. Honcho calls each participant a peer. The user is the peer Anton; the assistant is a peer that Honcho is told not to model, so its turns are context for the user's and nothing is concluded about it.

[3]
Code · 60 lines
PEER, ASSISTANT = "Anton", "assistant"

SESSION_1 = [  # 14 March 2026
    (PEER, "I'm planning a dinner for my sister's visit to Berlin next week. "
           "Worth saying up front: I've been strictly vegetarian for eight years, "
           "and I have a severe peanut allergy — anaphylactic, not a preference."),
    (ASSISTANT, "Understood — no meat, and peanuts are a hard exclusion. Any cuisine you lean towards?"),
    (PEER, "Indian, usually. Paneer dishes especially. And I'd rather not spend more "
           "than about 40 euros a head."),
]

SESSION_2 = [  # 20 July 2026, four months later
    (PEER, "Small update on the food thing — I started eating fish about a month ago. "
           "So I'm pescatarian now, not vegetarian. Still no meat, and the peanut "
           "situation obviously hasn't changed."),
    (ASSISTANT, "Noted, fish is in. Anything else shifted?"),
    (PEER, "I moved to Kreuzberg in May, so anything walkable from there is a plus."),
    (ASSISTANT, "Kreuzberg, noted. Anything else for next time?"),
    (PEER, "Yes — my sister Lena is coming back in the autumn, and she's bringing her partner, Jonas."),
    (ASSISTANT, "Lovely. Anything I should know about what they eat?"),
    (PEER, "Lena can't eat shellfish, and Jonas is coeliac."),
]

QUESTION = (  # a new session in September, with no transcript
    "My sister and her partner are in town tonight. Book the three of us somewhere "
    "for dinner — you know what we can and can't eat."
)

SESSION_START = {"s1": datetime(2026, 3, 14, 12, 0), "s2": datetime(2026, 7, 20, 12, 0)}
TODAY = datetime(2026, 9, 1)


@dataclass
class Message:
    id: int
    session: str
    peer: str
    time: datetime
    content: str


MESSAGES: list[Message] = []


def add_messages(session, turns):
    """Store a session's messages, a minute apart, as the experiment did."""
    start = len(MESSAGES)
    for i, (peer, content) in enumerate(turns):
        MESSAGES.append(Message(start + i + 1, session, peer, SESSION_START[session] + timedelta(minutes=i),
                                content))
    return MESSAGES[start:]


def show_session(caption, turns):
    return table(pd.DataFrame(turns, columns=["peer", "content"])).set_caption(caption)


display(show_session("Session 1 · 14 March 2026", SESSION_1))
display(show_session("Session 2 · 20 July 2026, four months later", SESSION_2))
display(show_session("Session 3 · 1 September 2026, with no transcript", [(PEER, QUESTION)]))
Session 1 · 14 March 2026
peer content
Anton I'm planning a dinner for my sister's visit to Berlin next week. Worth saying up front: I've been strictly vegetarian for eight years, and I have a severe peanut allergy — anaphylactic, not a preference.
assistant Understood — no meat, and peanuts are a hard exclusion. Any cuisine you lean towards?
Anton Indian, usually. Paneer dishes especially. And I'd rather not spend more than about 40 euros a head.
Session 2 · 20 July 2026, four months later
peer content
Anton Small update on the food thing — I started eating fish about a month ago. So I'm pescatarian now, not vegetarian. Still no meat, and the peanut situation obviously hasn't changed.
assistant Noted, fish is in. Anything else shifted?
Anton I moved to Kreuzberg in May, so anything walkable from there is a plus.
assistant Kreuzberg, noted. Anything else for next time?
Anton Yes — my sister Lena is coming back in the autumn, and she's bringing her partner, Jonas.
assistant Lovely. Anything I should know about what they eat?
Anton Lena can't eat shellfish, and Jonas is coeliac.
Session 3 · 1 September 2026, with no transcript
peer content
Anton My sister and her partner are in town tonight. Book the three of us somewhere for dinner — you know what we can and can't eat.

A correct answer to the question needs: pescatarian (no longer vegetarian), no peanuts, no shellfish for Lena, no gluten for Jonas, a liking for Indian food, and somewhere near Kreuzberg.

The store

A conclusion is one row. These are the fields of Honcho's documents table that matter here. Two of them carry the design:

A delete is a soft delete: Honcho stamps deleted_at and every read skips the row, but the row stays, and so do the links that point to it.

[4]
Code · 46 lines
LEVELS = ["explicit", "deductive", "inductive", "contradiction"]


@dataclass
class Conclusion:
    id: str
    level: str                  # explicit | deductive | inductive | contradiction
    content: str
    said_at: datetime           # explicit: the time of the message; derived: of its latest source
    session: str | None = None  # explicit: the session it came from; derived: none
    source_ids: list = field(default_factory=list)   # the conclusions it was drawn from
    premises: list = field(default_factory=list)     # deductive: premise text, as written
    sources: list = field(default_factory=list)      # inductive: source text, as written
    pattern_type: str = ""      # inductive only
    confidence: str = ""        # inductive only: low | medium | high
    message_ids: list = field(default_factory=list)
    times_derived: int = 1      # raised when the same conclusion is derived again
    deleted: str = ""           # "" while live; otherwise what deleted it
    order: int = 0              # insertion order (the row's created_at)
    embedding: list = field(default_factory=list, repr=False)


STORE: dict[str, Conclusion] = {}
PEER_CARD: list[str] | None = None   # none until a dream writes one


def live(levels=None):
    rows = [c for c in STORE.values() if not c.deleted]
    return [c for c in rows if levels is None or c.level in levels]


def new_id(level):
    return f"{level[0]}{len(STORE) + 1}"


def show_store(rows=None, caption=None):
    rows = list(STORE.values()) if rows is None else rows
    frame = pd.DataFrame([{
        "id": c.id, "level": c.level, "said at": f"{c.said_at:%Y-%m-%d %H:%M}",
        "content": c.content,
        "drawn from": ", ".join(c.source_ids) or "—",
        "x derived": c.times_derived,
        "deleted": c.deleted or "",
    } for c in sorted(rows, key=lambda c: (LEVELS.index(c.level), c.order))])
    styled = table(frame)
    return styled.set_caption(caption) if caption else styled

How Honcho prints conclusions

The agents and the read paths see conclusions as text, in a few fixed formats. These functions reproduce Honcho's (Representation.str_with_ids and format_as_markdown in src/utils/representation.py). Each line starts with the time the conclusion was said, to the minute.

[5]
Code · 56 lines
def stamp(c):
    return f"[{c.said_at:%Y-%m-%d %H:%M:%S}]"


def with_id(c):
    """One conclusion as the dream agents see it: id, time, text, then premises or sources."""
    head = f"[id:{c.id}] {stamp(c)}"
    if c.level == "explicit":
        return f"{head} {c.content}"
    if c.level == "deductive":
        return f"{head} {c.content}\n" + "\n".join(f"    - {p}" for p in c.premises)
    if c.level == "inductive":
        tail = "".join(f"\n    - {s}" for s in c.sources)
        return f"{head} [{c.confidence}] {c.content}{tail}"
    return f"{head} CONTRADICTION: {c.content}" + "".join(f"\n    - {s}" for s in c.sources)


def by_level_with_ids(rows):
    """Representation.str_with_ids: the four levels in order, numbered."""
    parts = []
    for level in LEVELS:
        parts.append(f"{level.upper()}:\n")
        parts += [f"{i}. {with_id(c)}" for i, c in enumerate([c for c in rows if c.level == level], 1)]
        parts.append("")
    return "\n".join(parts)


def as_markdown(rows, include_ids=False):
    """Representation.format_as_markdown: what the read paths return."""
    parts = []
    explicit = [c for c in rows if c.level == "explicit"]
    if explicit:
        parts += ["## Explicit Observations\n"] + [f"{stamp(c)} {c.content}" for c in explicit] + [""]
    deductive = [c for c in rows if c.level == "deductive"]
    if deductive:
        parts.append("## Deductive Observations\n")
        for c in deductive:
            parts.append(f"{f'[id:{c.id}] ' if include_ids else ''}{stamp(c)} {c.content}")
            if c.premises:
                parts += ["   Premises:"] + [f"   - {p}" for p in c.premises]
            parts.append("")
        parts.append("")
    inductive = [c for c in rows if c.level == "inductive"]
    if inductive:
        parts.append("## Inductive Observations\n")
        for c in inductive:
            parts.append(f"{f'[id:{c.id}] ' if include_ids else ''} **Pattern** [{c.confidence}]: {c.content}")
            if c.pattern_type:
                parts.append(f"   **Type**: {c.pattern_type}")
            if c.sources:
                parts += ["   **Sources**:"] + [f"   - {s}" for s in c.sources[:5]]
                if len(c.sources) > 5:
                    parts.append(f"   - ... and {len(c.sources) - 5} more")
            parts.append("")
        parts.append("")
    return "\n".join(parts)

1. Session 1: the deriver

When messages arrive, Honcho queues them. The deriver takes a batch (it waits until the batch holds 512 tokens or is 30 minutes old) and makes one model call. Each message goes into the prompt in a tag that says who wrote it, when, and whether that peer is the one being modelled (target="true").

[6]
Code · 3 lines
s1_messages = add_messages("s1", SESSION_1)
tagged = "\n".join(hs.deriver_message(i, m.peer, PEER, m.time, m.content) for i, m in enumerate(s1_messages))
print(tagged)
<message idx="0" peer="Anton" target="true" time="2026-03-14 12:00:00">I'm planning a dinner for my sister's visit to Berlin next week. Worth saying up front: I've been strictly vegetarian for eight years, and I have a severe peanut allergy — anaphylactic, not a preference.</message>
<message idx="1" peer="assistant" target="false" time="2026-03-14 12:01:00">Understood — no meat, and peanuts are a hard exclusion. Any cuisine you lean towards?</message>
<message idx="2" peer="Anton" target="true" time="2026-03-14 12:02:00">Indian, usually. Paneer dishes especially. And I'd rather not spend more than about 40 euros a head.</message>

The whole prompt, as Honcho writes it:

[7]
Code · 1 line
print(hs.deriver_prompt(PEER, tagged))
Analyze messages to extract **explicit atomic facts** about the target peer.

[EXPLICIT] DEFINITION: Facts about the target peer that can be derived directly from their messages.
   - Transform statements into one or multiple conclusions
   - Each conclusion must be self-contained with enough context
   - Use absolute dates/times when possible, resolving relative references against the message `time` attribute

RULES:
- The target peer is the peer identified below under `Target peer:`.
- A peer can be a human user, AI agent, bot, service, or other actor.
- Each message is wrapped as `<message idx="N" peer="..." target="true|false" time="...">`. `target="true"` marks messages authored by the target peer; `target="false"` marks everyone else.
- Extract ALL observations from `target="true"` messages. Use `target="false"` messages only as context to interpret them; never derive a fact about the target peer from what another peer said, did, or reported.
- When the target peer answers a question or accepts a proposal from another peer ("yes", "the first one"), the details in that question or proposal count as stated by the target peer. A bare acknowledgement ("ok", "thanks") does not.
- A batch may contain few or no `target="true"` messages, even when it holds many long messages from other peers (agent turns, tool output, system notices). In that case produce few or no conclusions.
- Do not record conversational mechanics (greeting, thanking, acknowledging, asking or answering a question) or anything true of nearly every participant.
- Each conclusion states exactly one independent fact. Keep a fact's reason, purpose, tool, place, and qualifiers attached to it; they are part of the same fact. Split when a conclusion joins independent facts, or when a clause adds a new fact about a person or thing.
- Do not emit two conclusions that state the same fact in different words.
- Properly attribute observations to the correct subject. If the target peer is referencing someone or something else, make that clear.
- Write each observation for a reader who knows only the peer id: identify other people and things by their relation to this peer, and leave no pronoun, "it", "there", or relative time unresolved.
- Include only what is needed to identify who or what the observation is about and to state the fact. Do not add explanation or background.



Target peer:
Anton

Write `Anton` as the subject of every observation about this peer. Never write "the target peer" or "the user" in its place.

Messages to analyze:
<messages>
<message idx="0" peer="Anton" target="true" time="2026-03-14 12:00:00">I'm planning a dinner for my sister's visit to Berlin next week. Worth saying up front: I've been strictly vegetarian for eight years, and I have a severe peanut allergy — anaphylactic, not a preference.</message>
<message idx="1" peer="assistant" target="false" time="2026-03-14 12:01:00">Understood — no meat, and peanuts are a hard exclusion. Any cuisine you lean towards?</message>
<message idx="2" peer="Anton" target="true" time="2026-03-14 12:02:00">Indian, usually. Paneer dishes especially. And I'd rather not spend more than about 40 euros a head.</message>
</messages>

The model answers in a fixed JSON shape: a list called explicit, one content string each. The descriptions below are Honcho's (PromptRepresentation in src/utils/representation.py); the schema is sent with the call, so the model reads them too.

[8]
Code · 26 lines
class ExplicitObservationBase(BaseModel):
    content: str = Field(description="The explicit observation")


class PromptRepresentation(BaseModel):
    explicit: list[ExplicitObservationBase] = Field(
        description="Facts LITERALLY stated by the user - direct quotes or clear paraphrases only, "
                    "no interpretation or inference.",
        default_factory=list)


def derive(session, messages):
    """One deriver call for a batch of messages; returns the new rows, not yet saved."""
    tagged = "\n".join(hs.deriver_message(i, m.peer, PEER, m.time, m.content) for i, m in enumerate(messages))
    reply = generate(hs.deriver_prompt(PEER, tagged), schema=PromptRepresentation)
    log_call(f"deriver {session}", reply)
    out = PromptRepresentation.model_validate_json(reply.text)
    # Every row is stamped with the time of the batch's last message (Honcho: latest_message.created_at).
    said_at = messages[-1].time
    target_ids = [m.id for m in messages if m.peer == PEER]
    return [Conclusion("", "explicit", o.content.strip(), said_at, session, message_ids=target_ids)
            for o in out.explicit]


s1_rows = derive("s1", s1_messages)
print(json.dumps([r.content for r in s1_rows], indent=1, ensure_ascii=False))
[
 "Anton is planning a dinner for his sister's visit to Berlin during the week of March 16, 2026.",
 "Anton has been strictly vegetarian since 2018.",
 "Anton has a severe, anaphylactic peanut allergy.",
 "Anton prefers Indian cuisine.",
 "Anton enjoys paneer dishes.",
 "Anton has a budget of approximately 40 euros per person for the dinner."
]

Saving: exact and near duplicates

Saving is not a plain insert. Honcho's create_documents (src/crud/document.py) applies three rules to each new row, in order:

  1. An exact duplicate is dropped. Same text (ignoring case and spaces at the ends), same level, and for an explicit row the same session. The existing row's times_derived goes up by one.
  2. A near duplicate is merged. The closest live row of the same level (and, for an explicit row, the same session) is compared by embedding. At a cosine distance of 0.05 or less the two count as one, and the richer text wins: words that only one side has count ten times as much as shared ones. If the new row wins, the old one is deleted and the new one inherits its count, plus one.
  3. Otherwise the row is stored.

Rule 2 never merges explicit rows from different sessions, so a fact said in March and said again in July is stored twice.

[9]
Code · 64 lines
NEAR = 0.05
SAVE_LOG = []


def normalized(text):
    return text.strip().lower()


def key(c):
    return (normalized(c.content), c.level, c.session if c.level == "explicit" else None)


def cosine_distance(a, b):
    a, b = np.asarray(a), np.asarray(b)
    return 1 - float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))


def richness(text, other):
    """Honcho's _score_semantic_dup, with words instead of tokens."""
    mine, theirs = set(text.lower().split()), set(other.lower().split())
    return len(mine) + 10 * len(mine - theirs)


def save(rows, step):
    """create_documents: drop exact duplicates, merge near duplicates, store the rest."""
    for row, vector in zip(rows, embed([r.content for r in rows])):
        row.embedding = vector
    seen = set()
    for row in rows:
        if key(row) in seen:
            SAVE_LOG.append((step, row.content, "exact duplicate within the batch: dropped"))
            continue
        seen.add(key(row))
        same = [c for c in live() if key(c) == key(row)]
        if same:
            same[0].times_derived += 1
            SAVE_LOG.append((step, row.content, f"exact duplicate of {same[0].id}: dropped, {same[0].id} counted again"))
            continue
        peers = [c for c in live([row.level]) if row.level != "explicit" or c.session == row.session]
        if peers:
            nearest = min(peers, key=lambda c: cosine_distance(row.embedding, c.embedding))
            distance = cosine_distance(row.embedding, nearest.embedding)
            if distance <= NEAR:
                if richness(row.content, nearest.content) >= richness(nearest.content, row.content):
                    row.times_derived = nearest.times_derived + 1
                    store(row)
                    nearest.deleted = f"replaced by {row.id} (near duplicate)"
                    SAVE_LOG.append((step, row.content, f"near duplicate of {nearest.id} ({distance:.3f}): replaces it"))
                else:
                    nearest.times_derived += 1
                    SAVE_LOG.append((step, row.content, f"near duplicate of {nearest.id} ({distance:.3f}): dropped"))
                continue
        store(row)


def store(row):
    row.id = new_id(row.level)
    row.order = len(STORE)
    STORE[row.id] = row


save(s1_rows, "s1")
print(cost_so_far())
show_store(caption="The store after session 1")
1 model calls so far   769 tokens in / 161 out
The store after session 1
id level said at content drawn from x derived deleted
e1 explicit 2026-03-14 12:02 Anton is planning a dinner for his sister's visit to Berlin during the week of March 16, 2026. — 1
e2 explicit 2026-03-14 12:02 Anton has been strictly vegetarian since 2018. — 1
e3 explicit 2026-03-14 12:02 Anton has a severe, anaphylactic peanut allergy. — 1
e4 explicit 2026-03-14 12:02 Anton prefers Indian cuisine. — 1
e5 explicit 2026-03-14 12:02 Anton enjoys paneer dishes. — 1
e6 explicit 2026-03-14 12:02 Anton has a budget of approximately 40 euros per person for the dinner. — 1

Six rows, each one fact, each with Anton as the subject and the time of the session's last message. The relative dates were resolved against the message time: "next week" became "the week of March 16, 2026" and "for eight years" became "since 2018". Nothing was merged: no two rows are near each other.

2. Dream 1: two agents with tools

A dream runs two specialists one after the other, both agents: a model in a loop that calls tools until it answers DONE.

  1. Deduction (at most 12 rounds) looks for knowledge updates, logical implications and contradictions, may delete outdated conclusions, and keeps the peer card.
  2. Induction (at most 10 rounds) looks for patterns across conclusions.

Neither is shown the whole store. Each starts from one instruction ("Begin with get_recent_observations") and sees only what its tools return: the ten most recent conclusions by default, or the twenty closest to a search.

The tools

The descriptions the agents read are Honcho's. Their behaviour is written out below, with Honcho's output formats.

[10]
Code · 5 lines
for name in ("DEDUCTION_SPECIALIST_TOOLS", "INDUCTION_SPECIALIST_TOOLS", "DIALECTIC_TOOLS"):
    print(f"{name}: {', '.join(t['name'] for t in hs.tool_set(name))}")
print()
for t in hs.tool_set("DEDUCTION_SPECIALIST_TOOLS"):
    print(f"{t['name']}: {t['description']}\n")
DEDUCTION_SPECIALIST_TOOLS: get_recent_observations, search_memory, search_messages, create_observations_deductive, delete_observations, update_peer_card
INDUCTION_SPECIALIST_TOOLS: get_recent_observations, search_memory, search_messages, create_observations_inductive
DIALECTIC_TOOLS: search_memory, search_messages, get_observation_context, grep_messages, get_messages_by_date_range, search_messages_temporal, get_reasoning_chain

get_recent_observations: Get the most recent observations about the peer. Useful for understanding what's been learned recently.

search_memory: Search for observations in memory using semantic similarity. Use this to find relevant information about the peer when you need to recall specific details.

search_messages: Search for messages using semantic similarity and retrieve conversation snippets. Returns matching messages with surrounding context (2 messages before and after). Nearby matches within the same session are merged into a single snippet to avoid repetition.

create_observations_deductive: Create new deductive observations discovered while answering the query. Every observation must include non-empty source_ids and premise text. Use this only for novel deductions grounded in existing observations.

delete_observations: Delete observations by their IDs. Use the exact ID shown in [id:xxx] format from search results. Example: if observation shows '[id:abc123XYZ]', pass 'abc123XYZ' to delete it.

update_peer_card: Update the peer card with stable identity markers about the observed peer. An identity marker distinguishes the peer from others of its kind and persists across interactions. The peer may be any entity with identity that changes over time (human, agent, codebase, team, organization) — do not assume the peer is human. Each entry must start with one of four prefixes: `IDENTITY:` (canonical name, kind, aliases, IDs), `ATTRIBUTE:` (stable durable property, including explicitly stated standing preferences), `RELATIONSHIP:` (durable link to another entity), or `INSTRUCTION:` (standing rule of engagement the peer has explicitly stated). Do not write `TRAIT:` or behavioral `PREFERENCE:` entries, one-off observations, transient state, inferred facts not directly supported by evidence, evidence bundles / `e.g.` clauses, or entries about co-occurring peers. Entries without an allowed prefix or that exceed the per-entry length cap are rejected.

[11]
Code · 149 lines
def by_similarity(query, rows):
    if not rows:
        return []
    vector = embed([query])[0]
    return sorted(rows, key=lambda c: cosine_distance(vector, c.embedding))


MESSAGE_VECTORS = {}


def message_vector(m):
    if m.id not in MESSAGE_VECTORS:
        MESSAGE_VECTORS[m.id] = embed([m.content])[0]
    return MESSAGE_VECTORS[m.id]


def snippets(matches, window):
    """Each match with `window` messages around it, overlapping windows of one session merged."""
    groups = []
    for m in sorted(matches, key=lambda m: m.id):
        session = [x for x in MESSAGES if x.session == m.session]
        i = session.index(m)
        lo, hi = session[max(0, i - window)].id, session[min(len(session) - 1, i + window)].id
        if groups and groups[-1]["session"] == m.session and lo <= groups[-1]["hi"]:
            groups[-1]["hi"] = max(hi, groups[-1]["hi"])
            groups[-1]["matches"] += 1
        else:
            groups.append({"session": m.session, "lo": lo, "hi": hi, "matches": 1})
    out = []
    for i, g in enumerate(groups, 1):
        lines = [f"{x.time:%Y-%m-%d %H:%M:%S} {x.peer}: {x.content}" for x in MESSAGES if g["lo"] <= x.id <= g["hi"]]
        out.append(f"--- Snippet {i} (session: {g['session']}, {g['matches']} match(es)) ---\n" + "\n".join(lines))
    return out


def message_snippets(matches, description, window=2):
    parts = snippets(matches, window)
    return (f"Found {len(matches)} matching messages in {len(parts)} conversation snippets {description}.\n"
            "These are raw messages with no observation ID - do not cite them in source_ids; "
            "use their text in premises/sources instead:\n\n" + "\n\n".join(parts))


def get_recent_observations(limit=10, session_only=False):
    rows = sorted(live(), key=lambda c: -c.order)[:limit]
    if not rows:
        return "No recent observations found"
    return f"Found {len(rows)} recent observations from all sessions:\n\n{by_level_with_ids(rows)}"


def search_memory(query, top_k=20):
    rows = by_similarity(query, live())[:min(top_k, 40)]
    if not rows:
        return f"No observations found for query '{query}'"
    return f"Found {len(rows)} observations for query '{query}':\n\n{by_level_with_ids(rows)}"


def search_messages(query, limit=10):
    vector = embed([query])[0]
    matches = sorted(MESSAGES, key=lambda m: cosine_distance(vector, message_vector(m)))[:min(limit, 20)]
    if not matches:
        return f"No messages found for query '{query}'"
    return message_snippets(matches, f"for query '{query}'")


def grounded(observations, level, minimum):
    """_filter_ungrounded_source_ids: keep only cited ids that exist; reject rows left with too few."""
    kept, failures = [], []
    for o in observations:
        real = [i.removeprefix("id:").strip() for i in o.get("source_ids", [])]
        real = [i for i in real if i in STORE]
        if len(real) < minimum:
            failures.append(f"'{o.get('content', '')[:50]}': {len(o.get('source_ids', [])) - len(real)} of "
                            f"{len(o.get('source_ids', []))} source_ids do not resolve to existing observations")
            continue
        kept.append({**o, "source_ids": real})
    return kept, failures


def create(level, observations, step):
    # Validation: a derived row needs at least one source id (Honcho's ObservationInput)
    failures = [f"'{o.get('content', '')[:50]}': Validation failed: {level} observations require "
                "'source_ids' field" for o in observations if not o.get("source_ids")]
    observations = [o for o in observations if o.get("source_ids")]
    kept, ungrounded = grounded(observations, level, minimum=2 if level == "contradiction" else 1)
    failures += ungrounded
    # Every row of one call is dated to the latest source cited anywhere in that call.
    cited = [STORE[i] for o in kept for i in o["source_ids"]]
    said_at = max((s.said_at for s in cited), default=TODAY)
    rows = []
    for o in kept:
        rows.append(Conclusion(
            "", level, o["content"].strip(),
            said_at=said_at,
            source_ids=o["source_ids"],
            premises=o.get("premises", []) if level == "deductive" else [],
            sources=o.get("sources", []) if level == "inductive" else [],
            pattern_type=o.get("pattern_type", "") if level == "inductive" else "",
            confidence=(o.get("confidence") or "medium") if level == "inductive" else ""))
    before = len(STORE)
    save(rows, step)
    made = len(STORE) - before
    counts = {lv: sum(1 for c in list(STORE.values())[before:] if c.level == lv) for lv in LEVELS}
    reply = (f"Created {made} observations for {PEER} by {PEER} ({counts['explicit']} explicit, "
             f"{counts['deductive']} deductive, {counts['inductive']} inductive, "
             f"{counts['contradiction']} contradiction)")
    if failures:
        reply += f"\nFailed {len(failures)}: " + "; ".join(failures)
    return reply


def delete_observations(observation_ids, step):
    deleted = 0
    for oid in observation_ids:
        oid = oid.removeprefix("id:").strip()
        if oid in STORE and not STORE[oid].deleted:
            STORE[oid].deleted = f"deleted by {step}"
            deleted += 1
    return f"Deleted {deleted} observations"


ALLOWED = ("IDENTITY: ", "ATTRIBUTE: ", "RELATIONSHIP: ", "INSTRUCTION: ")


def update_peer_card(content):
    global PEER_CARD
    card, seen, rejected = [], set(), 0
    for line in content:
        line = line.strip()
        if not line.startswith(ALLOWED) or len(line) > 200:
            rejected += 1
            continue
        if " ".join(line.lower().split()) not in seen:
            seen.add(" ".join(line.lower().split()))
            card.append(line)
    PEER_CARD = card[:40]
    return f"Updated peer card for {PEER} by {PEER} with {len(PEER_CARD)} entries." + (
        f" Rejected {rejected} entries without an allowed prefix." if rejected else "")


def dream_tools(step):
    return {
        "get_recent_observations": get_recent_observations,
        "search_memory": search_memory,
        "search_messages": search_messages,
        "create_observations_deductive": lambda observations: create("deductive", observations, step),
        "create_observations_inductive": lambda observations: create("inductive", observations, step),
        "delete_observations": lambda observation_ids: delete_observations(observation_ids, step),
        "update_peer_card": update_peer_card,
    }

The agent loop

One loop serves every agent in this notebook, as one loop serves every agent in Honcho (src/llm/tool_loop.py): call the model with the tools; run the tools it asks for; give it the results; repeat until it answers in text, or until the round limit, when Honcho asks once more for a final answer without tools.

[12]
Code · 39 lines
ROUNDS = []
SYNTHESIS = ("You have reached the maximum number of tool calls. Based on all the information you have "
             "gathered, provide your final response now. Do not attempt to call any more tools.")


def run_agent(step, system, user, tools, handlers, max_rounds):
    """Honcho's tool loop. Returns the agent's final text."""
    history = [{"role": "user", "parts": [{"text": user}]}]
    declarations = hs.declarations(tools)
    for round_ in range(1, max_rounds + 1):
        reply = generate(history, system=system, tools=declarations)
        log_call(step, reply)
        content = reply.candidates[0].content
        parts = (content.parts or []) if content else []
        calls = [p.function_call for p in parts if p.function_call]
        if not calls:
            text = "".join(p.text for p in parts if p.text).strip()
            ROUNDS.append({"step": step, "round": round_, "tool": "(answer)", "arguments": "", "result": text})
            return text
        history.append(content.model_dump(exclude_none=True))
        results = []
        for call in calls:
            arguments = dict(call.args or {})
            result = handlers[call.name](**arguments)
            ROUNDS.append({"step": step, "round": round_, "tool": call.name,
                           "arguments": json.dumps(arguments, ensure_ascii=False), "result": result})
            results.append({"function_response": {"name": call.name, "id": call.id,
                                                  "response": {"result": result}}})
        history.append({"role": "user", "parts": results})
    history.append({"role": "user", "parts": [{"text": SYNTHESIS}]})
    reply = generate(history, system=system)
    log_call(step, reply)
    return reply.text.strip()


def show_rounds(step, width=600):
    rows = [{**r, "result": r["result"] if len(r["result"]) <= width else r["result"][:width] + " …"}
            for r in ROUNDS if r["step"] == step]
    return table(pd.DataFrame(rows)[["round", "tool", "arguments", "result"]]).set_caption(step)

The deduction agent's prompts

The system prompt, in full. Its last section, on the peer card, is long; it is printed once here and then left out.

[13]
Code · 1 line
print(hs.deduction_system_prompt())
You are a deductive reasoning agent analyzing observations about the target observee.

## YOUR JOB

Create deductive observations by finding logical implications in what's already known. Think like a detective connecting evidence.

## PHASE 1: DISCOVERY

Explore what's actually in memory. Use these tools freely:
- `get_recent_observations` - See what's been learned recently
- `search_memory` - Search for specific topics
- `search_messages` - See actual conversation content

Spend a few tool calls understanding the landscape before creating anything.

## PHASE 2: ACTION

Once you understand what's there, create observations and clean up:

### Knowledge Updates (HIGH PRIORITY)
When the same fact has different values at different times:
- "meeting Tuesday" [old] → "meeting moved to Thursday" [new]
- Create a deductive update observation
- DELETE the outdated observation immediately

### Logical Implications
Extract implicit information:
- "works as SWE at Google" → "has software engineering skills", "employed in tech"
- "has kids ages 5 and 8" → "is a parent", "has school-age children"

### Contradictions
When statements can't both be true (not just updates), flag them:
- "I love coffee" vs "I hate coffee" → contradiction observation


## PEER CARD (REQUIRED)

The peer card is the target observee's identity store: stable identity markers that distinguish this entity from others and persist across interactions. Behavior, tendencies, transient state, and episodic facts belong in observations, not on the peer card.

A peer can be anything with identity that changes over time — a human, an agent, a codebase, a team, an organization. Do not assume the target observee is human. Do not require any field; empty is the correct output when evidence is absent.

### Allowed entry kinds

Each entry must start with one of these four prefixes (exact case, followed by a space):

- `IDENTITY: ...` — canonical name, kind, aliases, IDs
  - `IDENTITY: Name: Alice`
  - `IDENTITY: Kind: Python monorepo`
  - `IDENTITY: Version: 4.2`
  - `IDENTITY: Aliases: alice@example.com`
- `ATTRIBUTE: ...` — stable durable property of the entity (including explicitly stated standing preferences)
  - `ATTRIBUTE: Location: NYC`
  - `ATTRIBUTE: Language: Python`
  - `ATTRIBUTE: Prefers tea`
  - `ATTRIBUTE: Charter: ship Honcho infrastructure`
- `RELATIONSHIP: ...` — durable link to another entity
  - `RELATIONSHIP: Spouse: Bob`
  - `RELATIONSHIP: Maintainer: vineeth`
  - `RELATIONSHIP: Members: vineeth, rajat`
- `INSTRUCTION: ...` — standing rule of engagement that the target observee has explicitly stated (do/don't for the observer). Only when explicit; never inferred from behavior.
  - `INSTRUCTION: Call me Vee`
  - `INSTRUCTION: Never push to main without review`

### Rules

1. **Stable.** If the value plausibly changes within six months absent a deliberate announcement, it does not belong on the card. Prefer leaving the card empty over filling it with volatile content.
2. **Subject is the target observee.** Every entry must be a fact about the target observee, not about another participant in the session. Never write facts about co-occurring peers into the card, no matter how frequently they appear in the messages.
3. **Evidence-grounded.** Only write what the target observee has explicitly stated, or what another participant has explicitly stated about the target observee with the target observee's assent. No "general knowledge" inferences (`"co-founder"` does not imply an age; mentioning a colleague does not imply a family relationship).
4. **Type-agnostic.** The target observee may not be human. Do not require name/age/location/family/occupation fields.
5. **No behavioral content.** TRAITs, behavioral tendencies, patterns, and inferred preferences belong in observations, not on the peer card. Do not write `TRAIT:` entries or behavioral `PREFERENCE:` entries — they will be rejected.
6. **No evidence bundles.** Each entry is one concise fact. No `e.g.` clauses, no parenthetical example lists, no semicolon-separated value dumps.

### Migrating an existing peer card

The CURRENT PEER CARD shown in the user message may contain entries from an older format that do not start with an allowed prefix (e.g. `Name: Alice`, `Lives in NYC`, `TRAIT: Analytical`, `PREFERENCE: Detailed explanations`). When you call `update_peer_card`, you are responsible for re-emitting the entries you want to keep — entries you omit are dropped, and entries without an allowed prefix are silently rejected.

For each legacy entry:

- If it is still a valid identity marker, re-emit it under the correct prefix and keep the original content where reasonable. Examples:
  - `Name: Alice` → `IDENTITY: Name: Alice`
  - `Lives in NYC` → `ATTRIBUTE: Location: NYC`
  - `Works at Google` → `ATTRIBUTE: Employer: Google`
  - `INSTRUCTION: Call me Vee` → keep as is (already correctly prefixed)
- Drop entries that violate the rules above: behavioral `TRAIT:` lines, inferred behavioral `PREFERENCE:` lines, one-off events, transient state, evidence bundles. Do not re-prefix them — they are not identity markers.

When in doubt about a specific legacy entry, prefer migrating it (so valid info isn't lost) over dropping it. Splitting one dense legacy entry into multiple correctly-prefixed entries is fine and encouraged (e.g. a semicolon-separated `Tech Stack:` dump can become several `ATTRIBUTE:` lines, one per durable tool/platform).

Call `update_peer_card` with the complete deduplicated list when there is a durable identity update to record, or when the existing card needs migration. Entries that do not start with one of the four allowed prefixes will be rejected. Keep concise (max 40 entries).

## CREATING OBSERVATIONS

Use `create_observations_deductive`.

```json
{
  "observations": [{
    "content": "The logical conclusion",
    "source_ids": ["id1", "id2"],
    "premises": ["premise 1 text", "premise 2 text"]
  }]
}
```

## RULES

1. Don't explain your reasoning - just call tools
2. Create observations based on what you ACTUALLY FIND, not what you expect
3. Always include source_ids linking to the observations you're synthesizing
4. Copy source_ids exactly from the [id:xxx] shown in observation results - `search_messages` results have no ID and cannot be cited; invented IDs are discarded
5. Empty or missing source_ids will be rejected
6. Delete outdated observations - don't leave duplicates
7. Quality over quantity - fewer good deductions beat many weak ones
8. When you are finished, do not output a summary of what you did - output only the token DONE

The user message has the peer's id, the current peer card if there is one, and the instruction where to start. There is no card yet:

[14]
Code · 1 line
print(hs.deduction_user_prompt(PEER, PEER_CARD))
Target observee:
Anton

The target observee is the peer identified above. When created observations need to name this subject, use the exact observee id above, not the phrase "the target observee".

Explore the observation space and create deductive observations.

Start with `get_recent_observations` to see what's been learned recently, then investigate whatever seems most promising.

Look for:
1. Knowledge updates (same fact, different values over time)
2. Logical implications that haven't been made explicit
3. Contradictions that need flagging

Go.

Dream 1, deduction

[15]
Code · 15 lines
def dream(label):
    deduction = run_agent(f"{label} deduction", hs.deduction_system_prompt(),
                          hs.deduction_user_prompt(PEER, PEER_CARD),
                          hs.tool_set("DEDUCTION_SPECIALIST_TOOLS"), dream_tools(f"{label} deduction"),
                          hs.max_iterations("DeductionSpecialist"))
    induction = run_agent(f"{label} induction", hs.induction_system_prompt(),
                          hs.induction_user_prompt(PEER),
                          hs.tool_set("INDUCTION_SPECIALIST_TOOLS"), dream_tools(f"{label} induction"),
                          hs.max_iterations("InductionSpecialist"))
    return deduction, induction


dream("dream 1")
print(cost_so_far())
show_rounds("dream 1 deduction")
10 model calls so far   23,421 tokens in / 603 out
dream 1 deduction
round tool arguments result
1 get_recent_observations {} Found 6 recent observations from all sessions: EXPLICIT: 1. [id:e6] [2026-03-14 12:02:00] Anton has a budget of approximately 40 euros per person for the dinner. 2. [id:e5] [2026-03-14 12:02:00] Anton enjoys paneer dishes. 3. [id:e4] [2026-03-14 12:02:00] Anton prefers Indian cuisine. 4. [id:e3] [2026-03-14 12:02:00] Anton has a severe, anaphylactic peanut allergy. 5. [id:e2] [2026-03-14 12:02:00] Anton has been strictly vegetarian since 2018. 6. [id:e1] [2026-03-14 12:02:00] Anton is planning a dinner for his sister's visit to Berlin during the week of March 16, 2026. DEDUCTIVE: INDUCTIV …
2 create_observations_deductive {"observations": [{"content": "Anton requires a restaurant that offers vegetarian-friendly, peanut-free Indian cuisine.", "source_ids": ["e4", "e3", "e2"], "premises": ["Anton prefers Indian cuisine.", "Anton has a severe, anaphylactic peanut allergy.", "Anton has been strictly vegetarian since 2018."]}, {"content": "Anton is a resident of or is currently located in Berlin.", "source_ids": ["e1"], "premises": ["Anton is planning a dinner for his sister's visit to Berlin during the week of March 16, 2026."]}]} Created 2 observations for Anton by Anton (0 explicit, 2 deductive, 0 inductive, 0 contradiction)
3 update_peer_card {"content": ["ATTRIBUTE: Location: Berlin", "ATTRIBUTE: Dietary Restriction: Vegetarian", "ATTRIBUTE: Allergy: Peanut (anaphylactic)", "ATTRIBUTE: Cuisine Preference: Indian"]} Updated peer card for Anton by Anton with 4 entries.
4 (answer) DONE

Dream 1, induction

The induction agent's system prompt, in full:

[16]
Code · 1 line
print(hs.induction_system_prompt())
You are an inductive reasoning agent identifying patterns about the target observee.

## YOUR JOB

Create inductive observations by finding patterns across multiple observations. Think like a psychologist identifying behavioral tendencies.

## PHASE 1: DISCOVERY

Explore broadly to find patterns. Use these tools:
- `get_recent_observations` - Recent learnings
- `search_memory` - Topic-specific search
- `search_messages` - Actual conversation content

Look at BOTH explicit observations AND deductive ones. Patterns often emerge from synthesizing across both levels.

## PHASE 2: ACTION

Create inductive observations when you see patterns:

### Behavioral Patterns
- "Tends to reschedule meetings when stressed"
- "Makes decisions after consulting with partner"
- "Projects follow: enthusiasm → doubt → completion"

### Preferences
- "Prefers morning meetings"
- "Likes detailed technical explanations"

### Personality Traits
- "Generally optimistic about outcomes"
- "Detail-oriented in planning"

### Temporal Patterns
- "Career goals have remained consistent"
- "Living situation changes frequently"

## CREATING OBSERVATIONS

Use `create_observations_inductive`.

```json
{{
  "observations": [{{
    "content": "The pattern or generalization",
    "source_ids": ["id1", "id2", "id3"],
    "sources": ["evidence 1", "evidence 2"],
    "pattern_type": "tendency", // preference|behavior|personality|tendency|correlation
    "confidence": "medium" // low (2 sources), medium (3-4), high (5+)
  }}]
}}
```

## RULES

1. Minimum 2 source observations required - patterns need evidence
2. Don't just restate a single fact as a pattern
3. Confidence based on evidence count: 2=low, 3-4=medium, 5+=high
4. Look for HOW things change over time, not just static facts
5. Include source_ids - always link back to evidence
6. Copy source_ids exactly from the [id:xxx] shown in observation results - `search_messages` results have no ID and cannot be cited; invented IDs are discarded
7. Empty or missing source_ids will be rejected
8. When you are finished, do not output a summary of what you did - output only the token DONE
[17]
Code · 1 line
show_rounds("dream 1 induction")
dream 1 induction
round tool arguments result
1 get_recent_observations {"limit": 20} Found 8 recent observations from all sessions: EXPLICIT: 1. [id:e6] [2026-03-14 12:02:00] Anton has a budget of approximately 40 euros per person for the dinner. 2. [id:e5] [2026-03-14 12:02:00] Anton enjoys paneer dishes. 3. [id:e4] [2026-03-14 12:02:00] Anton prefers Indian cuisine. 4. [id:e3] [2026-03-14 12:02:00] Anton has a severe, anaphylactic peanut allergy. 5. [id:e2] [2026-03-14 12:02:00] Anton has been strictly vegetarian since 2018. 6. [id:e1] [2026-03-14 12:02:00] Anton is planning a dinner for his sister's visit to Berlin during the week of March 16, 2026. DEDUCTIVE: 1. [id:d8 …
2 search_memory {"query": "Anton preferences habits personality"} Found 8 observations for query 'Anton preferences habits personality': EXPLICIT: 1. [id:e4] [2026-03-14 12:02:00] Anton prefers Indian cuisine. 2. [id:e5] [2026-03-14 12:02:00] Anton enjoys paneer dishes. 3. [id:e2] [2026-03-14 12:02:00] Anton has been strictly vegetarian since 2018. 4. [id:e3] [2026-03-14 12:02:00] Anton has a severe, anaphylactic peanut allergy. 5. [id:e6] [2026-03-14 12:02:00] Anton has a budget of approximately 40 euros per person for the dinner. 6. [id:e1] [2026-03-14 12:02:00] Anton is planning a dinner for his sister's visit to Berlin during the week of March 16, 2026 …
3 search_messages {"query": "Anton dinner plans sister Berlin"} Found 3 matching messages in 1 conversation snippets for query 'Anton dinner plans sister Berlin'. These are raw messages with no observation ID - do not cite them in source_ids; use their text in premises/sources instead: --- Snippet 1 (session: s1, 3 match(es)) --- 2026-03-14 12:00:00 Anton: I'm planning a dinner for my sister's visit to Berlin next week. Worth saying up front: I've been strictly vegetarian for eight years, and I have a severe peanut allergy — anaphylactic, not a preference. 2026-03-14 12:01:00 assistant: Understood — no meat, and peanuts are a hard exclusion. Any cuisine y …
4 create_observations_inductive {"observations": [{"source_ids": ["e2", "e3"], "confidence": "medium", "content": "Anton maintains strict dietary restrictions (vegetarianism and peanut allergy) that dictate his dining choices.", "sources": ["Anton has been strictly vegetarian since 2018.", "Anton has a severe, anaphylactic peanut allergy."], "pattern_type": "behavior"}, {"sources": ["Anton prefers Indian cuisine.", "Anton enjoys paneer dishes."], "source_ids": ["e4", "e5"], "content": "Anton prefers Indian cuisine, specifically paneer dishes, when dining out.", "pattern_type": "preference", "confidence": "medium"}]} Created 2 observations for Anton by Anton (0 explicit, 0 deductive, 2 inductive, 0 contradiction)
5 (answer) DONE
[18]
Code · 2 lines
display(show_store(caption="The store after dream 1"))
print("peer card:", json.dumps(PEER_CARD, indent=1, ensure_ascii=False))
The store after dream 1
id level said at content drawn from x derived deleted
e1 explicit 2026-03-14 12:02 Anton is planning a dinner for his sister's visit to Berlin during the week of March 16, 2026. — 1
e2 explicit 2026-03-14 12:02 Anton has been strictly vegetarian since 2018. — 1
e3 explicit 2026-03-14 12:02 Anton has a severe, anaphylactic peanut allergy. — 1
e4 explicit 2026-03-14 12:02 Anton prefers Indian cuisine. — 1
e5 explicit 2026-03-14 12:02 Anton enjoys paneer dishes. — 1
e6 explicit 2026-03-14 12:02 Anton has a budget of approximately 40 euros per person for the dinner. — 1
d7 deductive 2026-03-14 12:02 Anton requires a restaurant that offers vegetarian-friendly, peanut-free Indian cuisine. e4, e3, e2 1
d8 deductive 2026-03-14 12:02 Anton is a resident of or is currently located in Berlin. e1 1
i9 inductive 2026-03-14 12:02 Anton maintains strict dietary restrictions (vegetarianism and peanut allergy) that dictate his dining choices. e2, e3 1
i10 inductive 2026-03-14 12:02 Anton prefers Indian cuisine, specifically paneer dishes, when dining out. e4, e5 1
peer card: [
 "ATTRIBUTE: Location: Berlin",
 "ATTRIBUTE: Dietary Restriction: Vegetarian",
 "ATTRIBUTE: Allergy: Peanut (anaphylactic)",
 "ATTRIBUTE: Cuisine Preference: Indian"
]

What dream 1 wrote. The deduction agent read the six rows, wrote two deductive rows and a four-line peer card, and stopped. Its first deduction follows from its premises. Its second, "a resident of or is currently located in Berlin", is a guess from planning a dinner there, stored at the level that the prompt defines as "logical implications". The induction agent searched twice and wrote two patterns, each from two sources.

Every derived row cites its sources by id. The vegetarian fact e2 is now a source of a deduction (d7) and a pattern (i9), and it is on the peer card.

3. Session 2: the user changes a fact

The deriver runs on session 2 exactly as on session 1. It is given the new messages and nothing else: not the store, not session 1.

[19]
Code · 5 lines
s2_messages = add_messages("s2", SESSION_2)
s2_rows = derive("s2", s2_messages)
save(s2_rows, "s2")
print(cost_so_far())
show_store([c for c in STORE.values() if c.session == "s2"], caption="Stored from session 2")
11 model calls so far   24,382 tokens in / 846 out
Stored from session 2
id level said at content drawn from x derived deleted
e11 explicit 2026-07-20 12:06 Anton started eating fish around June 2026. — 1
e12 explicit 2026-07-20 12:06 Anton is pescatarian. — 1
e13 explicit 2026-07-20 12:06 Anton does not eat meat. — 1
e14 explicit 2026-07-20 12:06 Anton has a peanut allergy or dietary restriction. — 1
e15 explicit 2026-07-20 12:06 Anton moved to Kreuzberg in May 2026. — 1
e16 explicit 2026-07-20 12:06 Anton has a sister named Lena. — 1
e17 explicit 2026-07-20 12:06 Anton's sister Lena is returning in the autumn of 2026. — 1
e18 explicit 2026-07-20 12:06 Anton's sister Lena is bringing her partner Jonas in the autumn of 2026. — 1
e19 explicit 2026-07-20 12:06 Anton's sister Lena cannot eat shellfish. — 1
e20 explicit 2026-07-20 12:06 Anton's sister's partner Jonas is coeliac. — 1

Ten rows. The store now holds both diets as explicit rows: e2 from March and e12 from July, each true when it was said. Nothing at this step compares them. The peanut allergy is stored a second time (e14), because near duplicates are merged only within one session.

4. Dream 2: the update

The deduction agent now gets the peer card that dream 1 wrote:

[20]
Code · 1 line
print(hs.deduction_user_prompt(PEER, PEER_CARD))
Target observee:
Anton

The target observee is the peer identified above. When created observations need to name this subject, use the exact observee id above, not the phrase "the target observee".


## CURRENT PEER CARD

- ATTRIBUTE: Location: Berlin
- ATTRIBUTE: Dietary Restriction: Vegetarian
- ATTRIBUTE: Allergy: Peanut (anaphylactic)
- ATTRIBUTE: Cuisine Preference: Indian

Update this with `update_peer_card` only for stable identity markers. See the PEER CARD section in the system prompt for the allowed entry kinds and rules.
If you update it, send the full deduplicated list and remove stale entries.

Explore the observation space and create deductive observations.

Start with `get_recent_observations` to see what's been learned recently, then investigate whatever seems most promising.

Look for:
1. Knowledge updates (same fact, different values over time)
2. Logical implications that haven't been made explicit
3. Contradictions that need flagging

Go.
[21]
Code · 3 lines
dream("dream 2")
print(cost_so_far())
show_rounds("dream 2 deduction")
19 model calls so far   49,766 tokens in / 1,400 out
dream 2 deduction
round tool arguments result
1 get_recent_observations {"limit": 20} Found 20 recent observations from all sessions: EXPLICIT: 1. [id:e20] [2026-07-20 12:06:00] Anton's sister's partner Jonas is coeliac. 2. [id:e19] [2026-07-20 12:06:00] Anton's sister Lena cannot eat shellfish. 3. [id:e18] [2026-07-20 12:06:00] Anton's sister Lena is bringing her partner Jonas in the autumn of 2026. 4. [id:e17] [2026-07-20 12:06:00] Anton's sister Lena is returning in the autumn of 2026. 5. [id:e16] [2026-07-20 12:06:00] Anton has a sister named Lena. 6. [id:e15] [2026-07-20 12:06:00] Anton moved to Kreuzberg in May 2026. 7. [id:e14] [2026-07-20 12:06:00] Anton has a peanut …
2 create_observations_deductive {"observations": [{"source_ids": ["e2", "e12"], "premises": ["Anton has been strictly vegetarian since 2018.", "Anton is pescatarian."], "content": "Anton is pescatarian, which contradicts his previous status as a strict vegetarian."}, {"source_ids": ["e2", "e11", "e12"], "premises": ["Anton has been strictly vegetarian since 2018.", "Anton started eating fish around June 2026.", "Anton is pescatarian."], "content": "Anton's dietary status has changed from strictly vegetarian to pescatarian as of June 2026."}]} Created 2 observations for Anton by Anton (0 explicit, 2 deductive, 0 inductive, 0 contradiction)
3 delete_observations {"observation_ids": ["e2", "e13"]} Deleted 2 observations
4 update_peer_card {"content": ["IDENTITY: Name: Anton", "ATTRIBUTE: Location: Berlin", "ATTRIBUTE: Neighborhood: Kreuzberg", "ATTRIBUTE: Dietary Restriction: Pescatarian", "ATTRIBUTE: Allergy: Peanut (anaphylactic)", "ATTRIBUTE: Cuisine Preference: Indian"]} Updated peer card for Anton by Anton with 6 entries.
5 (answer) DONE
[22]
Code · 1 line
show_rounds("dream 2 induction")
dream 2 induction
round tool arguments result
1 get_recent_observations {"limit": 20} Found 20 recent observations from all sessions: EXPLICIT: 1. [id:e20] [2026-07-20 12:06:00] Anton's sister's partner Jonas is coeliac. 2. [id:e19] [2026-07-20 12:06:00] Anton's sister Lena cannot eat shellfish. 3. [id:e18] [2026-07-20 12:06:00] Anton's sister Lena is bringing her partner Jonas in the autumn of 2026. 4. [id:e17] [2026-07-20 12:06:00] Anton's sister Lena is returning in the autumn of 2026. 5. [id:e16] [2026-07-20 12:06:00] Anton has a sister named Lena. 6. [id:e15] [2026-07-20 12:06:00] Anton moved to Kreuzberg in May 2026. 7. [id:e14] [2026-07-20 12:06:00] Anton has a peanut …
2 create_observations_inductive {"observations": [{"sources": ["Anton's sister Lena is bringing her partner Jonas in the autumn of 2026.", "Anton's sister Lena cannot eat shellfish.", "Anton's sister's partner Jonas is coeliac."], "content": "Anton is highly attentive to the dietary needs of his guests, specifically when planning social gatherings.", "pattern_type": "behavior", "confidence": "medium", "source_ids": ["e18", "e19", "e20"]}, {"pattern_type": "tendency", "content": "Anton's dietary habits have evolved over time, shifting from strict vegetarianism to pescatarianism as of mid-2026.", "sources": ["Anton started eating fish around June 2026.", "Anton is pescatarian.", "Anton's dietary status has changed from strictly vegetarian to pescatarian as of June 2026."], "source_ids": ["e11", "e12", "d22"], "confidence": "medium"}]} Created 2 observations for Anton by Anton (0 explicit, 0 deductive, 2 inductive, 0 contradiction)
3 (answer) DONE
[23]
Code · 3 lines
display(show_store(caption="The store after dream 2"))
print("peer card:", json.dumps(PEER_CARD, indent=1, ensure_ascii=False))
print("\nwhat saving merged or dropped:", SAVE_LOG or "nothing")
The store after dream 2
id level said at content drawn from x derived deleted
e1 explicit 2026-03-14 12:02 Anton is planning a dinner for his sister's visit to Berlin during the week of March 16, 2026. — 1
e2 explicit 2026-03-14 12:02 Anton has been strictly vegetarian since 2018. — 1 deleted by dream 2 deduction
e3 explicit 2026-03-14 12:02 Anton has a severe, anaphylactic peanut allergy. — 1
e4 explicit 2026-03-14 12:02 Anton prefers Indian cuisine. — 1
e5 explicit 2026-03-14 12:02 Anton enjoys paneer dishes. — 1
e6 explicit 2026-03-14 12:02 Anton has a budget of approximately 40 euros per person for the dinner. — 1
e11 explicit 2026-07-20 12:06 Anton started eating fish around June 2026. — 1
e12 explicit 2026-07-20 12:06 Anton is pescatarian. — 1
e13 explicit 2026-07-20 12:06 Anton does not eat meat. — 1 deleted by dream 2 deduction
e14 explicit 2026-07-20 12:06 Anton has a peanut allergy or dietary restriction. — 1
e15 explicit 2026-07-20 12:06 Anton moved to Kreuzberg in May 2026. — 1
e16 explicit 2026-07-20 12:06 Anton has a sister named Lena. — 1
e17 explicit 2026-07-20 12:06 Anton's sister Lena is returning in the autumn of 2026. — 1
e18 explicit 2026-07-20 12:06 Anton's sister Lena is bringing her partner Jonas in the autumn of 2026. — 1
e19 explicit 2026-07-20 12:06 Anton's sister Lena cannot eat shellfish. — 1
e20 explicit 2026-07-20 12:06 Anton's sister's partner Jonas is coeliac. — 1
d7 deductive 2026-03-14 12:02 Anton requires a restaurant that offers vegetarian-friendly, peanut-free Indian cuisine. e4, e3, e2 1
d8 deductive 2026-03-14 12:02 Anton is a resident of or is currently located in Berlin. e1 1
d21 deductive 2026-07-20 12:06 Anton is pescatarian, which contradicts his previous status as a strict vegetarian. e2, e12 1
d22 deductive 2026-07-20 12:06 Anton's dietary status has changed from strictly vegetarian to pescatarian as of June 2026. e2, e11, e12 1
i9 inductive 2026-03-14 12:02 Anton maintains strict dietary restrictions (vegetarianism and peanut allergy) that dictate his dining choices. e2, e3 1
i10 inductive 2026-03-14 12:02 Anton prefers Indian cuisine, specifically paneer dishes, when dining out. e4, e5 1
i23 inductive 2026-07-20 12:06 Anton is highly attentive to the dietary needs of his guests, specifically when planning social gatherings. e18, e19, e20 1
i24 inductive 2026-07-20 12:06 Anton's dietary habits have evolved over time, shifting from strict vegetarianism to pescatarianism as of mid-2026. e11, e12, d22 1
peer card: [
 "IDENTITY: Name: Anton",
 "ATTRIBUTE: Location: Berlin",
 "ATTRIBUTE: Neighborhood: Kreuzberg",
 "ATTRIBUTE: Dietary Restriction: Pescatarian",
 "ATTRIBUTE: Allergy: Peanut (anaphylactic)",
 "ATTRIBUTE: Cuisine Preference: Indian"
]

what saving merged or dropped: nothing

What dream 2 did. In five rounds the deduction agent:

  1. read the twenty most recent rows;
  2. wrote two deductions about the diet: an update (d22, "has changed from strictly vegetarian to pescatarian as of June 2026") and a second row that calls the change a contradiction (d21), stored as a deduction, because that is the only level its tool writes;
  3. deleted two rows: the vegetarian fact e2, and e13, "Anton does not eat meat", which is still true (the user said "Still no meat" in July);
  4. rewrote the peer card: "Vegetarian" became "Pescatarian", and Kreuzberg was added.

The induction agent added two patterns, one of them about the change.

The three runs of a real v3.3.0 server on this conversation (in the blog post's repository) did the same kind of thing: each wrote an update, and the deletes differed from run to run. Two of the three runs deleted the still-true "does not eat meat".

5. What rested on the deleted rows

A delete in Honcho removes the row it names. It does not look at the rows that cite it. Because every derived row lists its sources, that question has an exact answer, and it takes a few lines to compute.

[24]
Code · 17 lines
def rests_on(deleted_ids):
    """Every live conclusion that cites a deleted row, directly or through other conclusions."""
    found, frontier = {}, list(deleted_ids)
    while frontier:
        oid = frontier.pop()
        for c in STORE.values():
            if oid in c.source_ids and c.id not in found:
                found[c.id] = c
                frontier.append(c.id)
    return [c for c in found.values() if not c.deleted]


deleted = [c.id for c in STORE.values() if c.deleted]
print("deleted:", deleted)
for c in rests_on(deleted):
    gone = [i for i in c.source_ids if STORE[i].deleted]
    print(f"\n[{c.id}] {c.level}: {c.content}\n      cites {c.source_ids}; deleted among them: {gone}")
deleted: ['e2', 'e13']

[d7] deductive: Anton requires a restaurant that offers vegetarian-friendly, peanut-free Indian cuisine.
      cites ['e4', 'e3', 'e2']; deleted among them: ['e2']

[i9] inductive: Anton maintains strict dietary restrictions (vegetarianism and peanut allergy) that dictate his dining choices.
      cites ['e2', 'e3']; deleted among them: ['e2']

[d21] deductive: Anton is pescatarian, which contradicts his previous status as a strict vegetarian.
      cites ['e2', 'e12']; deleted among them: ['e2']

[d22] deductive: Anton's dietary status has changed from strictly vegetarian to pescatarian as of June 2026.
      cites ['e2', 'e11', 'e12']; deleted among them: ['e2']

[i24] inductive: Anton's dietary habits have evolved over time, shifting from strict vegetarianism to pescatarianism as of mid-2026.
      cites ['e11', 'e12', 'd22']; deleted among them: []

Honcho has this walk in one place. When a session is removed from a scope (a named group of sessions that limits what a read may see), Honcho deletes that session's explicit rows in the scope and then every derived row whose sources include anything deleted, repeating until nothing more goes (src/deriver/scope_backfill.py). The rule fails closed: one deleted source is enough to delete a conclusion, even if its other sources still hold.

The dreamer's deletes do not use it. After dream 2, two conclusions that rest on the deleted vegetarian fact are still live: d7, "requires a restaurant that offers vegetarian-friendly, peanut-free Indian cuisine", and i9, "maintains strict dietary restrictions (vegetarianism and peanut allergy)". Nothing in either row marks it as stale.

The walk also lists d21 and d22, the two rows about the change, which cite e2 on purpose, and i24, a pattern built on d22.

Honcho's scope rule would delete all five, the update included, because it fails closed. A rule that keeps a conclusion while any of its sources still holds would keep all five, the stale ones included, because each of them also cites a fact that is still true. One rule is too strict and the other too lenient. What the links give is the list itself, computed by code, without asking a model; deciding what to do with each row on it is a further step.

6. What the code checks

Honcho's prompts ask for several rules about premises. Its code enforces two.

Three rules are only requested, not checked:

And one rule is not in Honcho at all: that a conclusion may only be drawn from conclusions of a lower level, so that a pattern cannot rest on another pattern and a guess can never become the basis of something stated as certain. It would take a few lines:

[25]
Code · 15 lines
RANK = {"explicit": 0, "deductive": 1, "inductive": 2, "contradiction": 1}


def level_violations():
    return [(c.id, s, f"{STORE[s].level} source for a {c.level} conclusion")
            for c in STORE.values() for s in c.source_ids if RANK[STORE[s].level] >= RANK[c.level]]


print("confidence against the count rule:")
for c in STORE.values():
    if c.level == "inductive":
        n = len(c.source_ids)
        rule = "low" if n <= 2 else "medium" if n <= 4 else "high"
        print(f"  [{c.id}] {n} sources: model wrote {c.confidence!r}, the rule says {rule!r}")
print("\nlevel violations:", level_violations() or "none")
confidence against the count rule:
  [i9] 2 sources: model wrote 'medium', the rule says 'low'
  [i10] 2 sources: model wrote 'medium', the rule says 'low'
  [i23] 3 sources: model wrote 'medium', the rule says 'medium'
  [i24] 3 sources: model wrote 'medium', the rule says 'medium'

level violations: none

In this run the model broke the confidence rule for both two-source patterns (it wrote "medium" where the rule says "low"), and no row broke the level order. In the first real-server run, a dream-2 pattern cited an earlier pattern, which this check would have refused.

7. Reading it back

Honcho has two read paths, and the experiment measured both on the same store.

The representation: conclusions, no model call

peer.representation(search_query=...) returns at most 100 conclusions: a third of them (33) chosen by similarity to the query, and the rest filled with the newest. Within each level they are sorted by when they were said.

[26]
Code · 10 lines
def representation(query, max_conclusions=100):
    chosen = by_similarity(query, live())[:max_conclusions // 3]
    newest = [c for c in sorted(live(), key=lambda c: -c.order) if c not in chosen]
    rows = chosen + newest[:max_conclusions - len(chosen)]
    rows = sorted(rows, key=lambda c: (LEVELS.index(c.level), c.said_at))
    return as_markdown(rows)


REPRESENTATION = representation(QUESTION)
print(REPRESENTATION)
## Explicit Observations

[2026-03-14 12:02:00] Anton is planning a dinner for his sister's visit to Berlin during the week of March 16, 2026.
[2026-03-14 12:02:00] Anton has a budget of approximately 40 euros per person for the dinner.
[2026-03-14 12:02:00] Anton prefers Indian cuisine.
[2026-03-14 12:02:00] Anton enjoys paneer dishes.
[2026-03-14 12:02:00] Anton has a severe, anaphylactic peanut allergy.
[2026-07-20 12:06:00] Anton's sister's partner Jonas is coeliac.
[2026-07-20 12:06:00] Anton's sister Lena cannot eat shellfish.
[2026-07-20 12:06:00] Anton's sister Lena is bringing her partner Jonas in the autumn of 2026.
[2026-07-20 12:06:00] Anton has a peanut allergy or dietary restriction.
[2026-07-20 12:06:00] Anton is pescatarian.
[2026-07-20 12:06:00] Anton has a sister named Lena.
[2026-07-20 12:06:00] Anton's sister Lena is returning in the autumn of 2026.
[2026-07-20 12:06:00] Anton started eating fish around June 2026.
[2026-07-20 12:06:00] Anton moved to Kreuzberg in May 2026.

## Deductive Observations

[2026-03-14 12:02:00] Anton requires a restaurant that offers vegetarian-friendly, peanut-free Indian cuisine.
   Premises:
   - Anton prefers Indian cuisine.
   - Anton has a severe, anaphylactic peanut allergy.
   - Anton has been strictly vegetarian since 2018.

[2026-03-14 12:02:00] Anton is a resident of or is currently located in Berlin.
   Premises:
   - Anton is planning a dinner for his sister's visit to Berlin during the week of March 16, 2026.

[2026-07-20 12:06:00] Anton's dietary status has changed from strictly vegetarian to pescatarian as of June 2026.
   Premises:
   - Anton has been strictly vegetarian since 2018.
   - Anton started eating fish around June 2026.
   - Anton is pescatarian.

[2026-07-20 12:06:00] Anton is pescatarian, which contradicts his previous status as a strict vegetarian.
   Premises:
   - Anton has been strictly vegetarian since 2018.
   - Anton is pescatarian.


## Inductive Observations

 **Pattern** [medium]: Anton maintains strict dietary restrictions (vegetarianism and peanut allergy) that dictate his dining choices.
   **Type**: behavior
   **Sources**:
   - Anton has been strictly vegetarian since 2018.
   - Anton has a severe, anaphylactic peanut allergy.

 **Pattern** [medium]: Anton prefers Indian cuisine, specifically paneer dishes, when dining out.
   **Type**: preference
   **Sources**:
   - Anton prefers Indian cuisine.
   - Anton enjoys paneer dishes.

 **Pattern** [medium]: Anton is highly attentive to the dietary needs of his guests, specifically when planning social gatherings.
   **Type**: behavior
   **Sources**:
   - Anton's sister Lena is bringing her partner Jonas in the autumn of 2026.
   - Anton's sister Lena cannot eat shellfish.
   - Anton's sister's partner Jonas is coeliac.

 **Pattern** [medium]: Anton's dietary habits have evolved over time, shifting from strict vegetarianism to pescatarianism as of mid-2026.
   **Type**: tendency
   **Sources**:
   - Anton started eating fish around June 2026.
   - Anton is pescatarian.
   - Anton's dietary status has changed from strictly vegetarian to pescatarian as of June 2026.


The dialectic: an agent that answers

peer.chat(query) runs Honcho's dialectic agent at its default reasoning level, low: up to 5 rounds of tools, and the model decides whether to use them. Before the first call it searches the store itself and puts what it found under the query: the 25 explicit conclusions closest to the query and the 25 closest derived ones. Its system prompt is long; the parts that matter here are the two sections on contradictory and updated information.

[27]
Code · 3 lines
DIALECTIC_TOOLS = hs.tool_set("DIALECTIC_TOOLS")
system = hs.dialectic_system_prompt(PEER, PEER_CARD, {t["name"] for t in DIALECTIC_TOOLS})
print(system)

You are Honcho's dialectic: a recall agent that answers questions from memory about one peer, or about one peer's understanding of another.

Honcho is a memory system. Applications record conversations; Honcho derives conclusions about the people and agents in them. You are the query interface for one observer/observed pair. You do not speak as a participant. You search memory and synthesize a grounded answer.

A **peer** is any participant, human or AI. A **session** is a conversation they take part in. A **message** is a raw turn. A **conclusion** (tools may say observation) is a derived or stored fact about a peer, kept in this pair. A **peer card** is a short constructed bio for the pair, synthesized from the same conclusions — a convenience summary, not a separate source of truth.

Always give the asker the answer *they expect* based on the message history -- the goal is to help recall and *reason through* insights that the memory system has already gathered. Search wisely.


You are answering queries about 'Anton'.


Known biographical information about Anton:
<peer_card>
IDENTITY: Name: Anton
ATTRIBUTE: Location: Berlin
ATTRIBUTE: Neighborhood: Kreuzberg
ATTRIBUTE: Dietary Restriction: Pescatarian
ATTRIBUTE: Allergy: Peanut (anaphylactic)
ATTRIBUTE: Cuisine Preference: Indian
</peer_card>



Peer cards are **constructed summaries** - they are synthesized from the same observations stored in memory. This means:
- Information in a peer card originates from observations you can also find via `search_memory`
- The peer card is a convenience summary, not a separate source of truth

## TOOLS

Only the tools listed here are available on this query. If a later step names a tool you do not have, skip that step and use what you do have.

**Memory**
- `search_memory`: Semantic search over conclusions about this pair.
- `get_reasoning_chain`: Premises and downstream conclusions for a specific conclusion.
- `get_observation_context`: Messages around a specific conclusion.

**Conversation**
- `search_messages`: Semantic search over messages in this query's scope.
- `grep_messages`: Exact text search. Use for names, dates, keywords.
- `get_messages_by_date_range`: Messages in a time window.
- `search_messages_temporal`: Semantic search with a date filter.

## WORKFLOW

1. **Analyze the query**: What specific information does the query demand?

2. **Check for user preferences** (do this FIRST for any question that asks for advice, recommendations, or opinions):
   - Search for "prefer", "like", "want", "always", "never" to find user preferences
   - Search for "instruction", "style", "approach" to find communication preferences
   - Apply any relevant preferences to how you structure your response

3. **Strategic information gathering**:
   - Use `search_memory` to find relevant observations, then `search_messages` if memories are not sufficient
   - For questions about dates, deadlines, or schedules: also search for update language ("changed", "rescheduled", "updated", "now", "moved")
   - For factual questions: cross-reference what you find - search for related terms to verify accuracy
   - Watch for CONTRADICTORY information as you search (see below)
   - If you find an explicit answer to the query, stop calling tools and create your response

4. **For ENUMERATION/AGGREGATION questions** (questions asking for totals, counts, "how many", "all of", or listing items):
   - These questions require finding ALL matching items, not just some
   - **START WITH GREP**: Use `grep_messages` first for exhaustive matching:
     - grep for the UNIT being counted: "hours", "minutes", "dollars", "$", "%", "times"
     - grep for the CATEGORY noun: the thing being enumerated
     - grep catches exact mentions that semantic search might miss
   - **THEN USE SEMANTIC SEARCH**: Do at least 3 `search_memory` or `search_messages` calls with different phrasings
   - Use synonyms, related terms, specific instances
   - Use top_k=15 or higher to get more results per search
   - **SEARCH FOR SPECIFIC ITEMS**: After finding some items, search for each by name to find additional mentions
   - Cross-reference results to avoid double-counting the same item mentioned with different wording
   - A single search is NEVER sufficient for enumeration questions

   **MANDATORY VERIFICATION STEP**: After you think you have all items:
   1. List every item you found with its value
   2. Check if any NEW items appear that you missed
   3. Only then finalize your count

   **MANDATORY DEDUPLICATION STEP**: Before stating your final count:
   1. Create a deduplication table listing each candidate item with:
      - Item name/description
      - Distinguishing feature (specific date, location, or unique detail)
      - Source date (when was this mentioned?)
   2. Compare items and ask: "Are any of these the SAME thing mentioned differently?"
      - Same item in different recipes/contexts = ONE item
      - Same event mentioned on multiple dates = ONE event
      - Same person/place with slightly different wording = ONE entity
   3. Mark duplicates and remove them from your count
   4. State your final count based on UNIQUE items only

   When stating a count, NUMBER EACH ITEM (1, 2, 3...) and verify the final number matches how many you listed

5. **For SUMMARIZATION questions** (questions asking to summarize, recap, or describe patterns over time):
   - Do MULTIPLE searches with different query terms to ensure comprehensive coverage
   - Search for key entities mentioned (names, places, topics)
   - Search for time-related terms ("first", "then", "later", "changed", "decided")
   - Don't stop after finding a few relevant results - summarization requires thoroughness

6. **Ground your answer using reasoning chains** (for deductive/inductive observations):
   - When you find a deductive or inductive observation that answers the question, use `get_reasoning_chain` to verify its basis
   - This shows you the premises (explicit facts) that support the conclusion
   - If the premises are solid, cite them in your answer for confidence
   - If the premises seem weak or outdated, note that uncertainty

7. **Synthesize your response**:
   - Directly answer the application's question
   - Ground your response in the specific information you gathered
   - Quote exact values (dates, numbers, names) from what you found - don't paraphrase numbers
   - Apply user preferences to your response style if relevant
   - **For enumeration questions**: Before answering, ask yourself "Could there be more items I haven't found?" If you haven't done multiple grep searches AND a semantic search, keep searching

## CRITICAL: HANDLING CONTRADICTORY INFORMATION

As you search, actively watch for contradictions - cases where the user has made conflicting statements:
- "I have never done X" vs evidence they did X
- Different values for the same fact (different dates, numbers, names)
- Changed decisions or preferences stated at different times

**If you find contradictory information:**
1. DO NOT pick one version and present it as the definitive answer
2. Present BOTH pieces of conflicting information explicitly
3. State clearly that you found contradictory information
4. Ask the user which statement is correct

Example response format: "I notice you've mentioned contradictory information about this. You said [X], but you also mentioned [Y]. Which statement is correct?"

## CRITICAL: HANDLING UPDATED INFORMATION

Information changes over time. When you find multiple values for the same fact (e.g., different dates for a deadline):
1. **ALWAYS search for updates**: When you find a date/value, do an additional search for "changed", "updated", "rescheduled", "moved", "now" + the topic
2. Look for language indicating updates: "changed to", "rescheduled to", "updated to", "now", "moved to"
3. The MORE RECENT statement supersedes the older one
4. Return the UPDATED value, not the original
5. **Use `get_reasoning_chain`**: If you find a deductive observation about an update (e.g., "X was updated from A to B"), use `get_reasoning_chain` to verify the premises - it will show you both the old and new explicit observations with their timestamps.

Example: If you find "deadline is April 25", search for "deadline changed" or "deadline rescheduled". If you find "I rescheduled to April 22", return April 22.

**For knowledge update questions specifically:**
- Search for deductive observations containing "updated", "changed", "supersedes"
- These observations link to both old and new values via `source_ids`
- Use `get_reasoning_chain` to see the full update history

## CRITICAL: NEVER FABRICATE INFORMATION OR GUESS -- WHEN UNSURE, ABSTAIN

When answering questions, always clearly distinguish between:
- **Context found**: You located related information (e.g., "there was a debate about X")
- **Specific answer found**: You found the exact information requested (e.g., "the arguments were A, B, C")

If you find context but NOT the specific answer:
1. DO NOT fabricate or guess details to fill gaps.
2. Report only what you DO know: e.g., "I found that you had a debate about X at [location] on [date]."
3. Explicitly state what you DON'T know: e.g., "However, the specific arguments made during that debate are not captured in our conversation history."
4. Never present fabricated information or fill gaps with plausible-sounding but invented details.

If after thorough searching you find NOTHING relevant:
1. Clearly state: "I don't have any information about [topic] in my memory."
2. DO NOT guess or make assumptions.
3. DO NOT say "I think...", "Probably...", or similar hedges when you lack evidence.
4. A confident "I don't know" is ALWAYS correct; giving a fabricated answer is ALWAYS wrong.

**The test before stating a detail:** Ask yourself, "Did I find this EXACT information in my search results, or am I inferring/inventing it?" If you're inventing it, OMIT IT.

### How to Abstain Properly

- When the user asks about a topic that was NEVER discussed, or your search finds no relevant information:
    - CORRECT: "I don't have any information about your favorite color in my memory."
    - CORRECT: "I searched for information about X but found nothing in our conversation history."
    - WRONG: "Based on your preferences, I think your favorite color might be blue." (never invent)
    - WRONG: Filling in plausible details based on general knowledge or assumptions.

**Remember:** A clear, direct "I don't know" or "I have no information about X" is always the RIGHT answer when the information truly does not exist in memory. Hallucinating, guessing, or making up plausible-sounding details is always the WRONG answer.

After gathering context, reason through the information you found *before* stating your final answer. For comparison questions, explicitly compare the values. Only after you've verified your reasoning should you state your conclusion. Do NOT be pedantic, rather, be helpful and try to give the answer that the asker would expect -- they're the one who knows the most about themselves. Try to 'read their mind' -- understand the information they're really after and share it with them! Be **as specific as possible** given the information you have.

Do not explain your tool usage - just provide the synthesized answer.

[28]
Code · 88 lines
def plain(c):
    """One conclusion as the dialectic's tools print it (Representation.__str__): no id."""
    if c.level == "explicit":
        return f"{stamp(c)} {c.content}"
    if c.level == "deductive":
        return f"{stamp(c)} {c.content}\n" + "\n".join(f"    - {p}" for p in c.premises)
    if c.level == "inductive":
        return f"{stamp(c)} [{c.confidence}] {c.content}" + "".join(f"\n    - {s}" for s in c.sources)
    return f"{stamp(c)} CONTRADICTION: {c.content}" + "".join(f"\n    - {s}" for s in c.sources)


def dialectic_search_memory(query, top_k=20):
    rows = by_similarity(query, live())[:min(top_k, 40)]
    if not rows:
        return f"No observations found for query '{query}'"
    parts = []
    for level in LEVELS:
        parts.append(f"{level.upper()}:\n")
        parts += [f"{i}. {plain(c)}" for i, c in enumerate([c for c in rows if c.level == level], 1)]
        parts.append("")
    return f"Found {len(rows)} observations for query '{query}':\n\n" + "\n".join(parts)


def grep_messages(text, limit=10, context_window=2):
    matches = [m for m in MESSAGES if text.lower() in m.content.lower()][:limit]
    if not matches:
        return f"No messages found containing '{text}'"
    parts = snippets(matches, context_window)
    return f"Found {len(matches)} messages containing '{text}' in {len(parts)} conversation snippets:\n\n" + \
        "\n\n".join(parts)


def get_observation_context(message_ids):
    wanted = {int(i) for i in message_ids}
    rows = [m for m in MESSAGES if any(abs(m.id - w) <= 1 and m.session == MESSAGES[w - 1].session
                                       for w in wanted if 0 < w <= len(MESSAGES))]
    if not rows:
        return f"No messages found for IDs {message_ids}"
    return f"Retrieved {len(rows)} messages with context:\n" + "\n".join(
        f"{m.time:%Y-%m-%d %H:%M:%S} {m.peer}: {m.content}" for m in rows)


def in_range(m, after_date, before_date):
    return ((not after_date or m.time > datetime.fromisoformat(after_date[:10]))
            and (not before_date or m.time < datetime.fromisoformat(before_date[:10])))


def get_messages_by_date_range(after_date=None, before_date=None, limit=20, order="desc"):
    rows = sorted([m for m in MESSAGES if in_range(m, after_date, before_date)], key=lambda m: m.time,
                  reverse=order == "desc")[:limit]
    if not rows:
        return "No messages found in that range"
    return f"Found {len(rows)} messages:\n\n" + "\n".join(
        f"{m.time:%Y-%m-%d %H:%M:%S} {m.peer}: {m.content}" for m in rows)


def search_messages_temporal(query, after_date=None, before_date=None, limit=10, context_window=2):
    vector = embed([query])[0]
    pool = [m for m in MESSAGES if in_range(m, after_date, before_date)]
    matches = sorted(pool, key=lambda m: cosine_distance(vector, message_vector(m)))[:limit]
    if not matches:
        return f"No messages found for query '{query}'"
    return message_snippets(matches, f"for query '{query}'", context_window)


def get_reasoning_chain(observation_id, direction="both"):
    c = STORE.get(observation_id.removeprefix("id:"))
    if c is None:
        return f"ERROR: Observation '{observation_id}' not found"
    out = [f"**Observation [id:{c.id}] ({c.level}):**\n{c.content}"]
    if direction in ("premises", "both") and c.source_ids:
        found = [STORE[i] for i in c.source_ids if not STORE[i].deleted]
        out.append(f"\n**Premises ({len(found)}):**\n" + "\n".join(f" - [id:{p.id}] ({p.level}): {p.content}"
                                                                for p in found))
    if direction in ("conclusions", "both"):
        children = [x for x in live() if c.id in x.source_ids]
        if children:
            out.append(f"\n**Derived Conclusions ({len(children)}):**\n" +
                       "\n".join(f" - [id:{x.id}] ({x.level}): {x.content}" for x in children))
    return "\n".join(out)


DIALECTIC_HANDLERS = {
    "search_memory": dialectic_search_memory, "search_messages": search_messages,
    "get_observation_context": get_observation_context, "grep_messages": grep_messages,
    "get_messages_by_date_range": get_messages_by_date_range,
    "search_messages_temporal": search_messages_temporal, "get_reasoning_chain": get_reasoning_chain,
}

The prefetch and the first user message:

[29]
Code · 8 lines
def prefetch(query, limit=25):
    explicit = by_similarity(query, live(["explicit"]))[:limit]
    derived = by_similarity(query, live(["deductive", "inductive", "contradiction"]))[:limit]
    return "\n".join(part for part in (as_markdown(explicit), as_markdown(derived, include_ids=True)) if part)


user = hs.dialectic_user_message(QUESTION, prefetch(QUESTION))
print(user)
Query: My sister and her partner are in town tonight. Book the three of us somewhere for dinner — you know what we can and can't eat.

## Relevant Observations (prefetched)
The following observations were found to be semantically relevant to your query. Use these as primary context. You may still use tools to find additional information if needed.

## Explicit Observations

[2026-03-14 12:02:00] Anton is planning a dinner for his sister's visit to Berlin during the week of March 16, 2026.
[2026-07-20 12:06:00] Anton's sister's partner Jonas is coeliac.
[2026-07-20 12:06:00] Anton's sister Lena cannot eat shellfish.
[2026-07-20 12:06:00] Anton's sister Lena is bringing her partner Jonas in the autumn of 2026.
[2026-03-14 12:02:00] Anton has a budget of approximately 40 euros per person for the dinner.
[2026-07-20 12:06:00] Anton has a peanut allergy or dietary restriction.
[2026-03-14 12:02:00] Anton prefers Indian cuisine.
[2026-03-14 12:02:00] Anton enjoys paneer dishes.
[2026-07-20 12:06:00] Anton is pescatarian.
[2026-07-20 12:06:00] Anton has a sister named Lena.
[2026-03-14 12:02:00] Anton has a severe, anaphylactic peanut allergy.
[2026-07-20 12:06:00] Anton's sister Lena is returning in the autumn of 2026.
[2026-07-20 12:06:00] Anton started eating fish around June 2026.
[2026-07-20 12:06:00] Anton moved to Kreuzberg in May 2026.

## Deductive Observations

[id:d7] [2026-03-14 12:02:00] Anton requires a restaurant that offers vegetarian-friendly, peanut-free Indian cuisine.
   Premises:
   - Anton prefers Indian cuisine.
   - Anton has a severe, anaphylactic peanut allergy.
   - Anton has been strictly vegetarian since 2018.

[id:d22] [2026-07-20 12:06:00] Anton's dietary status has changed from strictly vegetarian to pescatarian as of June 2026.
   Premises:
   - Anton has been strictly vegetarian since 2018.
   - Anton started eating fish around June 2026.
   - Anton is pescatarian.

[id:d21] [2026-07-20 12:06:00] Anton is pescatarian, which contradicts his previous status as a strict vegetarian.
   Premises:
   - Anton has been strictly vegetarian since 2018.
   - Anton is pescatarian.

[id:d8] [2026-03-14 12:02:00] Anton is a resident of or is currently located in Berlin.
   Premises:
   - Anton is planning a dinner for his sister's visit to Berlin during the week of March 16, 2026.


## Inductive Observations

[id:i9]  **Pattern** [medium]: Anton maintains strict dietary restrictions (vegetarianism and peanut allergy) that dictate his dining choices.
   **Type**: behavior
   **Sources**:
   - Anton has been strictly vegetarian since 2018.
   - Anton has a severe, anaphylactic peanut allergy.

[id:i10]  **Pattern** [medium]: Anton prefers Indian cuisine, specifically paneer dishes, when dining out.
   **Type**: preference
   **Sources**:
   - Anton prefers Indian cuisine.
   - Anton enjoys paneer dishes.

[id:i23]  **Pattern** [medium]: Anton is highly attentive to the dietary needs of his guests, specifically when planning social gatherings.
   **Type**: behavior
   **Sources**:
   - Anton's sister Lena is bringing her partner Jonas in the autumn of 2026.
   - Anton's sister Lena cannot eat shellfish.
   - Anton's sister's partner Jonas is coeliac.

[id:i24]  **Pattern** [medium]: Anton's dietary habits have evolved over time, shifting from strict vegetarianism to pescatarianism as of mid-2026.
   **Type**: tendency
   **Sources**:
   - Anton started eating fish around June 2026.
   - Anton is pescatarian.
   - Anton's dietary status has changed from strictly vegetarian to pescatarian as of June 2026.


[30]
Code · 3 lines
CHAT = run_agent("chat (dialectic)", system, user, DIALECTIC_TOOLS, DIALECTIC_HANDLERS, max_rounds=5)
print(cost_so_far(), "\n")
print(CHAT)
20 model calls so far   54,752 tokens in / 1,690 out 

I cannot book a restaurant for you, but I can help you identify a suitable place based on the dietary requirements of your group.

To ensure everyone can eat safely, you need a restaurant that accommodates the following:

*   **Anton (You):** Pescatarian and a severe, anaphylactic peanut allergy.
*   **Lena (Sister):** No shellfish.
*   **Jonas (Partner):** Coeliac (requires gluten-free options).

Given your preference for Indian cuisine and your budget of approximately 40 euros per person, you should look for an Indian restaurant in or near Kreuzberg that is highly rated for its allergy awareness—specifically regarding **peanuts** (for your safety) and **gluten** (for Jonas).

**Important Considerations:**
*   **Cross-Contamination:** Because your peanut allergy is anaphylactic and Jonas is coeliac, please ensure you explicitly inform the restaurant of both conditions when you call to make a reservation.
*   **Menu:** While Indian cuisine is often vegetarian-friendly (which suits your pescatarian diet and Lena's shellfish restriction), many dishes contain wheat (gluten) or are prepared in kitchens with high risks of peanut cross-contamination.

I recommend calling a few highly-rated Indian restaurants in Kreuzberg, explaining these specific dietary needs, and asking if they can safely accommodate a party with a severe peanut allergy and a coeliac guest.

One model call, no tools. The prefetched conclusions held what the agent needed, and it answered from them. In the experiment, too, the dialectic made a median of one call per question.

The reply is right about the diet ("Pescatarian"), the three constraints and the budget. It read the stale rows too: d7 and i9 were in the prefetch.

The same answering call over each read path

In the experiment, whatever a read path returned went into one shared answering prompt. Here it is the booking assistant of the other notebooks, given first the dialectic's reply and then the representation.

[31]
Code · 12 lines
def answer(context, label):
    reply = generate(f"What you remember about this user:\n{context}\n\nTheir request: {QUESTION}",
                     system=f"You are a booking assistant for {PEER}. Today is {TODAY:%d %B %Y}. "
                            "Be brief and concrete.")
    log_call(f"answer ({label})", reply)
    return reply.text.strip()


print("1. FROM THE DIALECTIC'S REPLY\n")
print(answer(CHAT, "dialectic"))
print("\n2. FROM THE REPRESENTATION\n")
print(answer(REPRESENTATION, "representation"))
1. FROM THE DIALECTIC'S REPLY

I cannot make the booking for you, but based on your requirements, I recommend **Chutnify** in Kreuzberg. They specialize in South Indian cuisine (Dosa/Idli), which is naturally gluten-free and often peanut-free.

**Action plan:**
1. **Call them now:** +49 30 69507377.
2. **State clearly:** "I have a party of three for tonight. We have a severe, anaphylactic peanut allergy and a coeliac guest. Can you safely accommodate us?"
3. **Confirm:** If they cannot guarantee safety regarding cross-contamination, do not book. 

Would you like me to look up another option if they are fully booked?

2. FROM THE REPRESENTATION

I am looking for a restaurant in Berlin for tonight for three people. I will ensure the venue is peanut-free (anaphylactic), gluten-free friendly (for Jonas), and shellfish-free (for Lena), while accommodating your pescatarian diet.

I will prioritize Indian cuisine as per your preference. Shall I proceed with a reservation for 20:00?

The answer from the representation keeps all four constraints: pescatarian, no peanuts, no shellfish for Lena, gluten-free for Jonas. The answer from the dialectic's reply keeps two, the peanut allergy and the coeliac guest, though the reply it was given had all four; and it adds a restaurant and a phone number that are in neither read path. The dialectic path puts a second model between the memory and the answer, and each of the two can drop something.

8. What it costs

[32]
Code · 5 lines
ledger = pd.DataFrame(CALLS).groupby("step", sort=False).agg(
    calls=("step", "size"), **{"tokens in": ("tokens in", "sum"), "tokens out": ("tokens out", "sum")}
).reset_index()
ledger.loc[len(ledger)] = ["TOTAL", ledger["calls"].sum(), ledger["tokens in"].sum(), ledger["tokens out"].sum()]
table(ledger)
step calls tokens in tokens out
deriver s1 1 769 161
dream 1 deduction 4 12,234 221
dream 1 induction 5 10,418 221
deriver s2 1 961 243
dream 2 deduction 5 19,014 285
dream 2 induction 3 6,370 269
chat (dialectic) 1 4,986 290
answer (dialectic) 1 359 155
answer (representation) 1 1,161 77
TOTAL 22 56,272 1,922

Twenty model calls for Honcho's own work: two deriver calls, seventeen rounds of the dream agents and one dialectic call. With the two answering calls, 22 calls read about 56,000 tokens. The real server took 18 to 20 calls and 46,000 to 50,000 tokens on the same conversation.

Almost all of it is the dream. Each round sends the agent's instructions and tool descriptions again (on the real server, the first deduction call read 2,460 tokens before it had seen a single conclusion), plus everything the agent has read so far, so the later rounds of one agent read the most. What does not grow is the store each agent sees: ten or twenty rows per tool call, however large the profile is. The cost of a dream is set by its rounds, not by the size of the store.

9. Beyond Honcho: abduction

Honcho's documentation lists a fourth kind of reasoning, abduction: "inferring the simplest explanations for observed behavior". Its code has no level and no agent for it. This section implements it, with a prompt of this notebook's own, to see what such a level would write about a person. It is the only prompt in this notebook that is not Honcho's.

[33]
Code · 26 lines
ABDUCTIVE_PROMPT = """\
You are the ABDUCTIVE tier of a memory system.

LEVEL DEFINITION — ABDUCTIVE: the most plausible EXPLANATION for the observed \
behaviour. Not a summary and not a generalisation — an answer to "why is this \
person like this", which could be wrong even if every premise is true.

You may reason from the observations below. Cite ids.

RULES
- Prefer the simplest explanation that covers the most observations.
- State it as a hypothesis, not a finding.
- Give each one a "check": the single thing an assistant could observe next that
  would most cheaply confirm or kill it.

OBSERVATIONS
{observations}

Return JSON:
{{"hypotheses": [{{"content": "...", "premise_ids": ["e1","i1"], "check": "..."}}]}}
"""

reply = generate(ABDUCTIVE_PROMPT.format(observations=by_level_with_ids(live())), as_json=True)
log_call("abduction (not Honcho)", reply)
for h in json.loads(reply.text).get("hypotheses", []):
    print(f"{h['content']}\n   drawn from {h.get('premise_ids')}\n   check: {h.get('check')}\n")
Anton's shift from strict vegetarianism to pescatarianism in June 2026 [d22] was likely motivated by a desire to simplify his complex social dining planning, as managing his own severe peanut allergy [e3] alongside his guests' multiple restrictive dietary needs (shellfish allergy [e19] and coeliac disease [e20]) makes finding suitable restaurants increasingly difficult.
   drawn from ['e3', 'e19', 'e20', 'd22']
   check: Ask Anton if he finds it easier to select restaurants now that he includes fish in his diet, or if he feels the change has made planning for his guests' specific allergies more complicated.

The hypothesis says that Anton started eating fish in order to make the dinners easier to plan. Nobody said that. It is fluent, it cites its premises, and nothing stored can confirm or refute it. The check line, a test the next session could run, is the only safeguard this prompt adds.

What to take away

Stage What Honcho does What happened here
Extraction one call per batch; explicit rows, dated to the minute six and ten short facts; relative dates resolved
Saving drops exact duplicates; merges near duplicates within a session nothing merged; the allergy stored twice
Dream two agents with tools; deduction may delete an update written; two rows deleted, one of them still true
Links every derived row cites its sources what rests on a deleted row can be listed; Honcho does not act on it
Checks cited ids must exist confidence and level rules are only in prompts
Reading the representation (no model call) or the dialectic (an agent) both right on the diet; both carried stale derived rows
Cost set by the dream's rounds about 56,000 tokens for two short sessions

The five questions from the top.

1. Extraction. Short, dated facts, about as good as the other extractors in this series. Saving merges only near-identical rows from one session.

2. The dream. Two agents that read ten or twenty rows at a time and write what they conclude. Some of it follows from the facts; some is a guess filed as a deduction.

3. Updating. The dream wrote the update and deleted the old fact, and one true fact with it. What was drawn from the old fact stayed.

4. What the code checks. That cited ids exist. Everything else about premises is a request in a prompt.

5. Reading. Both paths gave the answering model the current diet, and both also gave it the stale conclusions.

Things worth trying

Contents

Reading

Text size

19 px

Column width

Colours

Code cells

When the file changes

Saved on this device.