freshness.py

clew/mcp_server/freshness.py

THREE AXES OF STALENESS, INTERPRETED — the tool describing its own currency.

_code_notice

dict[str, str] | None clew.mcp_server.freshness._code_notice(Mapping[str, object] code)

The code-axis notice, when the source moved under a running process.

clew/mcp_server/freshness.py:527

Show on the map →

Called by notices

Calls none

Source · 37 lines
def _code_notice(code: Mapping[str, object]) -> dict[str, str] | None:
    """THE AXIS THAT HAD NO SIGNAL AT ALL, and whose available signal pointed the other
    way (gh#29). It has now cost this loop three separate debugging sessions: a fix
    lands, `status` reports `stale: false`, and the query returns the pre-fix payload
    byte-for-byte, so an agent cannot distinguish "my fix did not work" from "the server
    has not loaded my fix".

    The message is careful in THREE directions now. It must not let anyone conclude their
    fix failed; it must not let anyone conclude the DATA is stale, because the query tools
    open the database per call and are current, which was measured; and — gh#348 — it must
    not let anyone conclude a REBUILD is safe, because it is not. The first two were here
    already. The third is the one whose absence cost a layer: the message said the data was
    unaffected, full stop, and was read as reassurance by someone about to write.

    Only logic and module-level constants are old, and only a client restart replaces them
    — this deliberately does not hot-reload modules, which is a bad idea and was not asked
    for.

    @brief Build the code-axis notice.
    @return The notice, or None.
    @version 2
    """
    if code.get("matches_source"):
        return None
    return {
        "axis": AXIS_CODE,
        "message": (
            f"This server process loaded clew {code.get('package_version')} at "
            f"launch and the package source has changed since "
            f"(fingerprint {code.get('process_fingerprint')} on disk now "
            f"{code.get('source_fingerprint')}), so its LOGIC and module-level constants "
            f"may predate the working tree. {_READ_EXEMPTION} {_WRITE_HAZARD} A rebuild "
            "cannot fix this: restart the MCP client to load the current code."
        ),
    }

Activity · 3 steps
lines 549–549◇ if code.get("matches_source")lines 550–550return Nonelines 551–561return { "axis": AXIS_CODE, "message": ( f"This server process loaded clew {code.get('package_version')} at " f"launch and the package source has changed since " f"(fingerprint {code.get('process_fingerprint')} on disk now " f"{code.get('source_fingerprint')}), so its LOGIC and module-level constants " f"may predate the working tree. {_READ_EXEMPTION} {_WRITE_HAZARD} A rebuild " "cannot fix this: restart the MCP client to load the current code." ), }

Flows

_cost_clause

str clew.mcp_server.freshness._cost_clause(Mapping[str, str]|None refresh)

Human phrasing for what a refresh of this target last cost.

clew/mcp_server/freshness.py:304

Show on the map →

Called by _data_notice, test_an_index_without_stage_timings_attributes_nothing, test_an_untimed_target_is_still_reported_as_unmeasured, test_the_cache_hits_are_reported_beside_the_recomputed_count, test_the_clause_names_the_stage_that_dominated, test_the_cost_clause_no_longer_quotes_bare_milliseconds, test_the_cost_is_not_attributed_to_the_payload_count

Tested by

2 teststest_a_zero_duration_reads_as_measured_not_as_missing, test_the_pre_rename_cost_key_is_still_read

Calls _dominant_clause, _humanise_ms

