Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions docs/features/memory/extraction.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,18 @@ from the observe plane. Only these run `loom.drop_non_durable` and `loom.verify_
The rules in `server/memory/domain/durable_facts.py` match sentence shape, not topic words: what
a release changed is kept; whether its CI was green at the time is dropped.

A plugin's session capture (a `source:` tag) is extracted under coding-session rules that
follow the conversation rules and replace their code rules. What the user states is kept
as in any conversation. From the work, only knowledge about the codebase that a later
session in the repository can reuse without reading the code again is kept:
A plugin's session capture (a `source:` tag) is extracted with a prompt of its own, at
every capture size. It holds no conversation rule or example, and is about 2,700 tokens
where the conversation prompt is 20,000 to 34,000, because most captures hold nothing to
keep and the prompt is then what the call costs. What the user states that holds beyond
the session is kept: a standing rule, a preference, a decision, a fact about their setup.
What the user asks for the task alone is not. Its schema asks for the fields a coding fact
uses and for the end of a state the user bounds (`valid_to`, `foresight`), so a freeze
"until Friday" stops being served after that day. The extractor sets no `valid_at`,
`temporal_confidence`, occurrence record or `question_topic` on a session capture's fact;
the row takes its `valid_at` from the fact's `temporal_anchor` when that is not in the
future, else from the observation date. From the work, only knowledge about the codebase
that a later session in the repository can reuse without reading the code again is kept:

- how a behaviour is reached across definitions or files, as one claim for the whole path;
- a relation between definitions that reading one of them does not show;
Expand Down
23 changes: 13 additions & 10 deletions server/memory/app/extract/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,15 +170,18 @@ def _extraction_system_prompt(
agent_learnings: bool = False,
coding_session: bool = False,
) -> str:
"""The extractor's system prompt: the base prompt under the strict-examples
preamble, the fence note, the namespace's categories and the caller's
instructions. Each call appends the operator's policy after it
(`with_policy`)."""
system_prompt = with_strict_examples_preamble(
_extraction_base_prompt(
compact, agent_learnings=agent_learnings, coding_session=coding_session
)
"""The extractor's system prompt: the base prompt (under the strict-examples
preamble when it is the conversation prompt), the fence note, the namespace's
categories and the caller's instructions. Each call appends the operator's
policy after it (`with_policy`)."""
system_prompt = _extraction_base_prompt(
compact, agent_learnings=agent_learnings, coding_session=coding_session
)
# The preamble binds the reply to numbered examples and rules out judging
# whether a case is worth a fact; a coding session's prompt has no such
# examples and asks for exactly that judgement.
if not coding_session:
system_prompt = with_strict_examples_preamble(system_prompt)
if existing_memories:
from server.memory.domain.prompt_fence import FENCE_NOTE

Expand Down Expand Up @@ -533,8 +536,8 @@ async def extract_from_messages(
`agent_learnings` asks the same call for the assistant's standing rules about
itself, returned as facts with `about="agent"` (`_split_agent_rules`).

`coding_session` marks a coding plugin's session capture: the base prompt ends
with the coding-session rules, under which zero facts is an answer, not a misfire.
`coding_session` marks a coding plugin's session capture: its system prompt is the
coding-session prompt alone, under which zero facts is an answer, not a misfire.
"""
if not messages:
return _no_messages_result()
Expand Down
18 changes: 9 additions & 9 deletions server/memory/app/extract/prompts.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
"""The first pass's prompts: the system prompt for the full or compact
examples with its flag-gated blocks, and the user prompt that layers the date, existing memories, prior turns and the current
messages.
"""The first pass's prompts: the system prompt (a coding session's own, or the
full or compact examples with their flag-gated blocks), and the user prompt that
layers the date, existing memories, prior turns and the current messages.
"""

from __future__ import annotations

from server.memory.app.extract.turns import _format_messages
from server.memory.domain.extraction_prompts import (
_AGENT_LEARNINGS_PROMPT_BLOCK,
_CODING_SESSION_PROMPT_BLOCK,
_CODING_SESSION_RETRY_ADDENDUM,
_CODING_SESSION_SYSTEM_PROMPT,
_EXTRACTION_SYSTEM_PROMPT,
_RETRY_PROMPT_ADDENDUM,
_STRUCTURED_ANSWER_PROMPT_BLOCK,
Expand All @@ -31,8 +31,11 @@ def _use_compact_prompt(messages: list[dict[str, object]]) -> bool:
def _extraction_base_prompt(
compact: bool, *, agent_learnings: bool = False, coding_session: bool = False
) -> str:
"""The extraction system prompt before the preamble: the full or the
compact examples, plus the flag-gated blocks."""
"""The extraction system prompt before the preamble: a coding session's own
prompt at every input size, else the full or the compact examples plus the
flag-gated blocks."""
if coding_session:
return _CODING_SESSION_SYSTEM_PROMPT
base_prompt = (
compact_extraction_prompt(_EXTRACTION_SYSTEM_PROMPT)
if compact
Expand All @@ -46,9 +49,6 @@ def _extraction_base_prompt(
# A standing rule is one short sentence, so a compact input gets the block too.
if agent_learnings:
base_prompt = base_prompt + "\n\n" + _AGENT_LEARNINGS_PROMPT_BLOCK
# Last, because it replaces rules above it for a coding session's turns.
if coding_session:
base_prompt = base_prompt + "\n\n" + _CODING_SESSION_PROMPT_BLOCK
return base_prompt


Expand Down
121 changes: 106 additions & 15 deletions server/memory/domain/extraction_prompts.py
Original file line number Diff line number Diff line change
Expand Up @@ -1978,26 +1978,56 @@ def with_strict_examples_preamble(system_prompt: str) -> str:
"""


# Appended to the extraction base prompt of a coding plugin's session
# capture. The rules above are written for conversations: their code rule asks
# for the concrete diff and a `File.cpp:123` location. Under them alone a coding
# session yields its own edits, which exist only in a working tree, and one
# line-numbered location per lookup, which the code index answers. A later
# session reuses what the code is, across definitions.
# The whole extraction prompt of a coding plugin's session capture. The prompt
# above is written for conversations: its code rule asks for the concrete diff
# and a `File.cpp:123` location, and under it a coding session yields its own
# edits, which exist only in a working tree, and one line-numbered location per
# lookup, which the code index answers. A later session reuses what the code
# is, across definitions. Most captures hold nothing to keep, so the prompt is
# the cost of the call: it carries no conversation rule or example, and its
# schema only the fields a coding fact uses and the two that end a state the
# user bounds (the parser defaults the rest).
CODING_SESSION_ANCHOR = "CODING SESSION — REUSABLE CODEBASE KNOWLEDGE ONLY"
_CODING_SESSION_PROMPT_BLOCK = f"""\
_CODING_SESSION_SYSTEM_PROMPT = f"""\
Role: evidence-bound memory extractor. The messages are one AI coding
session in a repository. Later sessions in the same repository search
this memory so that they do not have to read the same code again. Extract
the durable facts the messages hold and return strict JSON. Expect few
facts: most sessions hold zero to five.

RECORD WHAT IS ASSERTED. Write each statement as the messages state it,
even when it contradicts what you believe is true: never correct a value,
and never label a statement a claim, an error or a belief. Copy names,
paths, commands, versions and numbers verbatim.

==============================================================
WHAT THE USER STATES
==============================================================

Extract what a [user] turn states that holds beyond this session, one
fact per statement:
• a standing rule or convention for the repository or for how work is
done in it ("changelog entries only for user-visible changes");
• a preference (see the Preference rule under "tags");
• a decision: what was chosen, what was rejected, and why;
• a fact about the user, their team, their setup, environment,
deployment, constraints or plans;
• a named reviewer's or maintainer's standing expectations, tied to
that person's handle.
The subject is "User" for a fact about the user, the repository or
project for a rule about it, and the person's name for a fact about
someone else. Resolve a relative date ("last week") against
`observation_date`. What the user asks for or requires for this task
alone (the request, its scope, how to submit it, what to run or not to
run) is not a fact, however it is phrased: DO NOT EXTRACT below applies
to every turn.

==============================================================
{CODING_SESSION_ANCHOR}
==============================================================

The messages are one AI coding session in a repository. Later sessions in
the same repository search this memory so that they do not have to read
the same code again. What the USER states about themselves, their setup,
their standing rules, preferences and decisions is extracted as above.
For everything about the code and the work, the rules in this section
REPLACE "Code / engineering facts", "Assistant-stated facts",
"Enumerations and lists" and any rule above that captures an assistant
answer whole. Expect few facts: most sessions hold zero to five.
Everything about the code and the work is extracted under this section
alone.

EXTRACT, each as ONE claim that is true of the code and stands alone:
• how a behaviour is reached: the path from an entry point to the
Expand Down Expand Up @@ -2044,8 +2074,69 @@ def with_strict_examples_preamble(system_prompt: str) -> str:
`parse_header` in http/parse.py without a None check, so a None from
`parse_header` crashes request construction."

==============================================================
EXISTING MEMORIES
==============================================================

`existing_memories`, when shown, lists facts already remembered. Do not
extract a fact one of them already states. A fact that updates or refines
one of them is emitted with that memory's index in `linked_keys`; a fact
that contradicts one is emitted as stated.

==============================================================
OUTPUT SCHEMA
==============================================================

Return exactly one JSON object with one key, "facts", a list of objects:

"key": short_snake_case naming the SUBJECT and the ATTRIBUTE, never the
value (`user_merge_strategy`). A new value for an attribute already
keyed reuses its key, never `_new` or `_2`.
"value": the fact as one complete sentence that stands alone.
"tags": 0-4 lowercase tags. Preference rule: a user preference carries
BOTH "preference" and "preference:ATTRIBUTE", ATTRIBUTE being the
singular lowercase noun it is about (underscore-joined).
"entities": 0-6 lowercase named things: definitions, files, tools, people.
"topics": 0-3 lowercase concept phrases of 2-5 words, the idea the fact
is about and not one of its entities; [] when there is none.
"linked_keys": indices from existing_memories this fact updates or
refines (default []).
"source_message_indices": REQUIRED on every fact. 1-3 zero-based indices
from current_messages ([0:user], [1:assistant], ...) that directly
support the fact, never prior_turns.
"temporal_anchor": ISO date (YYYY-MM-DD) the fact is about when the
messages date it; null for a fact about the code, a rule or a
preference.
"valid_to": ISO date the fact stopped being true, when the messages
give a clear end ("the team used Jenkins until March 2026"); omit
while it still holds.
Comment thread
zlareb1 marked this conversation as resolved.
Resolved
"foresight": ONLY for a temporary state or a plan whose end or length
the messages state ("staging is being rebuilt until Friday", "on
call for two weeks"): {{"until": ISO date it ends, or null,
"duration_days": the stated length in days, or null}}, at least one
of the two set. Never for a rule, a preference or a fact about the
code.
"relations": REQUIRED when the fact has 2+ entities: triples
{{"s": subject, "v": verb, "o": object}}, lowercase, the verb 1-3
words underscore-joined.
"about": "other" when the fact is about a person other than the user;
omit otherwise.
"forget": true ONLY when the user asks to forget or to stop using
something: `key` names the attribute, `value` what to forget,
`linked_keys` every existing memory that holds it. Do not also emit
the forgotten information.

The example's fact in this schema:
{{"facts": [{{"key":"request_init_parse_header_none",
"value":"`Request.__init__` in http/request.py indexes the result of `parse_header` in http/parse.py without a None check, so a None from `parse_header` crashes request construction.",
"tags":["code","pitfall"],
"entities":["request.__init__","parse_header","http/request.py","http/parse.py"],
"relations":[{{"s":"request.__init__","v":"indexes_result_of","o":"parse_header"}}],
"source_message_indices":[0]}}]}}

{{"facts": []}} is the right answer for a session that established nothing
reusable about the code and in which the user stated nothing durable.
No markdown. No commentary. Only the JSON object.
"""

_JUDGE_SYSTEM_PROMPT = """You judge extracted memorable facts against
Expand Down
68 changes: 64 additions & 4 deletions tests/unit/test_coding_session_extraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,18 @@
from server.llm.client import LLMResult
from server.memory.app import durability_verifier, pipeline, pipeline_state
from server.memory.app.extract import ExtractionResult, extract_from_messages
from server.memory.app.extract.extract import _extraction_system_prompt
from server.memory.app.extract.parse import _parse_fact_list
from server.memory.app.extract.prompts import _extraction_base_prompt
from server.memory.app.extract.sweep import slim_sweep_system_prompt
from server.memory.app.trajectory_notes import TRAJECTORY_EXTRACTION_INSTRUCTIONS
from server.memory.domain import durable_facts
from server.memory.domain.extraction_prompts import (
_CODING_SESSION_PROMPT_BLOCK,
_CODING_SESSION_RETRY_ADDENDUM,
_CODING_SESSION_SYSTEM_PROMPT,
CODING_SESSION_ANCHOR,
)
from server.memory.domain.prompt_fence import FENCE_NOTE
from server.settings import settings
from tests.unit.llm_fake import ScriptedLLM

Expand All @@ -29,10 +33,66 @@


@pytest.mark.parametrize("compact", [False, True])
def test_the_coding_rules_follow_the_base_prompt_of_a_coding_session_only(compact: bool) -> None:
def test_a_coding_session_is_extracted_with_its_own_prompt_at_every_size(compact: bool) -> None:
assert CODING_SESSION_ANCHOR not in _extraction_base_prompt(compact)
prompt = _extraction_base_prompt(compact, agent_learnings=True, coding_session=True)
assert prompt.endswith(_CODING_SESSION_PROMPT_BLOCK)

def system_prompt(existing: list[dict[str, str]] | None) -> str:
return _extraction_system_prompt(
compact,
existing_memories=existing,
namespace_categories=None,
custom_instructions="",
agent_learnings=True,
coding_session=True,
)

prompt = system_prompt(None)
# No conversation rule or example and no examples preamble.
assert prompt == _CODING_SESSION_SYSTEM_PROMPT
assert "EXAMPLE 1" not in prompt
# Most captures hold nothing to keep, so this prompt is what their call costs.
assert len(prompt) < 9000
# Shown existing memories, which only a short capture is, it ends with the
# fence note: the one other system text a session capture is sent.
existing = [{"memory_key": "k0", "value": "User lives in Lyon."}]
assert system_prompt(existing) == prompt + "\n\n" + FENCE_NOTE


def test_the_coding_session_prompt_ends_with_a_schema_the_parser_reads() -> None:
prompt = _CODING_SESSION_SYSTEM_PROMPT
anchor = prompt[prompt.index("The example's fact in this schema:") :]
(fact,) = _parse_fact_list(anchor[: anchor.index("\n\n")])
assert fact.memory_key == "request_init_parse_header_none"
assert [(s, o) for s, _, o in fact.relations] == [("request.__init__", "parse_header")]
assert fact.relation_phrases == ["indexes_result_of"]
assert fact.source_message_indices == [0]
assert len(fact.entities) == 4 and fact.tags == ["code", "pitfall"]
# The schema is the last section, so a sweep's prompt takes it without the rules.
slim = slim_sweep_system_prompt(prompt)
assert "source_message_indices" in slim and "DO NOT EXTRACT" not in slim


def test_the_session_schema_names_every_field_the_write_step_acts_on() -> None:
schema = _CODING_SESSION_SYSTEM_PROMPT.partition("OUTPUT SCHEMA")[2]
# A field the schema leaves out keeps the parser's default: no link to the
# memory a fact refines, no ownership tag, no retirement on a forget request,
# no end to a state the user bounded.
for name in (
"key",
"value",
"tags",
"entities",
"topics",
"linked_keys",
"source_message_indices",
"temporal_anchor",
"valid_to",
"foresight",
"relations",
"about",
"forget",
):
assert f'\n "{name}": ' in schema, name


async def _calls_for_no_facts(
Expand Down
Loading