state.py¶
clew/mcp_server/state.py
R3 target registry: where each repo's clew.db lives, and how fresh it is.
_bounded_scope_meta
dict[str, str] clew.mcp_server.state._bounded_scope_meta(dict[str, str] meta)
Bound the stored scope strings a status reply carries.
Called by db_status, test_a_short_operator_exclude_is_reported_verbatim, test_the_status_scope_block_does_not_carry_a_full_exclude_list
Calls none
Source · 38 lines
def _bounded_scope_meta(meta: dict[str, str]) -> dict[str, str]:
"""gh#37. `status.scope.excludes` CARRIED THE WHOLE RESOLVED EXCLUDE LIST — ~390 entries,
dominated by `.github` and `.drone` paths inside a vendored boost — and the same list
appeared again under `operator_excludes`. Two refresh replies in one session exceeded the
client's result limit and were written to disk instead of returned.
THE COUNT IS THE ACTIONABLE FACT. "390 paths were excluded" is something an operator reads
and reacts to; the 390 paths themselves are what the buildlog is for, and it already has
them. So an oversized value keeps its opening — enough to recognise WHAT is being excluded —
and gains a sibling `<key>_count`.
NOTHING SHORT IS TOUCHED, which is what keeps `operator_excludes` useful: it is the
operator's OWN statement, normally a word or two, and it is the field that tells them their
decision was recorded and replayed. A count beside a two-word value would be noise.
gh#36 removed most of what made this list long in the first place, by no longer descending
vendored trees to collect their deep dot-directories. This is the bound that holds whatever
a repository's shape turns out to be — the same reason `_bounded_output` caps as well as
collapses.
@brief Trim oversized scope strings, disclosing the count.
@return Bounded scope mapping.
@version 1
"""
bounded: dict[str, str] = {}
for key, value in meta.items():
text = str(value)
if len(text) <= _SCOPE_STRING_CAP:
bounded[key] = value
continue
bounded[key] = (
f"{text[:_SCOPE_STRING_CAP]} ... trimmed to stay inside the client's result limit; "
f"the complete list is in the buildlog beside the index"
)
bounded[f"{key}_count"] = str(text.count(",") + 1)
return bounded
Activity · 9 steps
Flows
_coverage_meta
dict[str, str] clew.mcp_server.state._coverage_meta(Path db)
The index-coverage measurement recorded at build time, if any.
Source · 18 lines
def _coverage_meta(db: Path) -> dict[str, str]:
"""HOW MUCH of what was indexed actually yielded anything — which nothing in the
database answered before build 18, and which `status` could not report even though
the pipeline had measured it.
gh#6: a build announced 2,555 functions and 28,151 call edges for a target whose
index held almost none of the library, and `status` reported that index as present,
current and healthy. Size was queryable and coverage was not, so a consumer had no
way to ask the one question that would have voided a 198-cell acceptance run before
it was paid for.
@brief Read the stored coverage measurement.
@return Mapping without the key prefix, or {}.
@version 2
"""
return _meta_section(db, "coverage")
Activity · 1 steps
Requirements
Flows
_data_model_meta
dict[str, str] clew.mcp_server.state._data_model_meta(Path db)
The generated data model the repository declares, and what was declined.
Source · 32 lines
def _data_model_meta(db: Path) -> dict[str, str]:
"""gh#351, and it is a DIAGNOSTIC as much as an inventory. `data_model.keys` beside
`data_model.keys_listed` and the `data_model_keys.observed` column is the declared-vs-
observed measurement the layer exists for: a repository declaring 135 keys and touching 5
of them is a fact about that repository nothing else in the index reports.
The REFUSALS are the half a consumer acts on. `manifests_unlisted` says shape-matching
manifests were found and declined because no key list vouched for them, which is the
difference between "this repository has no data model" and "it has one and nothing selects
it"; `documents_oversized` means a document was refused unread for its size, and
`toml_unavailable` that the INGOT half specifically could not be looked at — both mean
"could not look" rather than "looked and found none". A count of zero is the measurement.
`unresolved_note` is the one PROSE field in this section and it earns that. gh#351 reads
two dialects, and one of them declares a key's default as a base value plus per-variant
siblings that only a build's variant selection resolves — so those rows carry a NULL
`default_value` BY DIALECT rather than by absence. A consumer cannot tell those apart from
a count, and the per-row `data_model_keys.unresolved_fields` it points at is what makes
the distinction queryable. The field is absent when nothing was unresolved, so it never
asserts a policy that did not apply to this repository.
A LITERAL prefix, for the reason `_diagnostics_meta` gives one screenful up: importing the
writer's constant would pull the discovery module into the server's startup path to read
one string, and a round-trip test pins the spelling at both ends instead.
@brief Read the stored data-model inventory and its refusals.
@return Mapping without the key prefix, or {}.
@version 2
"""
return _meta_section(db, "data_model")
Activity · 1 steps
Requirements
Flows
_diagnostics_meta
dict[str, str] clew.mcp_server.state._diagnostics_meta(Path db)
What the build searched for and did NOT find, counts included when they are zero.
Source · 24 lines
def _diagnostics_meta(db: Path) -> dict[str, str]:
"""THE ONLY SECTION ABOUT ABSENT ROWS (gh#320). Every other section describes what
the index HAS; this one names what the build looked for, did not claim, and therefore
wrote nothing for — so a sparse causal layer can be told apart from a repository that
genuinely has no dataflow.
The counts arrive as `"0"` rather than as missing keys, which is the whole point:
"searched 3,784 names and matched no undeclared family" is a measurement an agent can
report, while an absent key is indistinguishable from a diagnostic that never ran.
The SECTION being absent still means "not recorded" — true only for an index built
before this existed, and honest for one.
A LITERAL prefix, like `scope`/`coverage`/`refresh` above and unlike `options`.
Importing `diagnostics.META_PREFIX` would pull the shared-key and event importers into
the server's startup path to read one string. The spelling is pinned by a round-trip
test instead, which catches a divergence at either end rather than only at this one.
@brief Read the stored build diagnostics.
@return Mapping without the key prefix, or {}.
@version 1
"""
return _meta_section(db, "diagnostics")
Activity · 1 steps
Requirements
Flows
_meta_section
dict[str, str] clew.mcp_server.state._meta_section(Path db, str prefix)
One namespaced build_meta section, read without its key prefix.
Called by _coverage_meta, _data_model_meta, _diagnostics_meta, _options_meta, _refresh_meta, _scope_meta, db_status
Calls meta_section
Source · 20 lines
def _meta_section(db: Path, prefix: str) -> dict[str, str]:
"""ONE reader for every section, because there were two byte-identical copies of it
and a third was about to be pasted in for `refresh.*`. `build_meta` is deliberately a
namespaced key/value table so that a further section is a one-line change; three
copies of the same six-line SQLite dance is the opposite of that design.
THE IMPLEMENTATION MOVED to `query._common.meta_section` when gh#7 needed the same
section from the query layer — a fourth copy would have been the exact drift this
function was written to stop. The delegation is kept as a named function rather than
an import alias because the single-path audit's exemption for this module is written
against these three readers by name, and because the `Path`-typed signature is what
every caller here passes.
@brief Read one namespaced build_meta section.
@return Mapping without the key prefix, or {}.
@version 2
"""
return meta_section(db, prefix)
Activity · 1 steps
Requirements
Flows
_options_meta
dict[str, str] clew.mcp_server.state._options_meta(Path db)
Which precedence tier chose each layered setting this index was built with.
Called by _options_meta_section, db_status
Tested by 5 tests
test_a_stated_configuration_survives_export_declare_rebuild, test_a_stated_manifest_survives_a_rebuild_and_a_withdrawal_undoes_it, test_a_stated_predefined_survives_a_rebuild_and_a_withdrawal_undoes_it, test_status_names_the_options_an_operator_stated, test_status_reports_which_tier_chose_the_seeds
Calls _meta_section
Source · 20 lines
def _options_meta(db: Path) -> dict[str, str]:
"""WHOSE POLICY the index was built under (gh#319), which is the half of the
scope story the other sections do not tell. `scope.*` says which files were
indexed and `coverage.*` how much of them yielded anything — neither says
whether the liveness split came from the repo's own declared dispatch
vocabulary, from a flag an operator passed once, or from our provisional
name-shape guesses. A consumer reading a surprising orphan count has opposite
responses available for those three, and nothing to choose between them with.
Reporting it is not decoration: a tiered resolution whose winner is not visible
is the same opacity as an untiered one, with more moving parts. Absent on an
index built before build 30, which is the honest signal.
@brief Read the stored layered-option provenance.
@return Mapping without the key prefix, or {}.
@version 1
"""
return _meta_section(db, OPTIONS_META_PREFIX)
Activity · 1 steps
Requirements
Flows
_preserve_unreadable
None clew.mcp_server.state.TargetRegistry._preserve_unreadable(self, Exception reason)
Move an unreadable registry aside and say so, loudly.
Source · 28 lines
def _preserve_unreadable(self, reason: Exception) -> None:
"""Moving it aside is what stops the loss becoming permanent: `register()` calls
`load()` and then `save()`, so an unreadable file left in place is overwritten by a
registry containing one entry, and the only record of what was registered is gone.
A read method with a filesystem side effect is a real cost, accepted because `load`
is the only place that knows the file is unreadable — detecting it a second time in
`save` would mean reading the registry on every write.
MOVE FIRST, THEN REPORT. The first version composed the sentence "Its bytes are
preserved at X" and only afterwards attempted the move, so a failed `os.replace`
emitted a confident false claim followed by a correction — an operator reading the
first line would have believed the data was safe. A mutation control found it, by
disabling the move and leaving the message intact.
@brief Log an unreadable registry, having first preserved its bytes.
@version 2
"""
kept = self.path.with_name(self.path.name + UNREADABLE_SUFFIX)
logger.error(
"%s is unreadable (%s: %s). Treating the registry as EMPTY for this call, so "
"list_targets and cull will not see previously registered repositories. %s",
self.path,
type(reason).__name__,
reason,
self._move_aside(kept),
)
Activity · 2 steps
Requirements
_refresh_meta
dict[str, str] clew.mcp_server.state._refresh_meta(Path db)
What the last refresh of this index actually cost, if it was measured.
Source · 23 lines
def _refresh_meta(db: Path) -> dict[str, str]:
"""THE COST OF CORRECTING STALENESS, AS A MEASUREMENT (gh#9). The pipeline knew its
wall duration, how many files it reprocessed and how many it took from cache, and
returned none of it — so an agent asked what a refresh costs had to estimate, and
the two benchmark marks that demand a measured number missed 9 of 9 cells across
every model tier.
Persisted rather than estimated from a constant so the number is grounded in THIS
target's own history: 1.6 s for a 114-file target and 9.1 s for 420 files are the
same tool, and a single built-in constant would be wrong for both.
Values are STRINGS because `build_meta` is a TEXT table — and, load-bearingly,
because `write_build_signature` DROPS FALSY VALUES, so a measured zero survives as
`"0"` and would vanish as `0`. gh#6, gh#17 and gh#18 each worked around that; this
is the fourth section to do so on purpose.
@brief Read the measured cost of the last refresh.
@return Mapping without the key prefix, or {}.
@version 1
"""
return _meta_section(db, "refresh")
Activity · 1 steps
Requirements
Flows
_safe_index_name
str clew.mcp_server.state._safe_index_name(str name)
Reduce a declared sub-index name to something safe as a directory component.
Source · 23 lines
def _safe_index_name(name: str) -> str:
"""REFUSES RATHER THAN SUBSTITUTES when nothing survives. A name that sanitises to empty would
make the sub-index slug identical to the PARENT's, so a vendored sub-index would silently
overwrite the whole-repo index — a wrong answer produced by a naming accident, which is worse
than a build that stops and says the name is unusable.
Leading dots are stripped for the same reason `clew_hook`'s token filter rejects them: `.` and
`..` are path components, not names, and a dotfile directory in the state root is a surprise
nobody asked for.
@brief Sanitise a sub-index name.
@return A safe directory component.
@version 1
"""
kept = "".join(ch for ch in name if ch in _INDEX_NAME_SAFE).lstrip(".")[:_INDEX_NAME_MAX]
if not kept:
raise ValueError(
f"sub-index name {name!r} contains no usable characters "
f"(allowed: letters, digits, '.', '_', '-')"
)
return kept
Activity · 4 steps
Flows
_scope_meta
dict[str, str] clew.mcp_server.state._scope_meta(Path db)
The scope decision recorded at build time, if any.
Source · 15 lines
def _scope_meta(db: Path) -> dict[str, str]:
"""WHY a file set is what it is, which nothing in the database answered before build 16.
Measured on the entropic acceptance grid: the raw arm scored 3/3 on "checks the Doxyfile
and reports its INPUT does not list examples/" against the index arm's 1/3 — the only
clearly actionable gap in 56 marks. The raw arm simply reads the Doxyfile; the index arm
had no route to it, because the pipeline logged its scope decision and never stored it.
@brief Read the stored scope provenance.
@return Mapping without the key prefix, or {}.
@version 2
"""
return _meta_section(db, "scope")
Activity · 1 steps
Requirements
Flows
_source_drift
tuple[int, str | None] clew.mcp_server.state._source_drift(Path db, Path repo_root)
Count indexed source files modified since the database was built.
Source · 62 lines
def _source_drift(db: Path, repo_root: Path) -> tuple[int, str | None]:
"""Stat every indexed source file against the database's own mtime.
This is the term freshness was missing entirely. Staleness used to be just
`stamped != CLEW_BUILD_VERSION`, so a database built before any number
of source edits still reported `stale: false` and `build_or_refresh`
declined to rebuild it — an agent then answered from a graph describing
code that no longer exists, with the status tool actively asserting the
index was current. A version check cannot see source drift; only mtimes can.
Fails closed to "no drift" on an unreadable or table-less database: the
version term already marks those stale, and guessing here would force
pointless rebuilds.
@brief Detect source files newer than the database.
@return (changed count, newest changed repo-relative path).
@version 3
"""
try:
db_mtime = db.stat().st_mtime
conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
except (OSError, sqlite3.Error):
return 0, None
try:
indexed = [r[0] for r in conn.execute("SELECT name FROM path WHERE type=1")]
except sqlite3.Error:
indexed = []
finally:
conn.close()
changed, newest, newest_mtime = 0, None, 0.0
## A MTIME IN THE FUTURE IS NOT EVIDENCE OF AN EDIT (1.1.0 audit, M7). It is newer than
## every database that will ever be built from the file, so the index is PERMANENTLY stale
## and the 15 s `keep_current` loop rebuilds it forever — doxygen, cargo and the Kconfig
## parse, every one of them a repo-controlled stage, on a loop for the life of the server.
## A skewed clock on the machine that made the checkout produces it by accident; a
## committed timestamp produces it on purpose. The file stays INDEXED either way; only its
## timestamp is refused as a staleness signal, and the refusal is reported once.
horizon = time.time() + _MTIME_SKEW_TOLERANCE_SECONDS
future_dated = 0
for rel in indexed:
try:
mtime = (repo_root / rel).stat().st_mtime
except OSError:
continue # deleted/moved: the rebuild will notice, this pass will not
if mtime > horizon:
future_dated += 1
continue
if mtime > db_mtime:
changed += 1
if mtime > newest_mtime:
newest, newest_mtime = rel, mtime
if future_dated:
logger.warning(
"freshness: %d indexed file(s) under %s are dated in the future and were NOT "
"treated as edits — they would otherwise keep this index stale forever. Check the "
"clock on the machine that produced the checkout.",
future_dated,
repo_root,
)
return changed, newest
Activity · 27 steps
Flows
cull
list[dict[str, object]] clew.mcp_server.state.cull(TargetRegistry registry, float|None max_age_days=30.0, bool include_stale=True)
Remove databases that are aged out or built by an older pipeline.
Source · 44 lines
def cull(
registry: TargetRegistry,
max_age_days: float | None = 30.0,
include_stale: bool = True,
) -> list[dict[str, object]]:
"""Sweep the registry, dropping each target whose db is older than
`max_age_days` or (when `include_stale`) carries a non-current build
signature. Targets with no db on disk are dropped too — the registry
entry is dead weight, and a killed sub-index build leaves exactly that:
a slug holding a buildlock, a buildlog and an idxcache with no database.
ONE TARGET AT A TIME (gh#35). This used to call `drop(target.repo_path)`,
which removes every entry sharing that repo path — so culling one dead
sub-index deleted the repository's healthy first-party index and every
vendored sub-index beside it, off disk. The loop judges targets
individually and the removal must be individual too.
@brief Cull aged/stale target databases.
@return Status dicts of the culled targets.
@version 4
"""
culled: list[dict[str, object]] = []
for target in registry.targets():
status = db_status(target)
age = status["age_days"]
## NON-POSITIVE MEANS "NO AGE RULE", not "every database is too old" (1.1.0 audit,
## M4). `age > 0` holds for everything that exists, so `max_age_days=0` — which an
## agent reading "age threshold in days" passes to mean no limit, as it does in most
## such knobs — deleted every index on the machine, including repositories the session
## had never heard of. `None` already spelled the disable; 0 now agrees with it
## instead of inverting it, and the MCP boundary refuses a non-positive value outright.
age_rule = max_age_days is not None and max_age_days > 0
aged_out = age_rule and isinstance(age, float) and age > max_age_days
version_stale = include_stale and status["build_version"] != CLEW_BUILD_VERSION
if not status["exists"] or aged_out or version_stale:
registry.drop_one(target)
culled.append(status)
return culled
# Re-exported from the pipeline so the MCP server and the CLI share ONE
# discovery implementation. They previously diverged — only the MCP path looked
# for the repo's Doxyfile — which silently produced different databases for the
# same repo depending on the entry point used.Activity · 11 steps
Requirements
db_status
dict[str, object] clew.mcp_server.state.db_status(Target target)
Freshness/identity report for one target's database.
Called by _build_once, _data_stale, _run_build_walked, _stale, adopt, answering, build_or_refresh, cmd_autorefresh, cull, list_targets, main, staleness_notices 1 more
status
Tested by 15 tests
test_a_zero_refresh_measurement_survives_persistence, test_coverage_is_persisted_into_build_meta_and_reaches_status, test_db_status_detects_source_drift, test_db_status_freshness_uses_build_signature, test_db_status_reports_the_fast_section_and_counts_it_as_stale, test_db_status_source_drift_survives_a_corrupt_db, test_stamping_the_refresh_section_preserves_scope_and_version, test_status_on_a_PRE_COVERAGE_index_says_nothing_rather_than_guessing, test_status_on_a_PRE_DIAGNOSTICS_index_says_nothing_rather_than_guessing, test_status_on_a_PRE_SCOPE_index_says_nothing_rather_than_guessing, test_status_publishes_the_barren_ratio_and_offenders, test_status_reports_WHAT_THE_BUILD_DID_NOT_FIND
Calls _bounded_scope_meta, _coverage_meta, _data_model_meta, _diagnostics_meta, _meta_section, _options_meta, _refresh_meta, _scope_meta, _source_drift, code_identity, list, notices
Source · 104 lines
def db_status(target: Target) -> dict[str, object]:
"""Describe the db behind a target: does it exist, which pipeline version
stamped it, HAVE ITS SOURCES CHANGED SINCE, and how old is it.
Staleness is now two-termed, matching what the word means to a caller: an
older pipeline stamp OR drifted sources. Previously only the stamp counted,
which made `status` affirmatively wrong for the commonest case in live
development — edit a file, and the index still claimed to be current.
COVERAGE is reported beside size for gh#6: an index can be present, current and
entirely trustworthy-looking while holding almost none of the repository. Staleness
answers "does this describe the code as it is now"; coverage answers "does it
describe the code at all". A consumer that checks only the first can still be
reasoning about a library whose implementation never parsed.
AND `stale` IS NOW INTERPRETED, not merely raised. Three different things make it
true and they are cleared by three different actions — a rebuild, a client restart,
or nothing the consumer can do — so the flag alone under-determines the remedy. The
worst case shipped for months: `expected_build_version` below `build_version` makes
`stale: true` UNRESOLVABLE, because a rebuild re-stamps the same newer version. Both
integers were already right here in the payload and nothing read them out loud.
`staleness` is ABSENT when the tool is current, so it stays a signal.
AND WHOSE POLICY THIS INDEX CARRIES IS NAMED, not merely derivable (gh#364). A tier-1
statement now SURVIVES a rebuild, which means the index can carry a policy the
repository does not declare — so two operators of one commit can hold different
indexes. That is allowed only because it is deliberate AND visible: `stated_options`
names the options an operator stated, so the difference is findable without reading
every `options.*` row and knowing which tier word matters. Absent when nothing was
stated, so it stays a signal rather than a field to skim past.
@brief Report a target database's freshness, coverage, refresh cost, option tiers, stated options, build diagnostics, declared data model and code identity.
@return Status dict (exists / build_version / drift / stale / age_days / coverage / refresh / options / stated_options / diagnostics / data_model / code / staleness).
@version 11
"""
db = Path(target.db_path)
exists = db.is_file()
## Read ONCE and used twice — the stored rows and the derived summary of them. Two
## reads could not disagree today, but the summary must be a projection of exactly
## the rows reported beside it rather than of a second look at the database.
options = _options_meta(db) if exists else {}
stated = stated_options(options)
stamped = read_build_signature(db) if exists else None
age_days = round((time.time() - db.stat().st_mtime) / 86400.0, 3) if exists else None
changed, newest = _source_drift(db, Path(target.repo_path)) if exists else (0, None)
## A FAST IN-PLACE REFRESH STILL PENDING ITS FULL REFRESH (1.3.5). It counts as stale: the
## in-place write moved the database's mtime past the edit, so without this the index would
## read as current on every axis and the follow-up full build would skip itself.
fast = _meta_section(db, "fast") if exists else {}
fast_pending = fast.get("pending") == "1"
status: dict[str, object] = {
"repo_path": target.repo_path,
"db_path": target.db_path,
## ABSENT FOR A WHOLE-REPO TARGET, present and named for a sub-index — so a caller can
## tell the two apart without parsing anything, and `list_targets` can offer every
## sub_index name a repository has without a second call.
**({"sub_index": target.name} if target.name is not None else {}),
"exists": exists,
"build_version": stamped,
"expected_build_version": CLEW_BUILD_VERSION,
"source_changed_files": changed,
"newest_changed_source": newest,
"stale": (not exists) or stamped != CLEW_BUILD_VERSION or changed > 0 or fast_pending,
"age_days": age_days,
## WHY this file set, not just what. Absent on an index built before build 16, which
## is the honest signal — "not recorded" rather than a fabricated default.
**({"scope": _bounded_scope_meta(_scope_meta(db))} if exists else {}),
## HOW MUCH of that file set yielded anything. Absent before build 18, same signal.
**({"coverage": _coverage_meta(db)} if exists else {}),
## WHAT CORRECTING IT COSTS, measured on this target rather than estimated. Read
## BEFORE the notices below, which quote it, so the advice to refresh carries a
## number instead of inviting a guess.
**({"refresh": _refresh_meta(db)} if exists else {}),
## WHOSE POLICY chose the layered settings — an operator's flag, the target's
## own declaration, or our provisional guesses. Absent before build 30.
**({"options": options} if exists else {}),
## WHICH OF THEM AN OPERATOR STATED, and therefore which are being REPLAYED onto
## every later rebuild of this index. DERIVED from the rows above, never stored: a
## stored summary is a second source of truth that can disagree with what it
## summarises, which is where a silent wrong answer hides. Absent when nothing was
## stated — the common case, and the one that needs no attention.
**({"stated_options": list(stated)} if stated else {}),
## WHAT THE BUILD LOOKED FOR AND DID NOT FIND, counts included when zero. The
## only section about absent rows, and the one that makes an empty causal layer
## distinguishable from a repo that has no dataflow (gh#320).
**({"diagnostics": _diagnostics_meta(db)} if exists else {}),
## WHICH FILES A FAST REFRESH UPDATED IN PLACE and which layers it left behind. Absent
## unless one is pending, so a current index carries nothing.
**({"fast": fast} if fast_pending else {}),
## WHICH GENERATED DATA MODEL the repository declares, how much of it the code was
## observed to touch, and every manifest the discovery declined and why (gh#351).
## Absent before build 37. Empty-but-present for the many repositories that have no
## generated data model, which is a correct negative rather than a gap.
**({"data_model": _data_model_meta(db)} if exists else {}),
## WHICH CODE IS ANSWERING. Not about the database at all — about this process —
## and the one axis that had no signal whatsoever before gh#29.
"code": code_identity(),
}
found = notices(status)
if found:
status["staleness"] = found
return status
Activity · 14 steps
Requirements
REQ-DDB-CONFIG-006 REQ-DDB-CONFIG-007 REQ-DDB-MCP-001 REQ-DDB-MCP-004
Flows
derived_names
tuple[str, ...] clew.mcp_server.state.TargetRegistry.derived_names(self, str repo_path)
The sub-index names last derived for a repository.
Source · 14 lines
def derived_names(self, repo_path: str) -> tuple[str, ...]:
"""EMPTY IS A GAP, NOT A DENIAL. A repository no sub-index has ever been built for has
nothing recorded, and the caller must not read that as "this repository does not
split" — the honest reading is "nobody has derived it here yet", which one build fixes.
@brief Read back the recorded split.
@return The names, or ().
@version 1
"""
for rec in self.load().values():
if rec.get("repo_path") == repo_path and rec.get("derived"):
return tuple(str(n) for n in rec["derived"])
return ()
Activity · 4 steps
Requirements
drop
bool clew.mcp_server.state.TargetRegistry.drop(self, str repo_path)
Forget a target and delete its built database directory.
Source · 24 lines
def drop(self, repo_path: str) -> bool:
"""DROPS EVERY SUB-INDEX OF A REPOSITORY, not just the one keyed under the bare path.
Since the registry is keyed by slug, one repository can own several entries, and a caller
passing its root almost always means "forget this repo", not "forget whichever entry
happens to be keyed under this exact string". The argument is still accepted as an exact
slug too, for a caller that named one sub-index specifically.
@brief Drop a target and its database — every sub-index if a repo root was given.
@return Whether anything was removed.
@version 3
"""
data = self.load()
matches = [
key
for key, rec in data.items()
if key == repo_path or rec.get("repo_path") == repo_path
]
if not matches:
return False
for key in matches:
self._discard(data, key)
self.save(data)
return True
Activity · 8 steps
Requirements
drop_one
bool clew.mcp_server.state.TargetRegistry.drop_one(self, Target target)
Forget EXACTLY one target, leaving every sibling sub-index registered.
Source · 28 lines
def drop_one(self, target: Target) -> bool:
"""gh#35. `cull` JUDGED EACH TARGET AND THEN DROPPED THE WHOLE REPOSITORY. It called
`drop(target.repo_path)`, whose breadth is correct for `drop` — a caller naming a repo
root means "forget this repo" — and wrong as the implementation of a per-target
decision. One abandoned sub-index slug therefore took the repository's first-party
index and every vendored sub-index with it, databases deleted from disk, on a sweep
called to reclaim a directory that held no database at all.
IDENTIFIED BY `db_path`, which is unique per (repository, sub-index) and is the field
`db_status` just judged. The slug would work equally for anything written since
sub-indexes existed; `db_path` also covers a legacy entry keyed by repo path, where the
slug may be absent from the record entirely.
@brief Drop one target and its database directory.
@return Whether an entry was removed.
@version 1
"""
if not target.db_path:
return self.drop(target.repo_path)
data = self.load()
key = next((k for k, rec in data.items() if rec.get("db_path") == target.db_path), None)
if key is None:
return False
self._discard(data, key)
self.save(data)
return True
Activity · 9 steps
Requirements
known_protocol_versions
tuple[str, ...] clew.mcp_server.state.known_protocol_versions()
Protocol revisions the installed SDK recognises, or empty when unreadable.
Source · 15 lines
def known_protocol_versions() -> tuple[str, ...]:
"""Empty means "this code cannot tell", which `roots_request_supported` reads as
permission to try — never as "no revisions exist".
@brief Read the SDK's registry of known protocol revisions.
@return The revisions, or an empty tuple.
@version 2
"""
try:
from mcp_types.version import KNOWN_PROTOCOL_VERSIONS
except Exception:
return ()
return tuple(KNOWN_PROTOCOL_VERSIONS)
Activity · 5 steps
Flows
load
dict[str, dict[str, str]] clew.mcp_server.state.TargetRegistry.load(self)
Load the raw registry mapping from disk.
Called by derived_names, drop, drop_one, note_derived, register, targets
Calls _preserve_unreadable
Source · 28 lines
def load(self) -> dict[str, dict[str, str]]:
"""Read the registry file, tolerating absence and corruption (a
broken registry must never take the server down).
ABSENCE AND CORRUPTION ARE DIFFERENT FACTS and are now told apart. An absent file is
the ordinary first run and stays silent; an unreadable one is an error, is logged as
one, and has its bytes moved aside. The bare `except … : return {}` made the two
indistinguishable — and the empty reading is the one that gets persisted, so silence
was how the loss stayed invisible.
A ROOT THAT PARSES BUT IS NOT AN OBJECT is the same class of damage as one that does
not parse, so it is raised into the same handler rather than quietly becoming `{}`.
@brief Read the persisted registry mapping.
@return repo_path → {slug, db_path} records.
@version 2
"""
if not self.path.exists():
return {}
try:
data = json.loads(self.path.read_text(encoding="utf-8"))
if not isinstance(data, dict):
raise TypeError(f"registry root is a {type(data).__name__}, not an object")
except (OSError, ValueError, TypeError) as exc:
self._preserve_unreadable(exc)
return {}
return data
Activity · 10 steps
Requirements
note_derived
None clew.mcp_server.state.TargetRegistry.note_derived(self, str repo_path, tuple[str,...] names)
Record the sub-index split derived for a repository.
Source · 25 lines
def note_derived(self, repo_path: str, names: tuple[str, ...]) -> None:
"""gh#38. WRITTEN AT BUILD TIME BECAUSE A LISTING MUST NOT WALK. `derive_sub_indexes`
walks the whole tree — 24.6 s on the reporting repository — and `targets` is the
orientation call, often a session's first. A build of any sub-index has already paid
that walk, so it records what it found and the listing reads it back for nothing.
ON EVERY RECORD OF THE REPOSITORY, not one. The registry is keyed by slug, so a split
repository owns several entries and any of them may be the one a reader reaches first;
writing the note once would make the answer depend on which sub-index happened to be
registered earliest.
@brief Persist the derived split for later listing.
@return None.
@version 1
"""
data = self.load()
listed = list(names)
touched = False
for rec in data.values():
if rec.get("repo_path") == repo_path:
rec["derived"] = listed
touched = True
if touched:
self.save(data)
Activity · 9 steps
Requirements
register
Target clew.mcp_server.state.TargetRegistry.register(self, Path|str repo_path, str|None name=None)
Register (or re-register) a repo and allocate its db path.
Source · 39 lines
def register(self, repo_path: Path | str, name: str | None = None) -> Target:
"""Allocate the Target for `repo_path`, persist it, and ensure its
db directory exists so a build can write there.
`name` registers a SUB-INDEX of the repository — several indexes under one root, so a
repo vendoring pinned submodules builds them once and rebuilds only first-party code
thereafter.
`repo_path` IS WRITTEN INTO THE RECORD from here on, and that is what makes a composite
key safe: `targets()` reconstructs a Target from the key when the field is absent, which
is correct for every entry written before sub-indexes existed and wrong for a composite
one. Storing it removes the need for the reader to parse the key at all.
@brief Register a target repo, or one of its sub-indexes.
@return The registered Target.
@version 4
"""
target = target_for(repo_path, self.home, name)
data = self.load()
## THE LEGACY ROW FOR THIS SAME TARGET GOES WITH THE WRITE. The registry was keyed by
## repo path and is now keyed by slug, and re-registering wrote the new row beside the
## old one rather than in place of it — measured on this machine: one repository listed
## twice by `index(action='targets')`, and counted twice by every sibling lookup. Guarded
## on the SLUG so a sub-index registration cannot drop the whole repository's row.
legacy = data.get(str(target.repo_path))
if isinstance(legacy, dict) and legacy.get("slug", target.slug) == target.slug:
data.pop(str(target.repo_path), None)
record = {
"slug": target.slug,
"db_path": target.db_path,
"repo_path": target.repo_path,
}
if name is not None:
record["name"] = name
data[target.slug] = record
self.save(data)
Path(target.db_path).parent.mkdir(parents=True, exist_ok=True)
return target
Activity · 12 steps
Requirements
root_uri_to_path
Path | None clew.mcp_server.state.root_uri_to_path(str uri)
Convert one MCP root URI into a local directory path.
Source · 25 lines
def root_uri_to_path(uri: str) -> Path | None:
"""`file://` ONLY, and it must resolve to an existing directory.
A root is a client-supplied string, and this server turns it into a repo it will
index — so it fails closed on anything it cannot verify. A non-`file` scheme is
not a working tree at all; a `file` URI naming a missing path or a plain file is
not a repo root. Returning None for those lets the caller keep walking the root
list instead of adopting the first thing it was handed.
`url2pathname` after `unquote` rather than string surgery on the URI: a
percent-encoded path (a space in a directory name is enough) reaches here encoded,
and slicing `uri[7:]` would produce a path that does not exist and would therefore
be rejected by the `is_dir` check for entirely the wrong reason.
@brief Parse a root URI into a verified local directory.
@return The directory, or None.
@version 1
"""
parsed = urlsplit(str(uri))
if parsed.scheme != "file" or not parsed.path:
return None
path = Path(url2pathname(unquote(parsed.path)))
return path if path.is_dir() else None
Activity · 5 steps
Requirements
Flows
roots_request_supported
bool clew.mcp_server.state.roots_request_supported(str|None version)
Whether a standalone roots/list request is carriable at this protocol revision.
Called by _roots_askable
Tested by
Source · 27 lines
def roots_request_supported(version: str | None) -> bool:
"""FAILS OPEN, deliberately, on every unknown: an unstated revision, a revision the
SDK does not recognise, and an unreadable method map all return True. A
wrongly-refused request costs a target the client could have supplied and hides the
reason; a wrongly-attempted one costs a caught exception and one log line.
THE "KNOWN" TERM IS LOAD-BEARING AND WAS MISSING IN THE FIRST VERSION, which asked
only whether the map listed `(roots/list, version)` — so any revision string the SDK
had never heard of was REFUSED. That is backwards for the case that actually matters: a
future revision restoring the request would be silently declined by an older
installation of this server. A control assertion caught it.
So only a revision the SDK positively KNOWS and does not list is refused, which today
is exactly 2026-07-28, whose surface carries no server-to-client requests at all.
Derived from the SDK rather than compared against a literal revision, so the day a
revision restores the standalone request this follows without an edit.
@brief Decide whether `roots/list` can be sent on this connection.
@return Whether to attempt the request.
@version 2
"""
surface = server_request_surface()
if surface is None or version not in known_protocol_versions():
return True
return (TARGET_SOURCE_ROOTS, version) in surface
Activity · 4 steps
Flows
save
None clew.mcp_server.state.TargetRegistry.save(self, dict[str, dict[str, str]] data)
Persist the registry mapping to disk.
Source · 20 lines
def save(self, data: dict[str, dict[str, str]]) -> None:
"""Write the registry, creating the state root on demand.
STAGE THEN RENAME, because `write_text` truncates the destination before filling it
and a reader arriving in that window reads an empty registry rather than failing.
`os.replace` is atomic within a filesystem, and the staging file is a sibling so it
always is one.
The staging name carries the PID so two processes saving at once cannot corrupt each
other's half-written file; the rename is what serialises them, and last writer wins —
which is the pre-existing whole-file-replacement semantics, now actually delivered.
@brief Persist the registry mapping atomically.
@version 2
"""
self.home.mkdir(parents=True, exist_ok=True)
staging = self.path.with_name(f"{self.path.name}.{os.getpid()}.tmp")
staging.write_text(json.dumps(data, indent=2, sort_keys=True), encoding="utf-8")
os.replace(staging, self.path)
Activity · 4 steps
Requirements
server_request_surface
Mapping[tuple[str, str], object] | None clew.mcp_server.state.server_request_surface()
The SDK's server-to-client request surface, or None when it cannot be read.
Source · 18 lines
def server_request_surface() -> Mapping[tuple[str, str], object] | None:
"""Read the SDK's own per-revision method map instead of hardcoding revisions.
Returns None — meaning "unknown", never "empty" — when the map cannot be imported,
so a future SDK reshuffle degrades to attempting the call rather than to silently
refusing to. The attempt already fails closed at the call site.
@brief Locate the SDK's (method, version) server-request map.
@return The map, or None when unavailable.
@version 2
"""
try:
from mcp_types.methods import SERVER_REQUESTS
except Exception:
return None
return SERVER_REQUESTS
Activity · 5 steps
Flows
startup_target
tuple[str | None, str | None] clew.mcp_server.state.startup_target(str|None explicit, Mapping[str, str]|None env=None)
Resolve the target available BEFORE any request, and say where it came from.
Source · 33 lines
def startup_target(
explicit: str | None, env: Mapping[str, str] | None = None
) -> tuple[str | None, str | None]:
"""The eager half of target resolution: `--repo`, then `$CLAUDE_PROJECT_DIR`.
Both are readable at process start, so a target found here brings the tier-1
query tools up on connect. The third source — the client's `roots/list` — is
NOT readable here and cannot be: the only route to it is
`ctx.session.list_roots()`, which needs a live request, and there is no session
during `main()`. That asymmetry is why resolution is split across two functions
rather than expressed as one ordered list.
THE TWO SOURCES ARE VALIDATED DIFFERENTLY, on purpose. `--repo` is taken as
given: an operator typed it, and a wrong path should fail loudly at the first
query rather than be silently ignored in favour of something else. An
environment variable is not a declaration about THIS server — it describes the
client's session and may name a directory that has been moved or deleted — so it
must prove it is a directory before it is adopted. Adopting a phantom would
consume the resolution chain and prevent the `roots/list` fallback from ever
running, which is the failure this ordering exists to avoid.
@brief Resolve a target from the flag or the environment.
@return (repo path or None, source label or None).
@version 1
"""
if explicit:
return explicit, TARGET_SOURCE_FLAG
declared = (env if env is not None else os.environ).get(PROJECT_DIR_ENV)
if declared and Path(declared).expanduser().is_dir():
return declared, TARGET_SOURCE_ENV
return None, None
Activity · 6 steps
Requirements
state_home
Path clew.mcp_server.state.state_home()
Per-user state root for built databases and the registry.
Called by __init__, open_main, serve, target_for
Tested by 1 tests
test_state_home_env_override
Calls none
Source · 17 lines
def state_home() -> Path:
"""Resolve the state root, env-overridable and XDG-aware — never a hardcoded machine
path, because this path is reported in payloads and a home directory in one of those
is a machine-layout disclosure.
@brief Resolve the per-user clew state directory.
@return Path to the state root.
@version 3
"""
override = os.environ.get(STATE_HOME_ENV)
if override:
return Path(override).expanduser()
xdg = os.environ.get("XDG_STATE_HOME")
base = Path(xdg).expanduser() if xdg else Path.home() / ".local" / "state"
return base / STATE_DIR_NAME
Activity · 6 steps
Requirements
Flows
target_for
Target clew.mcp_server.state.target_for(Path|str repo_path, Path|None home=None, str|None name=None)
Allocate the Target record for a repo path (pure; no I/O).
Called by _build_subject, _built_on_disk, _first_build_worker, _legacy_and_slug_rows, _locate, _locate, _probe_repo, _register_built_target, _register_prompts, _resolve_output, _stale, adopt
Tested by 34 tests
test_a_cli_build_registers_the_target_it_wrote, test_a_declaration_applies_only_to_the_sub_index_it_names, test_a_declared_exclude_reaches_the_named_sub_index, test_a_declared_name_that_is_not_a_sub_index_is_refused, test_a_first_party_target_adds_nested_excludes, test_a_hit_whose_callees_are_unresolved_says_which_parts_it_did_not_read, test_a_hostile_name_cannot_escape_the_state_directory, test_a_named_target_is_distinct, test_a_non_positive_cull_age_leaves_every_current_index_alone, test_a_query_refreshes_only_when_the_data_axis_is_stale, test_a_registered_sub_index_whose_tree_vanished_refuses_and_names_the_route, test_a_running_hub_is_opened_instead_and_a_dead_one_ignored 22 more
test_a_stated_block_wins_over_the_declared_one, test_a_stated_sub_index_scope_reaches_the_build, test_a_sub_index_name_that_matches_nothing_is_refused, test_a_vendored_target_is_scoped_to_its_tree, test_a_whole_repo_target_is_never_refused, test_a_whole_repo_target_keeps_the_callers_scope, test_an_unknown_key_inside_a_block_is_refused_by_name, test_an_unnamed_target_is_unchanged, test_an_unregistered_sub_index_derives_its_own_target, test_an_unsplit_repository_refuses_any_sub_index_by_saying_so, test_every_derived_name_is_accepted, test_first_party_honours_its_own_declared_excludes, test_named_allocation_is_deterministic, test_one_repository_registered_twice_is_listed_once, test_registering_removes_the_legacy_row_it_supersedes, test_target_slug_disambiguates_same_named_checkouts, test_the_background_pass_refreshes_only_indexes_this_session_used, test_the_dossier_body_takes_the_repo_root_from_the_server_not_the_model, test_the_refusal_happens_before_the_build_lock_is_taken, test_the_refusal_names_top_level_trees_and_counts_the_rest, test_the_scope_helper_raises_rather_than_widening, test_without_a_hub_the_static_site_is_built_and_opened
Calls _safe_index_name, state_home
Source · 40 lines
def target_for(repo_path: Path | str, home: Path | None = None, name: str | None = None) -> Target:
"""Derive `<name>-<sha1[:6]>` from the resolved repo path so distinct
checkouts of the same project get distinct db directories.
`name` ALLOCATES A SUB-INDEX of one repository — several indexes under one root, so a repo
that vendors its dependencies as submodules can build them once (they are pinned, therefore
immutable) and rebuild only first-party code on every later refresh. Measured on a target
vendoring llama.cpp: 592 files and 13.9 s split, against 3,521 files and 69.0 s whole.
THE UNNAMED SPELLING IS FROZEN, and that is the constraint this function is written around.
Every index already on disk lives at a path derived from the unnamed rule, and nothing records
where it came from — so changing it strands those indexes rather than migrating them, and the
symptom is "no database has been built for this repo yet" against a perfectly good index. The
name is therefore appended to a slug that is otherwise computed exactly as before, and the
digest still covers the PATH ONLY so an unnamed slug is byte-identical to its history.
THE NAME IS SANITISED BECAUSE IT REACHES A FILESYSTEM PATH. Sub-index names come from a
repository's own `.clew.yaml`, which is untrusted input by this project's standing rule, and
a name of `../../etc` would otherwise place a database outside the state root. Reduced to
`[A-Za-z0-9._-]`, refused when nothing survives — a rejection is recoverable, a write outside
the state directory is not.
@brief Derive a Target (slug + db path) for a repo root, optionally a named sub-index.
@return Target for `repo_path`, or for one of its sub-indexes.
@version 3
"""
repo = Path(repo_path).expanduser().resolve()
digest = hashlib.sha1(str(repo).encode("utf-8")).hexdigest()[:6]
slug = f"{repo.name}-{digest}"
if name is not None:
slug = f"{slug}.{_safe_index_name(name)}"
root = home if home is not None else state_home()
return Target(
repo_path=str(repo),
slug=slug,
db_path=str(root / "targets" / slug / DB_NAME),
name=name,
)
Activity · 7 steps
Requirements
Flows
targets
list[Target] clew.mcp_server.state.TargetRegistry.targets(self)
Every registered target.
Source · 30 lines
def targets(self) -> list[Target]:
"""Rebuild Target records from the persisted mapping.
@brief List all registered targets.
@return List of Target.
@version 3
"""
## `repo_path` FALLS BACK TO THE KEY, which is exactly right for every entry written
## before sub-indexes existed — there the key IS the repo path — and is never reached for
## a composite key, because `register` writes the field whenever it writes one.
##
## DE-DUPLICATED BY SLUG, on the READ side as well as the write side, so a registry that
## already holds both shapes for one target is listed correctly on the next call rather
## than on the next build. The slug IS the identity: it is derived from (repo path,
## sub-index name), so two rows carrying one slug are two spellings of one database. The
## row that names its own `repo_path` wins, because the other's path comes from a key
## whose format predates sub-indexes.
found: dict[str, Target] = {}
for repo, rec in sorted(self.load().items()):
slug = rec.get("slug", "")
target = Target(
repo_path=rec.get("repo_path") or repo,
slug=slug,
db_path=rec.get("db_path", ""),
name=rec.get("name"),
)
if slug not in found or rec.get("repo_path"):
found[slug] = target
return list(found.values())