Source · 41 lines
def _cost_clause(refresh: Mapping[str, str] | None) -> str:
    """GROUNDED IN THIS TARGET'S OWN HISTORY, not a constant (gh#9). An agent that
    cannot measure the correction must estimate it, and it estimates badly — that is
    the whole of Q8, the worst result in the acceptance matrix.

    Says so plainly when there is no history, rather than falling back to a
    representative number. A fabricated estimate presented as a measurement is the
    failure this repo has recorded most often.

    IN UNITS A READER ACTS ON. This said "506974 ms", which is eight and a half minutes and
    does not scan like it — the tool recommended a refresh and then priced it in a unit that
    reads as small. That exact number sat in a real target's metadata while the operator's
    stated bar was ten minutes, and nobody noticed the two were in tension.

    @brief Phrase the measured cost-to-refresh.
    @return Cost clause.
    @version 4
    """
    duration = (refresh or {}).get("duration_ms")
    if not duration:
        return "no refresh of this target has been timed yet, so the cost is unmeasured"
    spelled = _humanise_ms(duration)
    ## NOT "file(s)" (#470). This number counts (file, stage) PAYLOADS recomputed, and there are
    ## ~10 stages, so it is normally several times the changed-file count. Printed as files it
    ## landed in the same notice as "18 source file(s) have changed" and read as a broken counter
    ## — or worse, as the refresh doing four times the necessary work. `files_reprocessed` is
    ## still read so an index built before the rename keeps reporting its cost.
    payloads = (refresh or {}).get("payloads_recomputed") or (refresh or {}).get(
        "files_reprocessed"
    )
    ## SEPARATE CLAUSES, NOT ONE CAUSAL ONE (gh#10). This read "measured 38 s recomputing 18
    ## cached stage payload(s)", which says the 38 seconds went on the 18 payloads. On the
    ## target it was measured from, 13,509 payloads were cache HITS, 18 were recomputed, and
    ## 66% of the time was doxygen — which the payload cache does not cover at all. Both
    ## numbers were right; the sentence joining them was the defect.
    hits = (refresh or {}).get("cache_hits")
    served = f" and {hits} served from cache" if hits else ""
    work = f"; {payloads} cached stage payload(s) recomputed{served}" if payloads else ""
    return f"the last refresh of this target measured {spelled}{_dominant_clause(refresh)}{work}"

Activity · 9 steps
lines 322–322duration = (refresh or {}).get("duration_ms")lines 323–323◇ if not durationlines 324–324return "no refresh of this target has been timed yet, so the cost is unmeasured"lines 325–325spelled = _humanise_ms(duration)lines 331–333payloads = (refresh or {}).get("payloads_recomputed") or (refresh or {}).get( "files_reprocessed" )lines 339–339hits = (refresh or {}).get("cache_hits")lines 340–340served = f" and {hits} served from cache" if hits else ""lines 341–341work = f"; {payloads} cached stage payload(s) recomputed{served}" if payloads else ""lines 342–342return f"the last refresh of this target measured {spelled}{_dominant_clause(refresh)}{work}"

Flows

_data_notice

dict[str, str] | None clew.mcp_server.freshness._data_notice(Mapping[str, object] status)

The data-axis notice, when the sources have drifted.

clew/mcp_server/freshness.py:390

Source · 26 lines
def _data_notice(status: Mapping[str, object]) -> dict[str, str] | None:
    """Fires on `source_changed_files`, which `db_status` has measured correctly all
    along — this only says what to DO about it, with the cost attached so the decision
    is informed rather than guessed.

    @brief Build the data-axis notice.
    @return The notice, or None.
    @version 2
    """
    changed = status.get("source_changed_files") or 0
    if not isinstance(changed, int) or changed <= 0:
        return None
    newest = status.get("newest_changed_source")
    where = f" (most recently {newest})" if newest else ""
    refresh = status.get("refresh")
    cost = _cost_clause(refresh if isinstance(refresh, Mapping) else None)
    return {
        "axis": AXIS_DATA,
        "message": (
            f"{changed} indexed source file(s) have changed since this index was built"
            f"{where}, so an answer may describe code that no longer exists. Call "
            f"index(action='refresh') to correct it — {cost}."
        ),
    }

Activity · 8 steps
lines 399–399changed = status.get("source_changed_files") or 0lines 400–400◇ if not isinstance(changed, int) or changed <= 0lines 401–401return Nonelines 402–402newest = status.get("newest_changed_source")lines 403–403where = f" (most recently {newest})" if newest else ""lines 404–404refresh = status.get("refresh")lines 405–405cost = _cost_clause(refresh if isinstance(refresh, Mapping) else None)lines 406–413return { "axis": AXIS_DATA, "message": ( f"{changed} indexed source file(s) have changed since this index was built" f"{where}, so an answer may describe code that no longer exists. Call " f"index(action='refresh') to correct it — {cost}." ), }

Flows

_derived_notice

dict[str, str] | None clew.mcp_server.freshness._derived_notice(Mapping[str, object] status)

The derived-axis notice, while a fast in-place refresh awaits its full refresh.

clew/mcp_server/freshness.py:455

Show on the map →

Called by notices

Calls none

