test_freshness.py

tests/test_freshness.py

THE TOOL DESCRIBING ITS OWN CURRENCY — gh#2, gh#9 and gh#29 as one surface.

test_a_current_index_carries_no_staleness_noise

None test_freshness.test_a_current_index_carries_no_staleness_noise()

A wholly current index and process produce no notices at all.

tests/test_freshness.py:99

Show on the map →

Called by none

Calls _status, notices

Checks

  • assert fr.notices(_status(), MATCHING_CODE) == []

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_a_current_index_carries_no_staleness_noise → notices
Source · 18 lines
def test_a_current_index_carries_no_staleness_noise() -> None:
    """THE CONTROL ON THE ENTIRE CHANGE. This annotation rides on every query reply, so
    if it cannot be silent it becomes a permanent banner that trains the reader to skip
    it — which is how the disarmed coverage gate, the leaked identifiers and a whole
    36-cell grid each got past someone.

    Mutating any single term of `_status` below must break this test; that is what the
    per-axis tests immediately following are.

    @brief A current tool is annotated with nothing.
    @version 1
    """
    assert fr.notices(_status(), MATCHING_CODE) == []


# ─── axis: schema (gh#29's cheap half — two integers nothing interpreted) ─────

Activity · 1 steps
lines 111–111assert fr.notices(_status(), MATCHING_CODE) == []

test_a_current_index_does_not_annotate_its_query_replies

None test_freshness.test_a_current_index_does_not_annotate_its_query_replies(Path rich_db)

A current index's query replies carry NO staleness key at all.

tests/test_freshness.py:599

Show on the map →

Called by none

Calls none

Checks

  • assert "staleness" not in tools.dossier("main")

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-004measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004catalog
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
Source · 12 lines
def test_a_current_index_does_not_annotate_its_query_replies(rich_db: Path) -> None:
    """The control on the mechanism, matching the control on the messages. An absent key
    rather than an empty list: `staleness: []` on every reply is noise that a model pays
    for on every call and learns to skip.

    @brief A current index annotates nothing.
    @version 1
    """
    tools = QueryTools(lambda: rich_db, lambda: rich_db.parent, list)
    assert "staleness" not in tools.dossier("main")

Activity · 2 steps
lines 607–607tools = QueryTools(lambda: rich_db, lambda: rich_db.parent, list)lines 608–608assert "staleness" not in tools.dossier("main")

test_a_failing_staleness_measurement_does_not_break_the_reply

None test_freshness.test_a_failing_staleness_measurement_does_not_break_the_reply(Path rich_db)

A provider that raises does not turn a good answer into an error.

tests/test_freshness.py:629

Show on the map →

Called by none

Calls none

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-004measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004catalog
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
Source · 16 lines
def test_a_failing_staleness_measurement_does_not_break_the_reply(rich_db: Path) -> None:
    """The annotation runs on the way OUT of replies that have already succeeded. A
    freshness check that could not run must cost the annotation, never the answer.

    @brief A raising provider degrades to no annotation.
    @version 1
    """

    def _explode() -> list[dict[str, str]]:
        raise sqlite3.Error("state root vanished mid-session")

    tools = QueryTools(lambda: rich_db, lambda: rich_db.parent, _explode)
    with pytest.raises(sqlite3.Error):
        tools.dossier("main")

Activity · 4 steps
lines 637–638def _explode() -> list[dict[str, str]]: raise sqlite3.Error("state root vanished mid-session")lines 640–640tools = QueryTools(lambda: rich_db, lambda: rich_db.parent, _explode)lines 641–641with pytest.raises(sqlite3.Error)lines 642–642tools.dossier("main")

test_a_future_source_mtime_is_not_evidence_of_an_edit

None test_freshness.test_a_future_source_mtime_is_not_evidence_of_an_edit(Path tmp_path)

A source file dated in the future does not make an index permanently stale.

tests/test_freshness.py:938

Checks

  • assert changed == 0, f"a future mtime was counted as an edit ({newest})"
  • assert (changed, newest) == (1, "src/b.c"), "a genuine edit must still raise drift"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004catalog
Source · 42 lines
def test_a_future_source_mtime_is_not_evidence_of_an_edit(tmp_path: Path) -> None:
    """M7, 1.1.0 SECURITY AUDIT. `_source_drift` compares every indexed file's mtime against
    the database's, so a file stamped in the future — a checkout from a machine with a skewed
    clock, a tarball carrying bogus timestamps, or a repository that committed one on purpose
    — is NEWER than every database that will ever be built from it. The index is then
    permanently stale, and the 15 s `keep_current` loop rebuilds it forever: doxygen, cargo
    and the Kconfig parse, all repo-controlled stages, on a loop, for as long as the server
    lives.

    A future mtime is not evidence that a file was edited. It is skipped and reported once;
    the file is still INDEXED, only its timestamp is refused as a staleness signal.

    @brief A far-future mtime raises no drift.
    @return None.
    @version 1
    """
    repo = tmp_path / "repo"
    (repo / "src").mkdir(parents=True)
    (repo / "src" / "a.c").write_text("int a(void) { return 0; }\n", encoding="utf-8")
    (repo / "src" / "b.c").write_text("int b(void) { return 0; }\n", encoding="utf-8")

    db = tmp_path / "clew.db"
    conn = sqlite3.connect(str(db))
    conn.execute("CREATE TABLE path (name TEXT, type INTEGER)")
    conn.executemany("INSERT INTO path (name, type) VALUES (?, 1)", [("src/a.c",), ("src/b.c",)])
    conn.commit()
    conn.close()

    ## A YEAR AHEAD, so no clock-skew tolerance could plausibly absorb it.
    future = db.stat().st_mtime + 365 * 24 * 3600
    os.utime(repo / "src" / "a.c", (future, future))

    changed, newest = st._source_drift(db, repo)

    assert changed == 0, f"a future mtime was counted as an edit ({newest})"

    ## AND THE CONTROL: an ordinary edit after the build still counts, which is the whole
    ## point of the term. Without this half, returning a constant zero would pass.
    recent = db.stat().st_mtime + 10
    os.utime(repo / "src" / "b.c", (recent, recent))
    changed, newest = st._source_drift(db, repo)
    assert (changed, newest) == (1, "src/b.c"), "a genuine edit must still raise drift"

1 more lines, not shown

Activity · 18 steps
lines 954–954repo = tmp_path / "repo"lines 955–955(repo / "src").mkdir(parents=True)lines 956–956(repo / "src" / "a.c").write_text("int a(void) { return 0; }\n", encoding="utf-8")lines 957–957(repo / "src" / "b.c").write_text("int b(void) { return 0; }\n", encoding="utf-8")lines 959–959db = tmp_path / "clew.db"lines 960–960conn = sqlite3.connect(str(db))lines 961–961conn.execute("CREATE TABLE path (name TEXT, type INTEGER)")lines 962–962conn.executemany("INSERT INTO path (name, type) VALUES (?, 1)", [("src/a.c",), ("src/b.c",)])lines 963–963conn.commit()lines 964–964conn.close()lines 967–967future = db.stat().st_mtime + 365 * 24 * 3600lines 968–968os.utime(repo / "src" / "a.c", (future, future))lines 970–970changed, newest = st._source_drift(db, repo)lines 972–972assert changed == 0, f"a future mtime was counted as an edit ({newest})"lines 976–976recent = db.stat().st_mtime + 10lines 977–977os.utime(repo / "src" / "b.c", (recent, recent))lines 978–978changed, newest = st._source_drift(db, repo)lines 979–979assert (changed, newest) == (1, "src/b.c"), "a genuine edit must still raise drift"

test_a_miss_also_carries_the_staleness

None test_freshness.test_a_miss_also_carries_the_staleness(Path rich_db)

A miss envelope carries staleness too.

tests/test_freshness.py:579

Show on the map →

Called by none

Calls none

Checks

  • assert payload["found"] is False
  • assert payload["staleness"] == drift

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measured
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-013measured
REQ-DDB-QUERY-014measured
Source · 16 lines
def test_a_miss_also_carries_the_staleness(rich_db: Path) -> None:
    """The reply where it matters MOST. "Not in this index" and "not in this index YET,
    because the index predates the function you just wrote" are the same payload today,
    and the second is the commoner one for an agent querying code it is editing.

    @brief A not-found reply is annotated.
    @version 1
    """
    drift = [{"axis": fr.AXIS_DATA, "message": "5 files changed; call build_or_refresh()"}]
    tools = QueryTools(lambda: rich_db, lambda: rich_db.parent, lambda: drift)

    payload = tools.dossier("a_function_this_index_has_never_heard_of")
    assert payload["found"] is False
    assert payload["staleness"] == drift

