Skip to content

sections

sections

Tier files as sections: parse, render, rank. Pure — no I/O.

A tier is a Markdown file directly inside the scope's tree (recent.md, growth.md...). It holds two kinds of unit:

  • fact blocks the backend wrote. Each opens with a level-2 heading that carries an HTML-comment marker and closes with a marker line::

    ## 2026-11-11 09:30:00Z the fact text, verbatim (it may contain its own headings)

The text between the markers is the fact, minus the one newline the writer adds. Headings inside it do not split it. - hand-written sections: everything else, cut at ## and ### heading lines. Text before the first heading is a section of its own. Whitespace-only stretches are not units.

Units are returned with their character offsets into the decoded text so a writer can splice one out without touching any other byte.

Classes

Unit dataclass

Unit(unit_id, tier, content, start, end, fact_id)

One recallable unit of a tier file.

Functions:

decode

decode(data)

Decode tier bytes so that :func:encode gives back the exact bytes.

Source code in src/marianne/memory/backends/files/sections.py
def decode(data: bytes) -> str:
    """Decode tier bytes so that :func:`encode` gives back the exact bytes."""
    return data.decode("utf-8", "surrogateescape")

has_marker

has_marker(text)

True when text contains something the parser would read as a marker.

Source code in src/marianne/memory/backends/files/sections.py
def has_marker(text: str) -> bool:
    """True when ``text`` contains something the parser would read as a marker."""
    return _ANY_MARKER_RE.search(text) is not None

render_block

render_block(fact_id, text, when)

The exact text written for one fact.

Source code in src/marianne/memory/backends/files/sections.py
def render_block(fact_id: str, text: str, when: float) -> str:
    """The exact text written for one fact."""
    stamp = datetime.fromtimestamp(when, UTC).strftime("%Y-%m-%d %H:%M:%SZ")
    return f"## {stamp} <!-- fact:{fact_id} -->\n{text}\n<!-- /fact:{fact_id} -->\n"

parse_tier

parse_tier(tier, text)

Cut text (decoded with :func:decode) into units, in file order.

Source code in src/marianne/memory/backends/files/sections.py
def parse_tier(tier: str, text: str) -> list[Unit]:
    """Cut ``text`` (decoded with :func:`decode`) into units, in file order."""
    lines = _lines(text)
    offsets = [0]
    for line in lines:
        offsets.append(offsets[-1] + len(line))
    units: list[Unit] = []
    seen: dict[str, int] = {}
    hand_start = 0

    def flush(end: int) -> None:
        chunk = text[hand_start:end]
        if chunk.strip():
            content = _clean(chunk)
            sid = _section_id(tier, content, seen)
            units.append(Unit(sid, tier, content, hand_start, end, None))

    i = 0
    while i < len(lines):
        line = lines[i]
        opened = _OPEN_RE.match(line)
        if opened:
            fid = opened.group(1)
            close = next(
                (j for j in range(i + 1, len(lines))
                 if (m := _CLOSE_RE.match(lines[j])) and m.group(1) == fid),
                None,
            )
            if close is not None:
                flush(offsets[i])
                body = "".join(lines[i + 1:close])
                if body.endswith("\n"):
                    body = body[:-1]
                units.append(Unit(fid, tier, _clean(body), offsets[i], offsets[close + 1], fid))
                hand_start = offsets[close + 1]
                i = close + 1
                continue
        if _HEADING_RE.match(line):
            flush(offsets[i])
            hand_start = offsets[i]
        i += 1
    flush(len(text))
    return units

score

score(query_tokens, content, asserted_at, now)

0.6 * match + 0.4 * 2^(-age / 30 days), rounded to 6 places.

match is the share of query tokens present in the unit's text (0 for an empty query). The caller drops units with no match for a non-empty query.

Source code in src/marianne/memory/backends/files/sections.py
def score(query_tokens: frozenset[str], content: str, asserted_at: float, now: float) -> float:
    """``0.6 * match + 0.4 * 2^(-age / 30 days)``, rounded to 6 places.

    ``match`` is the share of query tokens present in the unit's text (0 for
    an empty query). The caller drops units with no match for a non-empty
    query.
    """
    match = len(query_tokens & tokens(content)) / len(query_tokens) if query_tokens else 0.0
    age = max(0.0, now - asserted_at)
    recency = 2.0 ** (-age / RECENCY_HALF_LIFE_SECONDS)
    return float(round(MATCH_WEIGHT * match + RECENCY_WEIGHT * recency, 6))