Source · 29 lines
def _derived_notice(status: Mapping[str, object]) -> dict[str, str] | None:
    """NAMES THE FILES AND THE LAYERS, because both decide what a reader may trust: the edited
    files' symbols, bodies and outgoing calls are current; the named whole-index layers (and any
    answer built from them — callers reaching INTO those files, reachability, threads) still
    describe the code before the edit.

    THE REMEDY IS TIME, OR A REFRESH. The server starts the full refresh itself, so asking again
    shortly is usually enough; `index(action='refresh')` forces it.

    @brief Build the derived-axis notice.
    @return The notice, or None.
    @version 1
    """
    fast = status.get("fast")
    if not isinstance(fast, Mapping) or str(fast.get("pending")) != "1":
        return None
    files = str(fast.get("files") or "the edited files")
    layers = str(fast.get("layers") or "the whole-index layers").replace(",", ", ")
    return {
        "axis": AXIS_DERIVED,
        "message": (
            f"this index was updated in place for {files}: those files' own symbols, bodies and "
            f"outgoing calls are current, but {layers} — and anything built from them, such as "
            f"callers reaching into those files — still describe the code BEFORE that edit. A "
            f"full refresh completes this; ask again shortly, or call index(action='refresh')."
        ),
    }

Activity · 6 steps
lines 468–468fast = status.get("fast")lines 469–469◇ if not isinstance(fast, Mapping) or str(fast.get("pending")) != "1"lines 470–470return Nonelines 471–471files = str(fast.get("files") or "the edited files")lines 472–472layers = str(fast.get("layers") or "the whole-index layers").replace(",", ", ")lines 473–481return { "axis": AXIS_DERIVED, "message": ( f"this index was updated in place for {files}: those files' own symbols, bodies and " f"outgoing calls are current, but {layers} — and anything built from them, such as " f"callers reaching into those files — still describe the code BEFORE that edit. A " f"full refresh completes this; ask again shortly, or call index(action='refresh')." ), }

Flows

_dominant_clause

str clew.mcp_server.freshness._dominant_clause(Mapping[str, str]|None refresh)

Name the stage that dominated a refresh, from that refresh's own timings.

clew/mcp_server/freshness.py:350

Source · 35 lines
def _dominant_clause(refresh: Mapping[str, str] | None) -> str:
    """WHAT A READER NEEDS IN ORDER TO ACT. The duration says whether to run a refresh; the
    dominant stage says what would change it — and that trimming the changed-file set will
    not, because doxygen's xref pass is global. The README's whole argument for making refresh
    cost legible is that an agent which believes correction is expensive stops correcting and
    then reasons from a stale index; a cost attributed to the wrong cause serves that badly.

    READ FROM THIS TARGET'S OWN STAGE TIMINGS, never a constant. An index built before the
    timings were recorded returns '' — naming a typical stage would be the fabricated
    measurement this module's sibling calls the repo's most-recorded failure.

    REPORTED ONLY WHEN ONE STAGE ACTUALLY DOMINATES. Below a third of the total no single
    stage explains the cost, and pointing at the largest of many similar ones would invite a
    reader to optimise something that is not the problem.

    @brief The dominant-stage clause for a measured refresh.
    @return The clause, or ''.
    @version 1
    """
    raw = (refresh or {}).get("stages")
    if not raw:
        return ""
    timings: dict[str, int] = {}
    for pair in str(raw).split():
        stage, _, value = pair.partition("=")
        if value.isdigit():
            timings[stage] = int(value)
    total = sum(timings.values())
    if not total:
        return ""
    stage, spent = max(timings.items(), key=lambda kv: kv[1])
    share = round(100 * spent / total)
    return f", {share}% of it {stage}" if share >= _DOMINANT_SHARE else ""

Activity · 14 steps
lines 369–369raw = (refresh or {}).get("stages")lines 370–370◇ if not rawlines 371–371return ""lines 372–372timings: dict[str, int] = {}lines 373–373◇ for pair in str(raw).split()lines 374–374stage, _, value = pair.partition("=")lines 375–375◇ if value.isdigit()lines 376–376timings[stage] = int(value)lines 377–377total = sum(timings.values())lines 378–378◇ if not totallines 379–379return ""lines 380–380stage, spent = max(timings.items(), key=lambda kv: kv[1])lines 381–381share = round(100 * spent / total)lines 382–382return f", {share}% of it {stage}" if share >= _DOMINANT_SHARE else ""