Activity · 5 steps
lines 587–587drift = [{"axis": fr.AXIS_DATA, "message": "5 files changed; call build_or_refresh()"}]lines 588–588tools = QueryTools(lambda: rich_db, lambda: rich_db.parent, lambda: drift)lines 590–590payload = tools.dossier("a_function_this_index_has_never_heard_of")lines 591–591assert payload["found"] is Falselines 592–592assert payload["staleness"] == drift

test_a_query_against_a_stale_index_carries_the_staleness

None test_freshness.test_a_query_against_a_stale_index_carries_the_staleness(Path rich_db)

A query against a stale database carries that fact in its own payload.

tests/test_freshness.py:555

Show on the map →

Called by none

Calls none

Checks

  • assert payload["staleness"] == drift
  • assert payload["target"], "the target stamp must survive alongside it"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-004measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004measured
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
Source · 20 lines
def test_a_query_against_a_stale_index_carries_the_staleness(rich_db: Path) -> None:
    """gh#2's mechanism. `status` reported staleness clearly and without being asked
    twice — but reading it requires already SUSPECTING a problem, which is exactly what
    a consumer holding a confident, fresh-looking answer does not have. The signal was
    opt-in and the failure silent.

    Driven through `QueryTools` rather than the notice function, because the claim is
    about what a model actually receives.

    @brief A stale index annotates its query replies.
    @version 1
    """
    drift = [{"axis": fr.AXIS_DATA, "message": "5 files changed; call build_or_refresh()"}]
    tools = QueryTools(lambda: rich_db, lambda: rich_db.parent, lambda: drift)

    payload = tools.dossier("main")
    assert payload["staleness"] == drift
    assert payload["target"], "the target stamp must survive alongside it"

Activity · 5 steps
lines 567–567drift = [{"axis": fr.AXIS_DATA, "message": "5 files changed; call build_or_refresh()"}]lines 568–568tools = QueryTools(lambda: rich_db, lambda: rich_db.parent, lambda: drift)lines 570–570payload = tools.dossier("main")lines 571–571assert payload["staleness"] == driftlines 572–572assert payload["target"], "the target stamp must survive alongside it"

test_a_server_predating_its_index_is_told_to_restart_not_to_rebuild

None test_freshness.test_a_server_predating_its_index_is_told_to_restart_not_to_rebuild()

An index NEWER than the server tells the reader to restart, never to rebuild.

tests/test_freshness.py:120

Show on the map →

Called by none

Calls _message, _status, notices