Flows

_humanise_ms

str clew.mcp_server.freshness._humanise_ms(str raw)

Spell a millisecond count the way a reader would say it.

clew/mcp_server/freshness.py:259

Show on the map →

Called by _cost_clause, test_an_unreadable_duration_is_quoted_not_guessed, test_durations_are_spelled_the_way_a_reader_says_them

Calls none

Source · 34 lines
def _humanise_ms(raw: str) -> str:
    """KEEPS MILLISECONDS BELOW TEN SECONDS, because at that scale they are the informative
    unit and rounding a 2.7 s refresh to "3 s" throws away the thing that makes it obviously
    cheap. Above it, minutes are what a reader compares against their own patience.

    FALLS BACK TO THE RAW STRING rather than raising or guessing. `duration_ms` is persisted as
    text and an index written by a future version could hold something else; a notice that
    printed a traceback, or invented a number, would be worse than one that quotes what it
    found.

    @brief Render a stored duration in readable units.
    @return The spelled duration.
    @version 1
    """
    try:
        ms = int(float(raw))
    except (TypeError, ValueError, OverflowError):
        ## `OverflowError` IS NOT THEORETICAL and is not a subclass of the other two: `float`
        ## accepts "1e9999" happily and returns `inf`, which `int()` then refuses. Caught by the
        ## test that feeds this function junk — without it a staleness notice raises and takes
        ## down a query that was otherwise answerable, which is the opposite of what a notice is
        ## for.
        return f"{raw} ms"
    if ms < 10_000:
        return f"{ms} ms"
    seconds = round(ms / 1000)
    if seconds < 60:
        return f"{seconds} s"
    minutes, rest = divmod(seconds, 60)
    ## Both parts, always, above a minute: "8 min" alone loses the half-minute that decides
    ## whether a refresh fits inside somebody's threshold.
    return f"{minutes} min {rest} s"

Activity · 11 steps
lines 273–273trylines 274–274ms = int(float(raw))lines 275–275except (TypeError, ValueError, OverflowError)lines 281–281return f"{raw} ms"lines 282–282◇ if ms < 10_000lines 283–283return f"{ms} ms"lines 284–284seconds = round(ms / 1000)lines 285–285◇ if seconds < 60lines 286–286return f"{seconds} s"lines 287–287minutes, rest = divmod(seconds, 60)lines 290–290return f"{minutes} min {rest} s"

Flows

_partial_notice

dict[str, str] | None clew.mcp_server.freshness._partial_notice(Mapping[str, object] status)

The partial-index notice, when doxygen failed and the C/C++ layer is missing.

clew/mcp_server/freshness.py:421

Show on the map →

Called by notices

Calls none

Source · 29 lines
def _partial_notice(status: Mapping[str, object]) -> dict[str, str] | None:
    """A STAMP NOBODY READS CHANGES NOTHING. A build whose doxygen failed now completes without
    the C/C++ layer and records `diagnostics.doxygen = failed`; this is what puts that in front of
    the reader on every reply, rather than letting "no such C function" read as a measurement.

    THE REMEDY IS NOT "REFRESH". A refresh re-runs the doxygen that failed, so the schema axis's
    advice would send the reader round a loop. Fix the cause first — most often an over-wide
    scope — then refresh.

    @brief Build the partial-axis notice.
    @return The notice, or None.
    @version 1
    """
    diagnostics = status.get("diagnostics")
    if not isinstance(diagnostics, Mapping) or diagnostics.get("doxygen") != "failed":
        return None
    reason = diagnostics.get("doxygen_reason") or "no reason was recorded"
    return {
        "axis": AXIS_PARTIAL,
        "message": (
            f"this index was built WITHOUT its C/C++ layer: doxygen failed ({reason}). Every other "
            f"layer is complete, but a C/C++ symbol that is not found may exist and simply not be "
            f"indexed. A refresh alone re-runs the same doxygen — fix the cause first (most often "
            f"an over-wide scope: declare index_scope in .clew.yaml), then call "
            f"index(action='refresh')."
        ),
    }

Activity · 5 steps
lines 434–434diagnostics = status.get("diagnostics")lines 435–435◇ if not isinstance(diagnostics, Mapping) or diagnostics.get("doxygen") != "failed"lines 436–436return Nonelines 437–437reason = diagnostics.get("doxygen_reason") or "no reason was recorded"lines 438–447return { "axis": AXIS_PARTIAL, "message": ( f"this index was built WITHOUT its C/C++ layer: doxygen failed ({reason}). Every other " f"layer is complete, but a C/C++ symbol that is not found may exist and simply not be " f"indexed. A refresh alone re-runs the same doxygen — fix the cause first (most often " f"an over-wide scope: declare index_scope in .clew.yaml), then call " f"index(action='refresh')." ), }

Flows

_schema_notice

dict[str, str] | None clew.mcp_server.freshness._schema_notice(Mapping[str, object] status)

The schema-axis notice, when the stamped and expected versions disagree.

clew/mcp_server/freshness.py:489

Show on the map →

Called by notices

Calls none

Source · 33 lines
def _schema_notice(status: Mapping[str, object]) -> dict[str, str] | None:
    """THE DIRECTION DECIDES THE ADVICE, and getting it backwards is worse than
    silence. `expected < actual` means the SERVER predates the INDEX: rebuilding
    re-stamps the same newer version, so `stale: true` cannot be cleared by any action
    the consumer takes, and telling them to rebuild sends them round a loop that cannot
    terminate. Observed live at 23 versus 17.

    The opposite direction is the ordinary one and a rebuild really does fix it.

    @brief Build the schema-axis notice.
    @return The notice, or None.
    @version 2
    """
    stamped = status.get("build_version")
    if not isinstance(stamped, int) or stamped == CLEW_BUILD_VERSION:
        return None
    if stamped > CLEW_BUILD_VERSION:
        message = (
            f"This index was built by pipeline version {stamped} and this server process "
            f"expects {CLEW_BUILD_VERSION}, so THE SERVER PREDATES THE INDEX. "
            "REBUILDING CANNOT CLEAR the `stale` flag — a rebuild re-stamps the same "
            "newer version. Restart the MCP client so it loads the current code."
        )
    else:
        message = (
            f"This index was built by pipeline version {stamped} and this server expects "
            f"{CLEW_BUILD_VERSION}, so the index predates the server and may be "
            "missing whole layers rather than merely being out of date. Call "
            "index(action='refresh', force=True) to rebuild it."
        )
    return {"axis": AXIS_SCHEMA, "message": message}

Activity · 8 steps
lines 502–502stamped = status.get("build_version")lines 503–503◇ if not isinstance(stamped, int) or stamped == CLEW_BUILD_VERSIONlines 504–504return Nonelines 505–505◇ if stamped > CLEW_BUILD_VERSIONlines 506–511message = ( f"This index was built by pipeline version {stamped} and this server process " f"expects {CLEW_BUILD_VERSION}, so THE SERVER PREDATES THE INDEX. " "REBUILDING CANNOT CLEAR the `stale` flag — a rebuild re-stamps the same " "newer version. Restart the MCP client so it loads the current code." )lines 512–512elselines 513–518message = ( f"This index was built by pipeline version {stamped} and this server expects " f"{CLEW_BUILD_VERSION}, so the index predates the server and may be " "missing whole layers rather than merely being out of date. Call " "index(action='refresh', force=True) to rebuild it." )lines 519–519return {"axis": AXIS_SCHEMA, "message": message}

Flows

code_identity

dict[str, object] clew.mcp_server.freshness.code_identity()

The code identity the process is actually running.

clew/mcp_server/freshness.py:230

Source · 24 lines
def code_identity() -> dict[str, object]:
    """The `code` axis as data, so a consumer can see the comparison and not only the
    verdict — gh#29's point was that a payload should say what produced it.

    `matches_source` is False ONLY on positive evidence of disagreement: two non-empty
    fingerprints that differ. An unreadable tree leaves it True, because "cannot tell"
    must not manufacture a warning that sends someone restarting a client for no reason.
    The asymmetry is deliberate and is the opposite of the one `source_fingerprint`
    makes, for the same reason: absent evidence is not evidence.

    @brief Report the running code's identity against the source tree.
    @return Code identity mapping.
    @version 1
    """
    current = source_fingerprint()
    both_known = bool(current) and bool(PROCESS_SOURCE_FINGERPRINT)
    return {
        "package_version": package_version(),
        "process_fingerprint": PROCESS_SOURCE_FINGERPRINT,
        "source_fingerprint": current,
        "matches_source": (not both_known) or current == PROCESS_SOURCE_FINGERPRINT,
    }