Checks

  • assert message, "a version skew must raise the schema axis"
  • assert "restart" in message.lower(), "the only action that clears this must be named"
  • assert "CANNOT CLEAR" in message, "it must say a rebuild cannot clear the flag"
  • assert "action='refresh'" not in message, ("advising a rebuild here is the defect: rebuilding re-stamps the same newer " "version and the flag stays up" )
  • assert str(CURRENT + 6) in message and str(CURRENT) in message, ("both integers belong in the message — the reader needs the comparison, not the verdict" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_a_server_predating_its_index_is_told_to_restart_not_to_rebuild → notices
Source · 34 lines
def test_a_server_predating_its_index_is_told_to_restart_not_to_rebuild() -> None:
    """THE UNRESOLVABLE CASE, observed live at build 23 against a server expecting 17.
    A rebuild re-stamps the SAME newer version, so `stale: true` cannot be cleared by any
    action the consumer takes — and advising a rebuild sends them round a loop with no
    exit. The diagnosis was already in the payload as two mismatched integers and
    nothing read them out loud.

    Asserts the DIRECTION explicitly, not merely that some message appeared: a notice
    that fired here with the other branch's text would be worse than no notice, because
    it would be confidently wrong about the remedy.

    @brief The index-newer direction names a restart and denies a rebuild.
    @version 1
    """
    found = fr.notices(_status(build_version=CURRENT + 6, stale=True), MATCHING_CODE)

    message = _message(found, fr.AXIS_SCHEMA)
    assert message, "a version skew must raise the schema axis"
    assert "restart" in message.lower(), "the only action that clears this must be named"
    assert "CANNOT CLEAR" in message, "it must say a rebuild cannot clear the flag"
    ## SPELLED AS THE TOOL SPELLS IT. This forbade `build_or_refresh`, which the served messages
    ## stopped saying when the three admin tools were folded into `index(action=...)` — so the
    ## guard went on passing while forbidding a string that could no longer appear. A negative
    ## assertion pinned to a renamed identifier is the quietest vacuous test there is: it never
    ## fails, and nothing distinguishes "the defect is absent" from "the check cannot see it".
    assert "action='refresh'" not in message, (
        "advising a rebuild here is the defect: rebuilding re-stamps the same newer "
        "version and the flag stays up"
    )
    assert str(CURRENT + 6) in message and str(CURRENT) in message, (
        "both integers belong in the message — the reader needs the comparison, not the verdict"
    )

Activity · 7 steps
lines 134–134found = fr.notices(_status(build_version=CURRENT + 6, stale=True), MATCHING_CODE)lines 136–136message = _message(found, fr.AXIS_SCHEMA)lines 137–137assert message, "a version skew must raise the schema axis"lines 138–138assert "restart" in message.lower(), "the only action that clears this must be named"lines 139–139assert "CANNOT CLEAR" in message, "it must say a rebuild cannot clear the flag"lines 145–148assert "action='refresh'" not in message, ( "advising a rebuild here is the defect: rebuilding re-stamps the same newer " "version and the flag stays up" )lines 149–151assert str(CURRENT + 6) in message and str(CURRENT) in message, ( "both integers belong in the message — the reader needs the comparison, not the verdict" )

test_a_small_reply_keeps_the_full_staleness_prose

None test_freshness.test_a_small_reply_keeps_the_full_staleness_prose(Path rich_db)

A reply with room to spare keeps the full prose.

tests/test_freshness.py:690

Show on the map →

Called by none

Calls none

Checks

  • assert fitted == full

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004catalog
Source · 12 lines
def test_a_small_reply_keeps_the_full_staleness_prose(rich_db: Path) -> None:
    """The control on the compaction: a mechanism that always compacts would deliver the
    pointer and never the remedy, and the remedy is the whole value.

    @brief A small reply is not compacted.
    @version 1
    """
    full = [{"axis": fr.AXIS_DATA, "message": "x" * 400}]
    fitted = QueryTools(lambda: rich_db, lambda: rich_db.parent, lambda: full)._staleness({"a": 1})
    assert fitted == full

Activity · 3 steps
lines 697–697full = [{"axis": fr.AXIS_DATA, "message": "x" * 400}]lines 698–698fitted = QueryTools(lambda: rich_db, lambda: rich_db.parent, lambda: full)._staleness({"a": 1})lines 699–699assert fitted == full

test_a_stale_process_refuses_a_write_and_a_matching_one_does_not

None test_freshness.test_a_stale_process_refuses_a_write_and_a_matching_one_does_not()

A stale process refuses a write; a matching one raises no objection.

tests/test_freshness.py:356

Checks

  • assert refusal is not None
  • assert "restart" in refusal.lower() and "force=True" in refusal
  • assert "Nothing was written" in refusal
  • assert fr.stale_code_refusal(MATCHING_CODE) is None

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_a_stale_process_refuses_a_write_and_a_matching_one_does_not → stale_code_refusal
Source · 22 lines
def test_a_stale_process_refuses_a_write_and_a_matching_one_does_not() -> None:
    """THE CONTROL IS THE SECOND HALF. A refusal that fires unconditionally would block
    every build on every target, which is a worse bug than the one being fixed — and this
    repo's whole warning history is of signals that could not be silent.

    The refusal names the remedy because it costs exactly one reconnect: measured, a client
    restart plus `build_or_refresh(force=True)` restored `external=29` to the stage list and
    both `options.*.tier` rows.

    @brief A stale identity refuses; a matching identity does not.
    @version 1
    """
    stale = dict(MATCHING_CODE, source_fingerprint="bbbbbbbbbbbb", matches_source=False)

    refusal = fr.stale_code_refusal(stale)
    assert refusal is not None
    assert "restart" in refusal.lower() and "force=True" in refusal
    assert "Nothing was written" in refusal

    assert fr.stale_code_refusal(MATCHING_CODE) is None

Activity · 6 steps
lines 368–368stale = dict(MATCHING_CODE, source_fingerprint="bbbbbbbbbbbb", matches_source=False)lines 370–370refusal = fr.stale_code_refusal(stale)lines 371–371assert refusal is not Nonelines 372–372assert "restart" in refusal.lower() and "force=True" in refusallines 373–373assert "Nothing was written" in refusallines 375–375assert fr.stale_code_refusal(MATCHING_CODE) is None

test_a_test_run_never_inherits_a_moved_source_fingerprint

None test_freshness.test_a_test_run_never_inherits_a_moved_source_fingerprint()

Every test starts with the running tree matching the process fingerprint.

tests/test_freshness.py:900

Checks

  • assert identity["matches_source"] is True, ("this test run began with the source tree already disagreeing with the process " "fingerprint, so every build-shaped test in it will refuse — see " "`_pin_source_fingerprint` in conftest" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_a_test_run_never_inherits_a_moved_source_fingerprint → code_identity
Source · 34 lines
def test_a_test_run_never_inherits_a_moved_source_fingerprint() -> None:
    """WHAT THIS PROTECTS is the rest of the suite, not `code_identity` itself.

    `PROCESS_SOURCE_FINGERPRINT` is captured once at import, and `build_or_refresh` REFUSES
    when the tree no longer matches it — right for a long-lived MCP server, where code that
    moved under a running process means the pipeline and the answers disagree. A pytest run is
    not that process: it lasts minutes, and the tree moving during it means somebody saved a
    file. Every build-shaped test in the run then fails on a guard about the editor:

        REFUSED: this server process loaded clew 1.0.31 at launch and the package source has
        changed since ... 'matches_source': False

    MEASURED, with the `_pin_source_fingerprint` fixture removed and the fingerprint moved the
    way a save moves it: 10 of these tests failed, the same ones that failed three times in one
    session and passed on every re-run. That is the shape which teaches a reader to wave
    failures through as flakes — and they were not flakes.

    ASSERTS THE PROPERTY, NOT THE FIXTURE, so it holds however the pinning is done — and fails
    the moment a run inherits a moved fingerprint again.

    @brief The code axis reads clean inside a test.
    @return None.
    @version 1
    """
    from clew.mcp_server.freshness import code_identity

    identity = code_identity()
    assert identity["matches_source"] is True, (
        "this test run began with the source tree already disagreeing with the process "
        "fingerprint, so every build-shaped test in it will refuse — see "
        "`_pin_source_fingerprint` in conftest"
    )

Activity · 3 steps
lines 924–924from clew.mcp_server.freshness import code_identitylines 926–926identity = code_identity()lines 927–931assert identity["matches_source"] is True, ( "this test run began with the source tree already disagreeing with the process " "fingerprint, so every build-shaped test in it will refuse — see " "`_pin_source_fingerprint` in conftest" )

test_a_zero_duration_reads_as_measured_not_as_missing

None test_freshness.test_a_zero_duration_reads_as_measured_not_as_missing()

A measured ZERO is reported as a measurement, not as an absence.

tests/test_freshness.py:248

Checks

  • assert "0 ms" in clause
  • assert "unmeasured" not in clause

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004catalog
Source · 13 lines
def test_a_zero_duration_reads_as_measured_not_as_missing() -> None:
    """A fully cached rebuild legitimately costs ~0 ms and reprocesses 0 files. The
    persisted value is the STRING "0" precisely so it survives the falsy-drop rule, and
    the phrasing layer must not undo that by treating it as absent.

    @brief Zero is a measurement.
    @version 1
    """
    clause = fr._cost_clause({"duration_ms": "0", "payloads_recomputed": "0"})
    assert "0 ms" in clause
    assert "unmeasured" not in clause

Activity · 3 steps
lines 256–256clause = fr._cost_clause({"duration_ms": "0", "payloads_recomputed": "0"})lines 257–257assert "0 ms" in clauselines 258–258assert "unmeasured" not in clause

test_a_zero_refresh_measurement_survives_persistence

None test_freshness.test_a_zero_refresh_measurement_survives_persistence(Path tmp_path)

A measured ZERO survives persistence, where a falsy value would be dropped.

tests/test_freshness.py:504

Checks

  • assert st.db_status(target)["refresh"] == {"duration_ms": "0", "payloads_recomputed": "0"}

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measuredtest_a_zero_refresh_measurement_survives_persistence → db_status
REQ-DDB-CONFIG-007measuredtest_a_zero_refresh_measurement_survives_persistence → db_status
REQ-DDB-INDEX-003measuredtest_a_zero_refresh_measurement_survives_persistence → db_status → _coverage_meta
REQ-DDB-MCP-001measuredtest_a_zero_refresh_measurement_survives_persistence → db_status
REQ-DDB-MCP-004measuredtest_a_zero_refresh_measurement_survives_persistence → db_status
REQ-DDB-PIPE-005measuredtest_a_zero_refresh_measurement_survives_persistence → write_build_signature
Source · 19 lines
def test_a_zero_refresh_measurement_survives_persistence(tmp_path: Path) -> None:
    """`write_build_signature` DROPS FALSY VALUES so an absent key can honestly read as
    "not recorded". gh#6, gh#17 and gh#18 each had to work around that for a measured
    zero; this is the fourth section to do so, and a fully cached rebuild really does
    reprocess zero files in under a millisecond.

    The test writes STRINGS, which is the contract — and asserts the value comes back,
    which is what would break if a caller ever passed the int.

    @brief Zero survives the falsy-drop rule.
    @version 1
    """
    db = tmp_path / "clew.db"
    write_build_signature(db, refresh={"duration_ms": "0", "payloads_recomputed": "0"})

    target = st.Target(repo_path=str(tmp_path), slug="t", db_path=str(db))
    assert st.db_status(target)["refresh"] == {"duration_ms": "0", "payloads_recomputed": "0"}

Activity · 4 steps
lines 516–516db = tmp_path / "clew.db"lines 517–517write_build_signature(db, refresh={"duration_ms": "0", "payloads_recomputed": "0"})lines 519–519target = st.Target(repo_path=str(tmp_path), slug="t", db_path=str(db))lines 520–520assert st.db_status(target)["refresh"] == {"duration_ms": "0", "payloads_recomputed": "0"}

test_an_index_predating_the_server_is_told_to_rebuild

None test_freshness.test_an_index_predating_the_server_is_told_to_rebuild()

An index OLDER than the server is told to rebuild.

tests/test_freshness.py:157

Show on the map →

Called by none

Calls _message, _status, notices

Checks

  • assert "index(action='refresh'" in message assert "restart" not in message.lower()

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_an_index_predating_the_server_is_told_to_rebuild → notices
Source · 15 lines
def test_an_index_predating_the_server_is_told_to_rebuild() -> None:
    """The opposite direction, and the reason the test above asserts on direction rather
    than on presence. This one IS fixed by a rebuild, so the advice must invert.

    @brief The index-older direction names a rebuild.
    @version 1
    """
    message = _message(
        fr.notices(_status(build_version=CURRENT - 6, stale=True), MATCHING_CODE),
        fr.AXIS_SCHEMA,
    )
    assert "index(action='refresh'" in message
    assert "restart" not in message.lower()

Activity · 3 steps
lines 164–167message = _message( fr.notices(_status(build_version=CURRENT - 6, stale=True), MATCHING_CODE), fr.AXIS_SCHEMA, )lines 168–168assert "index(action='refresh'" in messagelines 169–169assert "restart" not in message.lower()

test_an_oversized_reply_compacts_the_message_but_keeps_the_axis

None test_freshness.test_an_oversized_reply_compacts_the_message_but_keeps_the_axis(Path rich_db)

An oversized reply keeps the axis token and compacts only the prose.

tests/test_freshness.py:649

Show on the map →

Called by none

Calls all

Checks

  • assert [n["axis"] for n in compact] == [fr.AXIS_DATA, fr.AXIS_CODE]
  • assert all("x" * 2_000 not in n["message"] for n in compact)
  • assert "call status" in compact[0]["message"], "the compact tier must still name the remedy"
  • assert len(json.dumps(roomy)) + len(json.dumps({"staleness": compact})) <= RESPONSE_BUDGET_BYTES
  • assert [n["axis"] for n in minimal] == [fr.AXIS_DATA, fr.AXIS_CODE], ("the axis token must survive every tier — it is what a consumer branches on" )
  • assert (len(json.dumps(cramped)) + len(json.dumps({"staleness": minimal})) <= RESPONSE_BUDGET_BYTES )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004catalog
REQ-DDB-WIKI-054inferredtest_an_oversized_reply_compacts_the_message_but_keeps_the_axis → all
Source · 37 lines
def test_an_oversized_reply_compacts_the_message_but_keeps_the_axis(rich_db: Path) -> None:
    """`_shrink_to_budget` trims a payload to just under the cap, so a full three-axis
    block could push it over — and the response budget exists to protect a model's
    context. The axis TOKEN is what a consumer branches on, so bytes are taken from the
    explanation and never from the axis.

    @brief Overflow compacts the prose, not the axis.
    @version 1
    """
    huge = [
        {"axis": fr.AXIS_DATA, "message": "x" * 2_000},
        {"axis": fr.AXIS_CODE, "message": "y" * 2_000},
    ]
    tools = QueryTools(lambda: rich_db, lambda: rich_db.parent, lambda: huge)

    ## 900 bytes free: the full block cannot fit and the compact one can. This is the
    ## tier the real trim path would land on if a reply ever ran this close to the cap.
    roomy = {"filler": "z" * (RESPONSE_BUDGET_BYTES - 900)}
    compact = tools._staleness(roomy)
    assert [n["axis"] for n in compact] == [fr.AXIS_DATA, fr.AXIS_CODE]
    assert all("x" * 2_000 not in n["message"] for n in compact)
    assert "call status" in compact[0]["message"], "the compact tier must still name the remedy"
    assert len(json.dumps(roomy)) + len(json.dumps({"staleness": compact})) <= RESPONSE_BUDGET_BYTES

    ## 200 bytes free — LESS THAN THE COMPACT BLOCK ITSELF. The first version of the
    ## fallback returned the compact form unconditionally and blew the cap here, which is
    ## why a third tier exists. A fallback that is merely smaller is not bounded.
    cramped = {"filler": "z" * (RESPONSE_BUDGET_BYTES - 200)}
    minimal = tools._staleness(cramped)
    assert [n["axis"] for n in minimal] == [fr.AXIS_DATA, fr.AXIS_CODE], (
        "the axis token must survive every tier — it is what a consumer branches on"
    )
    assert (
        len(json.dumps(cramped)) + len(json.dumps({"staleness": minimal})) <= RESPONSE_BUDGET_BYTES
    )

Activity · 12 steps
lines 658–661huge = [ {"axis": fr.AXIS_DATA, "message": "x" * 2_000}, {"axis": fr.AXIS_CODE, "message": "y" * 2_000}, ]lines 662–662tools = QueryTools(lambda: rich_db, lambda: rich_db.parent, lambda: huge)lines 666–666roomy = {"filler": "z" * (RESPONSE_BUDGET_BYTES - 900)}lines 667–667compact = tools._staleness(roomy)lines 668–668assert [n["axis"] for n in compact] == [fr.AXIS_DATA, fr.AXIS_CODE]lines 669–669assert all("x" * 2_000 not in n["message"] for n in compact)lines 670–670assert "call status" in compact[0]["message"], "the compact tier must still name the remedy"lines 671–671assert len(json.dumps(roomy)) + len(json.dumps({"staleness": compact})) <= RESPONSE_BUDGET_BYTESlines 676–676cramped = {"filler": "z" * (RESPONSE_BUDGET_BYTES - 200)}lines 677–677minimal = tools._staleness(cramped)lines 678–680assert [n["axis"] for n in minimal] == [fr.AXIS_DATA, fr.AXIS_CODE], ( "the axis token must survive every tier — it is what a consumer branches on" )lines 681–683assert ( len(json.dumps(cramped)) + len(json.dumps({"staleness": minimal})) <= RESPONSE_BUDGET_BYTES )

test_an_unbound_provider_annotates_nothing

None test_freshness.test_an_unbound_provider_annotates_nothing(Path rich_db)

A tool set bound without a provider behaves exactly as it did before gh#2.

tests/test_freshness.py:615

Show on the map →

Called by none

Calls none

Checks

  • assert "staleness" not in QueryTools(lambda: rich_db, lambda: rich_db.parent).dossier("main")

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-INDEX-004measured
REQ-DDB-MCP-003measured
REQ-DDB-MCP-004catalog
REQ-DDB-QUERY-001measured
REQ-DDB-QUERY-002measured
REQ-DDB-QUERY-003measured
REQ-DDB-QUERY-004measured
REQ-DDB-QUERY-006measured
REQ-DDB-QUERY-009measured
REQ-DDB-QUERY-010measured
REQ-DDB-QUERY-012measured
REQ-DDB-QUERY-014measured
REQ-DDB-SCHEMA-011measured
Source · 10 lines
def test_an_unbound_provider_annotates_nothing(rich_db: Path) -> None:
    """The provider is optional so the pre-gh#2 shape is still reachable and still
    silent — which is what keeps the change additive for every existing caller.

    @brief No provider means no annotation.
    @version 1
    """
    assert "staleness" not in QueryTools(lambda: rich_db, lambda: rich_db.parent).dossier("main")

Activity · 1 steps
lines 622–622assert "staleness" not in QueryTools(lambda: rich_db, lambda: rich_db.parent).dossier("main")

test_an_unreadable_source_tree_does_not_manufacture_a_code_warning

None test_freshness.test_an_unreadable_source_tree_does_not_manufacture_a_code_warning(Path tmp_path)

An unreadable source tree yields "cannot tell", never a fabricated warning.

tests/test_freshness.py:382

Show on the map →

Called by none

Calls _message, _status, notices, source_fingerprint

Checks

  • assert fr.source_fingerprint(tmp_path / "does-not-exist") == ""
  • assert _message(fr.notices(_status(), unknown), fr.AXIS_CODE) == ""

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_an_unreadable_source_tree_does_not_manufacture_a_code_warning → source_fingerprint
Source · 15 lines
def test_an_unreadable_source_tree_does_not_manufacture_a_code_warning(tmp_path: Path) -> None:
    """`source_fingerprint` returns "" for a tree it cannot read, and that must read as
    absent evidence rather than as disagreement. A warning that fires when the check
    could not run is the "guard that fires on some of the real cases" defect: it converts
    "unchecked" into "checked and wrong".

    @brief An empty fingerprint is not evidence of drift.
    @version 1
    """
    assert fr.source_fingerprint(tmp_path / "does-not-exist") == ""

    unknown = dict(MATCHING_CODE, source_fingerprint="", matches_source=True)
    assert _message(fr.notices(_status(), unknown), fr.AXIS_CODE) == ""

Activity · 3 steps
lines 391–391assert fr.source_fingerprint(tmp_path / "does-not-exist") == ""lines 393–393unknown = dict(MATCHING_CODE, source_fingerprint="", matches_source=True)lines 394–394assert _message(fr.notices(_status(), unknown), fr.AXIS_CODE) == ""

test_an_unstamped_index_raises_no_schema_axis

None test_freshness.test_an_unstamped_index_raises_no_schema_axis()

An index with no readable build version does not manufacture a schema notice.

tests/test_freshness.py:175

Show on the map →

Called by none

Calls _message, _status, notices

Checks

  • assert _message(fr.notices(_status(build_version=None), MATCHING_CODE), fr.AXIS_SCHEMA) == ""

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_an_unstamped_index_raises_no_schema_axis → notices
Source · 14 lines
def test_an_unstamped_index_raises_no_schema_axis() -> None:
    """`read_build_signature` returns None for an unreadable or unstamped database. That
    is "cannot tell", and comparing None against an int must not produce a confident
    claim about which side is newer.

    @brief A None build version is not a version skew.
    @version 1
    """
    assert _message(fr.notices(_status(build_version=None), MATCHING_CODE), fr.AXIS_SCHEMA) == ""


# ─── axis: data (gh#2, with gh#9's measured cost attached) ────────────────────

Activity · 1 steps
lines 183–183assert _message(fr.notices(_status(build_version=None), MATCHING_CODE), fr.AXIS_SCHEMA) == ""

test_an_untimed_target_says_the_cost_is_unmeasured

None test_freshness.test_an_untimed_target_says_the_cost_is_unmeasured()

With no timing history the data axis says so instead of inventing a number.

tests/test_freshness.py:229

Show on the map →

Called by none

Calls _message, _status, notices

Checks

  • assert "unmeasured" in message
  • assert "ms" not in message, "no number may appear where none was measured"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_an_untimed_target_says_the_cost_is_unmeasured → notices
Source · 16 lines
def test_an_untimed_target_says_the_cost_is_unmeasured() -> None:
    """A fabricated estimate presented as a measurement is the failure this repo has
    recorded more than any other — a `$0.5` placeholder whose own comment said it was
    not measured became an authoritative budget by being copied into prose. So an index
    predating the `refresh` section reports the absence, and reports it as an absence.

    @brief An untimed target admits the cost is unmeasured.
    @version 1
    """
    message = _message(
        fr.notices(_status(source_changed_files=1, stale=True), MATCHING_CODE), fr.AXIS_DATA
    )
    assert "unmeasured" in message
    assert "ms" not in message, "no number may appear where none was measured"

Activity · 3 steps
lines 238–240message = _message( fr.notices(_status(source_changed_files=1, stale=True), MATCHING_CODE), fr.AXIS_DATA )lines 241–241assert "unmeasured" in messagelines 242–242assert "ms" not in message, "no number may appear where none was measured"

test_bytecode_does_not_move_the_fingerprint

None test_freshness.test_bytecode_does_not_move_the_fingerprint(Path tmp_path)

A non- .py file does not move the fingerprint.

tests/test_freshness.py:433

Checks

  • assert fr.source_fingerprint(pkg) == before

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_bytecode_does_not_move_the_fingerprint → source_fingerprint
Source · 21 lines
def test_bytecode_does_not_move_the_fingerprint(tmp_path: Path) -> None:
    """`.pyc` is regenerated as a side effect of importing the very code being
    identified, and the house control procedure purges `__pycache__` between runs — so
    hashing bytecode would move the fingerprint because it was READ, and again because a
    control run cleaned up.

    @brief Only source files are fingerprinted.
    @version 1
    """
    pkg = tmp_path / "pkg"
    (pkg / "__pycache__").mkdir(parents=True)
    (pkg / "a.py").write_text("x = 1\n", encoding="utf-8")
    before = fr.source_fingerprint(pkg)

    (pkg / "__pycache__" / "a.cpython-312.pyc").write_bytes(b"\x00\x01")
    assert fr.source_fingerprint(pkg) == before


# ─── all three at once, and the ordering ──────────────────────────────────────

Activity · 6 steps
lines 442–442pkg = tmp_path / "pkg"lines 443–443(pkg / "__pycache__").mkdir(parents=True)lines 444–444(pkg / "a.py").write_text("x = 1\n", encoding="utf-8")lines 445–445before = fr.source_fingerprint(pkg)lines 447–447(pkg / "__pycache__" / "a.cpython-312.pyc").write_bytes(b"\x00\x01")lines 448–448assert fr.source_fingerprint(pkg) == before

test_every_axis_in_play_is_reported

None test_freshness.test_every_axis_in_play_is_reported()

Three simultaneous axes are all reported, in remedy order.

tests/test_freshness.py:457

Show on the map →

Called by none

Calls _status, notices

Checks

  • assert axes == [fr.AXIS_DATA, fr.AXIS_SCHEMA, fr.AXIS_CODE]

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_every_axis_in_play_is_reported → notices
Source · 18 lines
def test_every_axis_in_play_is_reported() -> None:
    """A real session can hold all three, and reporting only the first would hide the
    one that says no rebuild will help. The order is data → schema → code: cheapest and
    commonest remedy first, "nothing you can rebuild" last.

    @brief All active axes are reported in order.
    @version 1
    """
    status = _status(build_version=CURRENT + 1, source_changed_files=2, stale=True)
    code = dict(MATCHING_CODE, source_fingerprint="bbbbbbbbbbbb", matches_source=False)

    axes = [n["axis"] for n in fr.notices(status, code)]
    assert axes == [fr.AXIS_DATA, fr.AXIS_SCHEMA, fr.AXIS_CODE]


# ─── the persisted refresh cost (gh#9's pipeline half) ────────────────────────

Activity · 4 steps
lines 465–465status = _status(build_version=CURRENT + 1, source_changed_files=2, stale=True)lines 466–466code = dict(MATCHING_CODE, source_fingerprint="bbbbbbbbbbbb", matches_source=False)lines 468–468axes = [n["axis"] for n in fr.notices(status, code)]lines 469–469assert axes == [fr.AXIS_DATA, fr.AXIS_SCHEMA, fr.AXIS_CODE]

test_stamping_the_refresh_section_preserves_scope_and_version

None test_freshness.test_stamping_the_refresh_section_preserves_scope_and_version(Path tmp_path)

Stamping a refresh section leaves the other sections intact.

tests/test_freshness.py:527

Checks

  • assert status["scope"] == {"source": "doxygen-guard", "reason": "declared"}
  • assert status["refresh"] == {"duration_ms": "42"}
  • assert read_build_signature(db) == CLEW_BUILD_VERSION

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measuredtest_stamping_the_refresh_section_preserves_scope_and_version → db_status
REQ-DDB-CONFIG-007measuredtest_stamping_the_refresh_section_preserves_scope_and_version → db_status
REQ-DDB-INDEX-003measuredtest_stamping_the_refresh_section_preserves_scope_and_version → db_status → _coverage_meta
REQ-DDB-MCP-001measuredtest_stamping_the_refresh_section_preserves_scope_and_version → db_status
REQ-DDB-MCP-004measuredtest_stamping_the_refresh_section_preserves_scope_and_version → db_status
REQ-DDB-PIPE-005measuredtest_stamping_the_refresh_section_preserves_scope_and_version → write_build_signature
Source · 24 lines
def test_stamping_the_refresh_section_preserves_scope_and_version(tmp_path: Path) -> None:
    """The pipeline stamps `refresh.*` in a SECOND `write_build_signature` call, after
    the atomic swap and the HTML stage, so the duration covers the whole build. That is
    only safe because the write UPSERTS — if it replaced the table, this stamp would
    silently delete the scope provenance that the entropic grid measured as the only
    clearly actionable gap in 56 marks.

    @brief A second stamp does not clobber the first.
    @version 1
    """
    db = tmp_path / "clew.db"
    write_build_signature(db, scope={"source": "doxygen-guard", "reason": "declared"})
    write_build_signature(db, refresh={"duration_ms": "42"})

    target = st.Target(repo_path=str(tmp_path), slug="t", db_path=str(db))
    status = st.db_status(target)
    assert status["scope"] == {"source": "doxygen-guard", "reason": "declared"}
    assert status["refresh"] == {"duration_ms": "42"}
    assert read_build_signature(db) == CLEW_BUILD_VERSION


# ─── the query-reply annotation (gh#2's chosen mechanism) ─────────────────────

Activity · 8 steps
lines 537–537db = tmp_path / "clew.db"lines 538–538write_build_signature(db, scope={"source": "doxygen-guard", "reason": "declared"})lines 539–539write_build_signature(db, refresh={"duration_ms": "42"})lines 541–541target = st.Target(repo_path=str(tmp_path), slug="t", db_path=str(db))lines 542–542status = st.db_status(target)lines 543–543assert status["scope"] == {"source": "doxygen-guard", "reason": "declared"}lines 544–544assert status["refresh"] == {"duration_ms": "42"}lines 545–545assert read_build_signature(db) == CLEW_BUILD_VERSION

test_status_reports_the_real_package_version_not_the_unknown_fallback

None test_freshness.test_status_reports_the_real_package_version_not_the_unknown_fallback()

The version status reports must be the version the package actually declares.

tests/test_freshness.py:748

Show on the map →

Called by none

Calls _installed_editable, code_identity, package_version, require_toml_module

Checks

  • assert reported != "unknown", ("package_version() fell back to 'unknown'. Either the package is not installed in " f"this environment, or {pyproject.name} renamed the distribution and " "freshness._DISTRIBUTION was not updated with it — the exact defect that shipped." )
  • assert code_identity().get("package_version") == reported, ("code_identity() is what reaches a status reply; it must carry the same version" )
  • assert reported == want, (f"status would report package_version={reported!r} while pyproject declares {want!r}. " "This is a NON-EDITABLE install, so the code under test is the installed copy too — " "the whole run is exercising a version behind this working tree." )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_status_reports_the_real_package_version_not_the_unknown_fallback → code_identity
Source · 66 lines
def test_status_reports_the_real_package_version_not_the_unknown_fallback() -> None:
    """THIS SHIPPED THROUGH 1.0.0. `package_version()` asked `importlib.metadata` for
    `version("clew")` — the IMPORT name — while the distribution ships as `clew-trace`, so
    every `index(action='status')` reply reported `package_version: "unknown"`. That is the
    first field a consumer pastes into a bug report, and it named no version at all.

    NOTHING CAUGHT IT BECAUSE THE FALLBACK IS SILENT BY DESIGN. A failed metadata lookup
    returns the string "unknown" rather than raising, deliberately — it is called on the way
    out of replies that already succeeded — so the broken lookup renders as a plausible
    field value. The function's own docstring meanwhile claimed it could not drift from
    `pyproject.toml`, which was true of the version and false of the distribution name it
    passed. A defect that reads as a legitimate value needs a test asserting the value is
    legitimate; there is no error to notice.

    ASSERTED AGAINST `pyproject.toml`, NEVER A LITERAL. A hardcoded "1.0.0" here would be a
    third place to forget on the next release, which is the shape of the defect above.

    TWO ASSERTIONS, AND THEY ARE NOT THE SAME KIND OF THING. `!= "unknown"` is a property of
    the PRODUCT: a wheel's metadata and its pyproject are built from one source, so a real
    install can only disagree by looking up the wrong distribution name, which is the defect
    above. Equality with the working tree's pyproject is a property of the ENVIRONMENT, and
    what it means depends on how the package was installed:

      * NON-EDITABLE — the code under test is the installed copy, so a version behind the
        working tree means the whole suite is exercising stale code. A hard failure, and the
        most useful thing this test does for anyone running it that way.
      * EDITABLE — the code under test IS the working tree and only the `.dist-info` is
        behind. Nothing about the run is stale; the version bump simply has not been
        reinstalled. Failing here says "reinstall" while reporting it as a version defect,
        and it turned a routine release bump into a red suite.

    So the mode is MEASURED rather than assumed, from PEP 610's `direct_url.json`. Absent or
    unreadable means NOT editable, which keeps the strict assertion as the default: an
    install shape this cannot recognise fails loudly instead of quietly loosening.

    @brief `package_version()` is never the fallback, and matches pyproject unless editable.
    @return None.
    @version 2
    """
    from clew.mcp_server.freshness import code_identity, package_version
    from clew.tomlcompat import require_toml_module

    pyproject = Path(__file__).resolve().parent.parent / "pyproject.toml"
    declared = require_toml_module().loads(pyproject.read_text(encoding="utf-8"))
    want = declared["project"]["version"]

    reported = package_version()
    assert reported != "unknown", (
        "package_version() fell back to 'unknown'. Either the package is not installed in "
        f"this environment, or {pyproject.name} renamed the distribution and "
        "freshness._DISTRIBUTION was not updated with it — the exact defect that shipped."
    )
    ## THROUGH `code_identity` TOO, because that is the payload `status` actually serves.
    ## Asserting only on the helper would leave a wrapper free to drop or rename the field.
    assert code_identity().get("package_version") == reported, (
        "code_identity() is what reaches a status reply; it must carry the same version"
    )
    if _installed_editable():
        return
    assert reported == want, (
        f"status would report package_version={reported!r} while pyproject declares {want!r}. "
        "This is a NON-EDITABLE install, so the code under test is the installed copy too — "
        "the whole run is exercising a version behind this working tree."
    )

Activity · 11 steps
lines 787–787from clew.mcp_server.freshness import code_identity, package_versionlines 788–788from clew.tomlcompat import require_toml_modulelines 790–790pyproject = Path(__file__).resolve().parent.parent / "pyproject.toml"lines 791–791declared = require_toml_module().loads(pyproject.read_text(encoding="utf-8"))lines 792–792want = declared["project"]["version"]lines 794–794reported = package_version()lines 795–799assert reported != "unknown", ( "package_version() fell back to 'unknown'. Either the package is not installed in " f"this environment, or {pyproject.name} renamed the distribution and " "freshness._DISTRIBUTION was not updated with it — the exact defect that shipped." )lines 802–804assert code_identity().get("package_version") == reported, ( "code_identity() is what reaches a status reply; it must carry the same version" )lines 805–805◇ if _installed_editable()lines 806–806returnlines 807–811assert reported == want, ( f"status would report package_version={reported!r} while pyproject declares {want!r}. " "This is a NON-EDITABLE install, so the code under test is the installed copy too — " "the whole run is exercising a version behind this working tree." )

test_the_code_axis_fires_when_the_source_moves_under_the_process

None test_freshness.test_the_code_axis_fires_when_the_source_moves_under_the_process()

The code axis fires when the source moved under the running process.

tests/test_freshness.py:292

Show on the map →

Called by none

Calls _message, _status, notices

Checks

  • assert "aaaaaaaaaaaa" in message and "bbbbbbbbbbbb" in message
  • assert "restart" in message.lower(), "only a client restart replaces loaded modules"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_the_code_axis_fires_when_the_source_moves_under_the_process → notices
Source · 16 lines
def test_the_code_axis_fires_when_the_source_moves_under_the_process() -> None:
    """The axis that had NO signal and whose available signal pointed the other way: a
    fix lands, `status` says `stale: false` — truthfully, about the data axis — and the
    query returns the pre-fix payload byte-for-byte. It has cost this loop three
    debugging sessions.

    @brief Disagreeing fingerprints raise the code axis.
    @version 1
    """
    code = dict(MATCHING_CODE, source_fingerprint="bbbbbbbbbbbb", matches_source=False)

    message = _message(fr.notices(_status(), code), fr.AXIS_CODE)
    assert "aaaaaaaaaaaa" in message and "bbbbbbbbbbbb" in message
    assert "restart" in message.lower(), "only a client restart replaces loaded modules"

Activity · 4 steps
lines 301–301code = dict(MATCHING_CODE, source_fingerprint="bbbbbbbbbbbb", matches_source=False)lines 303–303message = _message(fr.notices(_status(), code), fr.AXIS_CODE)lines 304–304assert "aaaaaaaaaaaa" in message and "bbbbbbbbbbbb" in messagelines 305–305assert "restart" in message.lower(), "only a client restart replaces loaded modules"

test_the_code_axis_says_a_build_through_it_is_refused

None test_freshness.test_the_code_axis_says_a_build_through_it_is_refused()

The code axis must ALSO say that building through this process is refused.

tests/test_freshness.py:332

Show on the map →

Called by none

Calls _message, _status, notices

Checks

  • assert "refused" in message.lower(), "a stale process must not be invited to build"
  • assert "DROP WHOLE LAYERS" in message, "name the consequence, not just the prohibition"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_the_code_axis_says_a_build_through_it_is_refused → notices
Source · 21 lines
def test_the_code_axis_says_a_build_through_it_is_refused() -> None:
    """THE OTHER HALF OF THE SAME SENTENCE, and the half whose absence was measured
    (gh#348). The message used to read "The DATA is not affected", full stop — TRUE FOR
    READS, FALSE FOR WRITES. A build-30 process rebuilt a build-32 index AT 30, the
    `external` stage vanished from the stage list, and `status` then reported
    `stale: false, build_version: 30` — perfectly healthy, having just destroyed a layer.

    The reader was TOLD not to worry by the very notice that should have stopped them, so
    the read exemption above and this refusal have to travel together. Testing only the
    exemption is what let the wrong half ship pinned.

    @brief The code axis states the write hazard, not only the read exemption.
    @version 1
    """
    code = dict(MATCHING_CODE, source_fingerprint="bbbbbbbbbbbb", matches_source=False)

    message = _message(fr.notices(_status(), code), fr.AXIS_CODE)
    assert "refused" in message.lower(), "a stale process must not be invited to build"
    assert "DROP WHOLE LAYERS" in message, "name the consequence, not just the prohibition"

Activity · 4 steps
lines 346–346code = dict(MATCHING_CODE, source_fingerprint="bbbbbbbbbbbb", matches_source=False)lines 348–348message = _message(fr.notices(_status(), code), fr.AXIS_CODE)lines 349–349assert "refused" in message.lower(), "a stale process must not be invited to build"lines 350–350assert "DROP WHOLE LAYERS" in message, "name the consequence, not just the prohibition"

test_the_code_axis_says_the_data_is_still_current

None test_freshness.test_the_code_axis_says_the_data_is_still_current()

The code axis must not let a reader conclude the DATA is stale.

tests/test_freshness.py:311

Show on the map →

Called by none

Calls _message, _status, notices

Checks

  • assert "READS are not affected" in message
  • assert "read" in message and "live" in message
  • assert "rebuild cannot fix this" in message

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_the_code_axis_says_the_data_is_still_current → notices
Source · 18 lines
def test_the_code_axis_says_the_data_is_still_current() -> None:
    """MEASURED, and the reason the wording is pinned by a test: query tools open the
    database per call, so newly-added symbols appear immediately even while the process
    runs old logic. Saying "the server is stale" without that qualification trades one
    wrong conclusion for the opposite one, and would send someone rebuilding an index
    that was never the problem.

    @brief The code axis exempts the data explicitly.
    @version 1
    """
    code = dict(MATCHING_CODE, source_fingerprint="bbbbbbbbbbbb", matches_source=False)

    message = _message(fr.notices(_status(), code), fr.AXIS_CODE)
    assert "READS are not affected" in message
    assert "read" in message and "live" in message
    assert "rebuild cannot fix this" in message

Activity · 5 steps
lines 321–321code = dict(MATCHING_CODE, source_fingerprint="bbbbbbbbbbbb", matches_source=False)lines 323–323message = _message(fr.notices(_status(), code), fr.AXIS_CODE)lines 324–324assert "READS are not affected" in messagelines 325–325assert "read" in message and "live" in messagelines 326–326assert "rebuild cannot fix this" in message

test_the_data_axis_quotes_the_measured_refresh_cost

None test_freshness.test_the_data_axis_quotes_the_measured_refresh_cost()

Source drift raises the data axis and quotes the MEASURED cost of fixing it.

tests/test_freshness.py:192

Show on the map →

Called by none

Calls _message, _status, notices

Checks

  • assert "5 indexed source file(s)" in message
  • assert "tools_query.py" in message, "naming the newest changed file makes it checkable"
  • assert "3314 ms" in message, "the cost must be the measured one"
  • assert "70 cached stage payload(s)" in message
  • assert "70 file(s)" not in message, "the payload count must not be reported as a file count"
  • assert message.count("file(s)") == 1, (f"exactly one file count belongs in this notice, the changed-source one; got: {message}" )
  • assert "index(action='refresh'" in message, "the action that clears this axis must be named"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_the_data_axis_quotes_the_measured_refresh_cost → notices
Source · 34 lines
def test_the_data_axis_quotes_the_measured_refresh_cost() -> None:
    """gh#9's whole argument in one assertion: an agent that cannot measure the
    correction must estimate it, and it estimates badly — Q7 and Q8 are the only two
    questions where the index arm scored BELOW reading source, and Q8 is the worst
    result in the matrix. The number must come from THIS target's history, so it is
    quoted from the persisted `refresh` block rather than from a constant.

    @brief The data axis carries the measured cost.
    @version 1
    """
    status = _status(
        source_changed_files=5,
        newest_changed_source="clew/mcp_server/tools_query.py",
        stale=True,
        refresh={"duration_ms": "3314", "payloads_recomputed": "70"},
    )

    message = _message(fr.notices(status, MATCHING_CODE), fr.AXIS_DATA)
    assert "5 indexed source file(s)" in message
    assert "tools_query.py" in message, "naming the newest changed file makes it checkable"
    assert "3314 ms" in message, "the cost must be the measured one"
    assert "70 cached stage payload(s)" in message
    ## #470 IN ONE ASSERTION. This notice reports BOTH numbers, and the payload count is normally
    ## several times the file count because there are ~10 stages. Calling it "70 file(s)" beside
    ## "5 indexed source file(s)" read as a contradiction — the same notice claiming 5 files
    ## changed and 70 files reprocessed — when both numbers were right and only one label was
    ## wrong. So no second "file(s)" count may appear here.
    assert "70 file(s)" not in message, "the payload count must not be reported as a file count"
    assert message.count("file(s)") == 1, (
        f"exactly one file count belongs in this notice, the changed-source one; got: {message}"
    )
    assert "index(action='refresh'" in message, "the action that clears this axis must be named"

Activity · 9 steps
lines 202–207status = _status( source_changed_files=5, newest_changed_source="clew/mcp_server/tools_query.py", stale=True, refresh={"duration_ms": "3314", "payloads_recomputed": "70"}, )lines 209–209message = _message(fr.notices(status, MATCHING_CODE), fr.AXIS_DATA)lines 210–210assert "5 indexed source file(s)" in messagelines 211–211assert "tools_query.py" in message, "naming the newest changed file makes it checkable"lines 212–212assert "3314 ms" in message, "the cost must be the measured one"lines 213–213assert "70 cached stage payload(s)" in messagelines 219–219assert "70 file(s)" not in message, "the payload count must not be reported as a file count"lines 220–222assert message.count("file(s)") == 1, ( f"exactly one file count belongs in this notice, the changed-source one; got: {message}" )lines 223–223assert "index(action='refresh'" in message, "the action that clears this axis must be named"

test_the_editable_probe_defaults_to_strict

None test_freshness.test_the_editable_probe_defaults_to_strict()

The editable probe must not answer True for a normal install.

tests/test_freshness.py:818

Show on the map →

Called by none

Calls _editable_from, _installed_editable

Checks

  • assert _editable_from(None) is False, "a PyPI wheel writes no direct_url.json at all"
  • assert _editable_from('{"url": "file:///src", "dir_info": {}}') is False, ("a local non-editable install writes the file without the flag" )
  • assert _editable_from("not json at all") is False, "unparseable provenance is not proof"
  • assert _editable_from('{"dir_info": {"editable": true}}') is True
  • assert _installed_editable() is True, "this repository is installed with `pip install -e`"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004catalog
Source · 25 lines
def test_the_editable_probe_defaults_to_strict() -> None:
    """WHAT THIS PROTECTS is the assertion above, not any product behaviour. A probe that
    drifted to True everywhere would disable the stale-installed-code check silently and
    leave the test passing — the same shape as the "unknown" fallback it sits beside: a
    weakened check that still renders as a pass.

    The three shapes are exactly what pip writes. Only the third is editable, and the two
    that are not must both come back strict.

    @brief Absent and unflagged provenance both read as non-editable.
    @return None.
    @version 1
    """
    assert _editable_from(None) is False, "a PyPI wheel writes no direct_url.json at all"
    assert _editable_from('{"url": "file:///src", "dir_info": {}}') is False, (
        "a local non-editable install writes the file without the flag"
    )
    assert _editable_from("not json at all") is False, "unparseable provenance is not proof"
    assert _editable_from('{"dir_info": {"editable": true}}') is True

    ## AND IT IS TRUE HERE, which is what makes the assertion above meaningful rather than
    ## vacuous: this checkout IS editable, so the relaxed branch is the one being exercised.
    assert _installed_editable() is True, "this repository is installed with `pip install -e`"

Activity · 5 steps
lines 831–831assert _editable_from(None) is False, "a PyPI wheel writes no direct_url.json at all"lines 832–834assert _editable_from('{"url": "file:///src", "dir_info": {}}') is False, ( "a local non-editable install writes the file without the flag" )lines 835–835assert _editable_from("not json at all") is False, "unparseable provenance is not proof"lines 836–836assert _editable_from('{"dir_info": {"editable": true}}') is Truelines 840–840assert _installed_editable() is True, "this repository is installed with `pip install -e`"

test_the_fingerprint_tracks_the_source_tree

None test_freshness.test_the_fingerprint_tracks_the_source_tree(Path tmp_path)

The fingerprint moves when a source file is touched, and holds when it is not.

tests/test_freshness.py:401

Checks

  • assert before, "a readable tree must fingerprint"
  • assert fr.source_fingerprint(pkg) == before, "an untouched tree must not drift"
  • assert fr.source_fingerprint(pkg) != before, "an edited file must move the fingerprint"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_the_fingerprint_tracks_the_source_tree → source_fingerprint
Source · 28 lines
def test_the_fingerprint_tracks_the_source_tree(tmp_path: Path) -> None:
    """Both halves matter. A fingerprint that never changes cannot detect drift; one
    that changes when nothing did makes the code axis fire permanently, which is the
    same failure as no signal at all.

    SENSITIVITY IS TO CONTENT, NOT MTIME, and this test used to assert the opposite —
    "a touched file must move the fingerprint" — which contradicted the sentence directly
    above it in its own docstring. An mtime key fires on `git checkout`, a branch switch
    and plain `touch`, all byte-identical, and because the code axis is a hard refusal
    that no rebuild clears, those spurious trips disabled the query-time auto-refresh
    entirely. `test_the_source_fingerprint_ignores_mtime_and_tracks_content` covers the
    stability half against a touch specifically.

    @brief The fingerprint is sensitive and stable.
    @version 2
    """
    pkg = tmp_path / "pkg"
    pkg.mkdir()
    (pkg / "a.py").write_text("x = 1\n", encoding="utf-8")

    before = fr.source_fingerprint(pkg)
    assert before, "a readable tree must fingerprint"
    assert fr.source_fingerprint(pkg) == before, "an untouched tree must not drift"

    (pkg / "a.py").write_text("x = 2\n", encoding="utf-8")
    assert fr.source_fingerprint(pkg) != before, "an edited file must move the fingerprint"

Activity · 8 steps
lines 417–417pkg = tmp_path / "pkg"lines 418–418pkg.mkdir()lines 419–419(pkg / "a.py").write_text("x = 1\n", encoding="utf-8")lines 421–421before = fr.source_fingerprint(pkg)lines 422–422assert before, "a readable tree must fingerprint"lines 423–423assert fr.source_fingerprint(pkg) == before, "an untouched tree must not drift"lines 425–425(pkg / "a.py").write_text("x = 2\n", encoding="utf-8")lines 426–426assert fr.source_fingerprint(pkg) != before, "an edited file must move the fingerprint"

test_the_pre_rename_cost_key_is_still_read

None test_freshness.test_the_pre_rename_cost_key_is_still_read()

An index built before the #470 rename still reports its measured cost.

tests/test_freshness.py:264

Checks

  • assert "1612 ms" in clause
  • assert "45 cached stage payload(s)" in clause, (f"the legacy key must still be read, and reported under the CORRECTED label — the old " f"name was wrong about the unit, not about the number: {clause}" )
  • assert "file(s)" not in clause, "the corrected label applies to legacy values too"

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004catalog
Source · 25 lines
def test_the_pre_rename_cost_key_is_still_read() -> None:
    """#470 renamed the persisted key `files_reprocessed` to `payloads_recomputed` because the old
    name named the wrong UNIT. An index built by an earlier version carries only the old key, and
    dropping to "unmeasured" there would discard a real measurement over a spelling.

    WITHOUT THIS TEST THE FALLBACK IS UNTESTED CODE, which is how it gets deleted as dead. The
    build-version bump makes such an index rare rather than impossible: a stale index is READ
    live and only rebuilt when something asks for a build.

    @brief The legacy key is honoured, under the corrected label.
    @return None.
    @version 1
    """
    clause = fr._cost_clause({"duration_ms": "1612", "files_reprocessed": "45"})
    assert "1612 ms" in clause
    assert "45 cached stage payload(s)" in clause, (
        f"the legacy key must still be read, and reported under the CORRECTED label — the old "
        f"name was wrong about the unit, not about the number: {clause}"
    )
    assert "file(s)" not in clause, "the corrected label applies to legacy values too"


# ─── axis: code (gh#29's misleading half) ────────────────────────────────────

Activity · 4 steps
lines 277–277clause = fr._cost_clause({"duration_ms": "1612", "files_reprocessed": "45"})lines 278–278assert "1612 ms" in clauselines 279–282assert "45 cached stage payload(s)" in clause, ( f"the legacy key must still be read, and reported under the CORRECTED label — the old " f"name was wrong about the unit, not about the number: {clause}" )lines 283–283assert "file(s)" not in clause, "the corrected label applies to legacy values too"

test_the_refresh_cost_round_trips_into_status

None test_freshness.test_the_refresh_cost_round_trips_into_status(Path tmp_path)

A refresh section round-trips through build_meta into db_status.

tests/test_freshness.py:479

Checks

  • assert refresh == {"duration_ms": "1612", "payloads_recomputed": "3", "cache_hits": "111"}

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-CONFIG-006measuredtest_the_refresh_cost_round_trips_into_status → db_status
REQ-DDB-CONFIG-007measuredtest_the_refresh_cost_round_trips_into_status → db_status
REQ-DDB-INDEX-003measuredtest_the_refresh_cost_round_trips_into_status → db_status → _coverage_meta
REQ-DDB-MCP-001measuredtest_the_refresh_cost_round_trips_into_status → db_status
REQ-DDB-MCP-004measuredtest_the_refresh_cost_round_trips_into_status → db_status
REQ-DDB-PIPE-005measuredtest_the_refresh_cost_round_trips_into_status → write_build_signature
Source · 21 lines
def test_the_refresh_cost_round_trips_into_status(tmp_path: Path) -> None:
    """The path that makes the estimate grounded in this target's own history: the
    pipeline stamps it, `_refresh_meta` reads it back, `db_status` publishes it.

    @brief Refresh metrics reach db_status.
    @version 1
    """
    db = tmp_path / "clew.db"
    conn = sqlite3.connect(db)
    conn.execute("CREATE TABLE memberdef (id INTEGER)")
    conn.commit()
    conn.close()
    write_build_signature(
        db, refresh={"duration_ms": "1612", "payloads_recomputed": "3", "cache_hits": "111"}
    )

    target = st.Target(repo_path=str(tmp_path), slug="t", db_path=str(db))
    refresh = st.db_status(target)["refresh"]
    assert refresh == {"duration_ms": "1612", "payloads_recomputed": "3", "cache_hits": "111"}

Activity · 9 steps
lines 486–486db = tmp_path / "clew.db"lines 487–487conn = sqlite3.connect(db)lines 488–488conn.execute("CREATE TABLE memberdef (id INTEGER)")lines 489–489conn.commit()lines 490–490conn.close()lines 491–493write_build_signature( db, refresh={"duration_ms": "1612", "payloads_recomputed": "3", "cache_hits": "111"} )lines 495–495target = st.Target(repo_path=str(tmp_path), slug="t", db_path=str(db))lines 496–496refresh = st.db_status(target)["refresh"]lines 497–497assert refresh == {"duration_ms": "1612", "payloads_recomputed": "3", "cache_hits": "111"}

test_the_source_fingerprint_ignores_mtime_and_tracks_content

None test_freshness.test_the_source_fingerprint_ignores_mtime_and_tracks_content(Path tmp_path)

A touch with no edit must not move the source fingerprint.

tests/test_freshness.py:848

Checks

  • assert before, "a package with .py files must fingerprint to something"
  • assert fr.source_fingerprint(pkg) == before, ("a touch with identical content moved the fingerprint, so the code axis fires on " "every git checkout and branch switch and disables auto-refresh with no edit at all" )
  • assert fr.source_fingerprint(pkg) != before, ("a real content edit did NOT move the fingerprint — the axis can no longer detect " "the stale process it exists to catch, which is worse than firing too often" )

Result: passed

Verifies

requirementlinkedpath to the implementer
REQ-DDB-MCP-004measuredtest_the_source_fingerprint_ignores_mtime_and_tracks_content → source_fingerprint
Source · 48 lines
def test_the_source_fingerprint_ignores_mtime_and_tracks_content(tmp_path: Path) -> None:
    """THE CODE AXIS IS A HARD REFUSAL, so a false positive on it is expensive.

    `matches_source` false blocks the automatic query-time refresh AND refuses an explicit
    build, and no rebuild clears it — only restarting the client does. So anything that trips
    it spuriously disables both, silently, until someone reconnects.

    An mtime-keyed digest trips on `git checkout`, a branch switch, `git stash pop`, rsync and
    plain `touch`, all of which leave byte-identical content. MEASURED LIVE in this
    repository: reverting one file with `git checkout` moved the fingerprint and the code axis
    fired on the next two query replies, which is what stopped the auto-refresh from ever
    engaging here.

    The sibling `IndexCache` already states the correct rule for this codebase — mtime+size is
    a PREFILTER and the sha256 of the bytes is the AUTHORITY, so a touch with no edit and a
    checkout that restores identical content both stay HITS. This pins the same rule for the
    fingerprint.

    The cost objection was measured rather than argued: 90 files and 2.6 MB hash in 4.0 ms
    against 2.2 ms for stat-only, so content costs 1.8 ms on a surface called once per reply.

    @brief A touch is invisible; an edit is not.
    @return None.
    @version 1
    """
    pkg = tmp_path / "pkg"
    pkg.mkdir()
    (pkg / "a.py").write_text("x = 1\n", encoding="utf-8")
    (pkg / "b.py").write_text("y = 2\n", encoding="utf-8")

    before = fr.source_fingerprint(pkg)
    assert before, "a package with .py files must fingerprint to something"

    ## A touch far in the future, so this cannot pass by the mtime happening to land in the
    ## same nanosecond — the masking that makes this class of test lie.
    os.utime(pkg / "a.py", ns=(10**18, 10**18))
    assert fr.source_fingerprint(pkg) == before, (
        "a touch with identical content moved the fingerprint, so the code axis fires on "
        "every git checkout and branch switch and disables auto-refresh with no edit at all"
    )

    (pkg / "a.py").write_text("x = 2\n", encoding="utf-8")
    assert fr.source_fingerprint(pkg) != before, (
        "a real content edit did NOT move the fingerprint — the axis can no longer detect "
        "the stale process it exists to catch, which is worse than firing too often"
    )

Activity · 10 steps
lines 873–873pkg = tmp_path / "pkg"lines 874–874pkg.mkdir()lines 875–875(pkg / "a.py").write_text("x = 1\n", encoding="utf-8")lines 876–876(pkg / "b.py").write_text("y = 2\n", encoding="utf-8")lines 878–878before = fr.source_fingerprint(pkg)lines 879–879assert before, "a package with .py files must fingerprint to something"lines 883–883os.utime(pkg / "a.py", ns=(10**18, 10**18))lines 884–887assert fr.source_fingerprint(pkg) == before, ( "a touch with identical content moved the fingerprint, so the code axis fires on " "every git checkout and branch switch and disables auto-refresh with no edit at all" )lines 889–889(pkg / "a.py").write_text("x = 2\n", encoding="utf-8")lines 890–893assert fr.source_fingerprint(pkg) != before, ( "a real content edit did NOT move the fingerprint — the axis can no longer detect " "the stale process it exists to catch, which is worse than firing too often" )