Activity · 3 steps
lines 244–244current = source_fingerprint()lines 245–245both_known = bool(current) and bool(PROCESS_SOURCE_FINGERPRINT)lines 246–251return { "package_version": package_version(), "process_fingerprint": PROCESS_SOURCE_FINGERPRINT, "source_fingerprint": current, "matches_source": (not both_known) or current == PROCESS_SOURCE_FINGERPRINT, }

Requirements

REQ-DDB-MCP-004

Flows

notices

list[dict[str, str]] clew.mcp_server.freshness.notices(Mapping[str, object] status, Mapping[str, object]|None code=None)

Every staleness axis currently in play, with the action that clears it.

clew/mcp_server/freshness.py:653

Source · 25 lines
def notices(
    status: Mapping[str, object], code: Mapping[str, object] | None = None
) -> list[dict[str, str]]:
    """EMPTY ON A CURRENT TOOL, which is the load-bearing half. A warning that is always
    present is a warning nobody reads, and this annotation rides on every query reply —
    so the control on the whole change is that a genuinely current index is annotated
    with nothing at all.

    Ordered by how likely the reader is to act on it: `data` is the common case and the
    cheapest fix, `schema` is rarer and changes which fix applies, `code` is last because
    it is the one that says no rebuild will help.

    @brief List the active staleness axes with their remedies.
    @return List of {axis, message}, empty when current.
    @version 2
    """
    identity = code if code is not None else code_identity()
    found = (
        _data_notice(status),
        _schema_notice(status),
        _partial_notice(status),
        _derived_notice(status),
        _code_notice(identity),
    )
    return [notice for notice in found if notice is not None]

1 more lines, not shown

Activity · 3 steps
lines 669–669identity = code if code is not None else code_identity()lines 670–676found = ( _data_notice(status), _schema_notice(status), _partial_notice(status), _derived_notice(status), _code_notice(identity), )lines 677–677return [notice for notice in found if notice is not None]

Requirements

REQ-DDB-MCP-004

Flows

package_source_root

Path clew.mcp_server.freshness.package_source_root()

The installed package's source directory.

clew/mcp_server/freshness.py:103

Source · 13 lines
def package_source_root() -> Path:
    """The directory the RUNNING process imported from, whatever install shape put it
    there. Under `pipx install --editable` that is the working tree, which is the whole
    reason the `code` axis can drift at all; under a snapshot install it is a
    site-packages copy that never changes, and the axis then correctly stays silent.

    @brief Locate the imported package's source directory.
    @return The package root.
    @version 1
    """
    return Path(__file__).resolve().parent.parent

Activity · 1 steps
lines 113–113return Path(__file__).resolve().parent.parent

Flows

package_version

str clew.mcp_server.freshness.package_version()

The package version this process is running.

clew/mcp_server/freshness.py:201

Source · 25 lines
def package_version() -> str:
    """Read from installed metadata, so the version cannot drift from `pyproject.toml`.
    "unknown" rather than a raise: this is called on the way out of replies that already
    succeeded.

    THE DISTRIBUTION NAME IS THE PART THAT DRIFTED. This asked for `version("clew")` — the
    import name — and every `index(action='status')` reply since the rename reported
    `package_version: "unknown"`, which is the first field a consumer pastes into a bug
    report. Nothing caught it because the fallback is silent by design: the failure of a
    version lookup renders as a plausible-looking value, not as an error.

    @brief Read the installed package version.
    @return Version string or "unknown".
    @version 3
    """
    try:
        from importlib.metadata import (
            version,
        )

        return version(_DISTRIBUTION)
    except Exception:
        return "unknown"

Activity · 5 steps
lines 216–216trylines 217–219from importlib.metadata import ( version, )lines 221–221return version(_DISTRIBUTION)lines 222–222except Exceptionlines 223–223return "unknown"

Flows

refused

str clew.mcp_server.freshness.refused(Exception exc)

Tag a deliberate refusal so a truncating client still shows the distinction.

clew/mcp_server/freshness.py:569

Source · 34 lines
def refused(exc: Exception) -> str:
    """FIELD-REPORTED: a caller's client showed only the tool name for both an EXPECTED
    refusal (a mistyped action, an ambiguous target) and an actual crash. THE FIRST
    HYPOTHESIS — a client rendering or truncating aggressively — was wrong, and only a
    real second environment proved it: CI (mcp==2.1.1) reproduced the bare "Error
    executing tool X" this function exists to prevent, on the very tests written to
    guard it, while a developer venv (mcp==2.0.0) had the fix working the whole time.
    `Tool.run()`, since 2.1, preserves an exception's text ONLY when it is already the
    SDK's own `ToolError`/`ResourceError`/`MCPError` — anything else is an unexpected
    CRASH by definition, and its text is discarded before a client ever sees it. So the
    caller has to raise the RESULT of this function as `_sdk.ToolError`, not as
    `type(exc)`; tagging a `RuntimeError`'s message and re-raising the same type was a
    fix that only worked on the OLDER SDK behaviour. `stale_code_refusal` below already
    spoke the REFUSED: convention for one case; this generalises the marker for every
    deliberate refusal this server raises, and lives beside it for that reason — one
    module owns the wording, even though a different module now owns getting it there.

    SCOPED TO `RuntimeError`/`ValueError`, which is what every deliberate refusal on the
    MCP surface already raises — not a bespoke exception hierarchy, which would mean
    touching every one of its ~30 call sites and risking a missed one. The trade a
    type-based tag accepts: a stdlib call that happened to raise one of those two for a
    genuine bug would be mislabelled REFUSED. None currently does, on those call sites.

    IDEMPOTENT, because a refusal built from another refusal's text (a caught-and-rewrapped
    RuntimeError) must not read "REFUSED: REFUSED: ...".

    @brief Prefix a deliberate refusal's message with "REFUSED:", once.
    @return The tagged message text.
    @version 2
    """
    text = str(exc)
    return text if text.startswith("REFUSED:") else f"REFUSED: {text}"

Activity · 2 steps
lines 599–599text = str(exc)lines 600–600return text if text.startswith("REFUSED:") else f"REFUSED: {text}"

Requirements

REQ-DDB-MCP-004

Flows

source_fingerprint

str clew.mcp_server.freshness.source_fingerprint(Path|None root=None)

Fingerprint the package source's identity on disk.

clew/mcp_server/freshness.py:121

Source · 61 lines
def source_fingerprint(root: Path | None = None) -> str:
    """Hashes RELATIVE path and file CONTENT for every `.py` under the package — never
    mtime, and never an absolute path.

    IT HASHED MTIME UNTIL A LIVE MEASUREMENT KILLED THAT. The reasoning was that "has the
    tree moved since this process started" is answered by a stat, and reading every byte
    would cost real time on a surface called once per reply. The cost claim was wrong by
    measurement — 90 files and 2.6 MB hash in 4.0 ms against 2.2 ms for stat-only, so
    content costs 1.8 ms — and the correctness cost was much larger than 1.8 ms.

    THE CODE AXIS IS A HARD REFUSAL: `matches_source` false blocks the automatic
    query-time refresh AND refuses an explicit build, and no rebuild clears it — only
    restarting the client does. An mtime key trips on `git checkout`, a branch switch,
    `git stash pop`, rsync and plain `touch`, every one of which leaves byte-identical
    content. Observed here: reverting ONE file with `git checkout` moved the fingerprint,
    the axis fired on the next two query replies, and that is what stopped the
    query-time auto-refresh from ever engaging in this repository. A safety gate that
    fires on ordinary git operations disables the feature it guards.

    The sibling `IndexCache` already states this codebase's rule — 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 now follows it. No
    prefilter here, because there is nothing to compare a prefilter against: the result is
    a single digest over the whole tree, not a per-file cache lookup.

    Not absolute paths because anything reachable over MCP is published, and stamping a
    machine's directory layout into a payload is the disclosure that forced the
    build-version-9 bump. A digest over relative paths compares exactly as well and
    discloses nothing.

    Returns "" — meaning "cannot tell", never "unchanged" — when the tree is unreadable,
    and `notices` treats an empty fingerprint on either side as no evidence rather than
    as agreement. A missing measurement must not read as a clean bill of health.

    THE EMPTY-TREE CASE IS CHECKED SEPARATELY AND A CONTROL CAUGHT IT. `Path.rglob`
    SWALLOWS a missing or unreadable directory and yields nothing rather than raising, so
    the `except OSError` alone let a tree that could not be read hash to the digest of
    ZERO FILES — a perfectly stable, entirely fabricated fingerprint. Worse than useless:
    two unreadable trees produce the SAME digest, so `matches_source` would compare equal
    and report the process as healthy on no evidence at all. That is this repo's standing
    lesson exactly — "no rows" is a claim about the detector — reached by a detector that
    could not look. A package with zero `.py` files is not a package.

    @brief Digest the package source tree's CONTENT identity.
    @return Short hex digest, or "" when unreadable or empty.
    @version 3
    """
    base = root if root is not None else package_source_root()
    digest = hashlib.sha256()
    seen = 0
    try:
        for path in sorted(base.rglob(_SOURCE_GLOB)):
            rel = path.relative_to(base).as_posix()
            digest.update(f"{rel}\0".encode())
            digest.update(hashlib.sha256(path.read_bytes()).digest())
            seen += 1
    except OSError:
        return ""
    return digest.hexdigest()[:_FINGERPRINT_CHARS] if seen else ""

Activity · 12 steps
lines 168–168base = root if root is not None else package_source_root()lines 169–169digest = hashlib.sha256()lines 170–170seen = 0lines 171–171trylines 172–172◇ for path in sorted(base.rglob(_SOURCE_GLOB))lines 173–173rel = path.relative_to(base).as_posix()lines 174–174digest.update(f"{rel}\0".encode())lines 175–175digest.update(hashlib.sha256(path.read_bytes()).digest())lines 176–176seen += 1lines 177–177except OSErrorlines 178–178return ""lines 179–179return digest.hexdigest()[:_FINGERPRINT_CHARS] if seen else ""

Requirements

REQ-DDB-MCP-004

Flows

stale_code_refusal

str | None clew.mcp_server.freshness.stale_code_refusal(Mapping[str, object]|None code=None)

The refusal a write path owes its caller when this process predates its source.

clew/mcp_server/freshness.py:608

Source · 36 lines
def stale_code_refusal(code: Mapping[str, object] | None = None) -> str | None:
    """THE GUARD A WRITE PATH CALLS BEFORE TOUCHING AN INDEX. Returns None — meaning
    "go ahead" — on the ordinary case, so the caller is one `if` and the prose lives here
    with the rest of the code-axis wording rather than being paraphrased at each call site.

    IT DOES NOT ACCEPT AN OVERRIDE, and `force` deliberately does not bypass it. `force`
    exists to skip the FRESHNESS check; the incident that motivated this used it, so a
    refusal it could argue past would have prevented nothing.

    REJECTED — reload the pipeline modules and proceed: `PROCESS_SOURCE_FINGERPRINT` is
    taken at import and module-level constants captured by OTHER modules do not refresh
    with a reload, so a partially-reloaded pipeline would build with a MIXTURE of old and
    new logic and report success. That is a harder bug than the one being fixed.

    REJECTED — warn loudly and proceed: the notice above ALREADY warned on every call. It
    was read, and the downgrade happened anyway, because the warning said the data was
    unaffected. A louder version of a message that is already present and already wrong is
    not a fix.

    @brief Refuse a write when the running code predates the source tree.
    @return Refusal message, or None when the process matches its source.
    @version 2
    """
    identity = code if code is not None else code_identity()
    if identity.get("matches_source"):
        return None
    return (
        f"REFUSED: this server process loaded clew "
        f"{identity.get('package_version')} at launch and the package source has changed "
        f"since (fingerprint {identity.get('process_fingerprint')} on disk now "
        f"{identity.get('source_fingerprint')}). {_WRITE_HAZARD} Nothing was written. "
        "Restart the MCP client so it loads the current code, then call "
        f"index(action='refresh', force=True) — one reconnect is the whole cost. {_READ_EXEMPTION}"
    )

Activity · 4 steps
lines 631–631identity = code if code is not None else code_identity()lines 632–632◇ if identity.get("matches_source")lines 633–633return Nonelines 634–641return ( f"REFUSED: this server process loaded clew " f"{identity.get('package_version')} at launch and the package source has changed " f"since (fingerprint {identity.get('process_fingerprint')} on disk now " f"{identity.get('source_fingerprint')}). {_WRITE_HAZARD} Nothing was written. " "Restart the MCP client so it loads the current code, then call " f"index(action='refresh', force=True) — one reconnect is the whole cost. {_READ_EXEMPTION}" )

Requirements

REQ-DDB-MCP-004

Flows