provision.py¶
acceptance/provision.py
Put a target on disk at its pinned commit, index it, and write the index arm's MCP config.
check_index_tools_reachable
None acceptance.provision.check_index_tools_reachable(Path config, Path repo)
Refuse unless the written config actually surfaces the index tools.
Called by provision, test_probe_distinguishes_a_blocked_probe_from_a_missing_index
Calls none
Source · 64 lines
def check_index_tools_reachable(config: Path, repo: Path) -> None:
"""THE ONLY CHECK THAT DISTINGUISHES A WORKING INDEX ARM FROM A SILENT ONE.
Every earlier signal was absent by construction: the server starts, exits 0, writes nothing
to stderr, the agent raises no denial, and the run reports every cell ok. Twice a config that
surfaced NO TOOLS produced four plausible answers, and the only evidence was a tool count
nobody had a reason to read until the numbers looked odd.
So this SPENDS ONE CHEAP CALL before any cell is generated. A probe that costs a fraction of
a cell and refuses is strictly better than a run that costs all of them and cannot be
interpreted.
@brief The index arm can actually reach the index.
@return None.
@version 1
"""
argv = [
"claude",
"-p",
"Call the clew search tool with text 'int' and corpus 'symbols'. "
"Reply with the single word FOUND, or NOTOOL if no such tool exists.",
"--model",
"sonnet",
"--output-format",
"json",
"--allowedTools",
"mcp__clew__dossier,mcp__clew__search,mcp__clew__index",
"--strict-mcp-config",
"--mcp-config",
str(config.resolve()),
]
try:
done = subprocess.run(
argv, capture_output=True, text=True, timeout=300, check=False, cwd=str(repo)
)
reply = str(json.loads(done.stdout).get("result") or "")
except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError) as exc:
raise ProvisionError(f"index-tool probe could not run: {exc}") from exc
## A PROBE THAT COULD NOT RUN IS NOT AN UNREACHABLE INDEX, and reporting them alike sends an
## operator hunting a config defect that does not exist. Measured on this grid's own
## pre-flight: two targets were refused with "the index arm cannot reach the index" and the
## quoted reply was "You've hit your session limit". The index was fine.
##
## The two failures need OPPOSITE responses — fix the config, versus wait and re-run the
## identical command — so they get different refusals.
## ONE LIST, SHARED WITH THE JUDGE. Both have to tell a capacity refusal from a real
## failure, and two copies of the vocabulary drift into one of them recognising a phrase
## the other does not — which reads as the two phases disagreeing about the machine.
if any(phrase in reply.lower() for phrase in CAPACITY_PHRASES):
raise ProvisionError(
f"index-tool probe could not run — the model refused before reaching the tools:\n"
f"{reply[:300]}\n"
f"This says NOTHING about {config}. Re-run the identical command once capacity "
f"returns; nothing has been generated and nothing needs fixing."
)
if "NOTOOL" in reply.upper() or "FOUND" not in reply.upper():
raise ProvisionError(
f"the index arm cannot reach the index through {config}. The probe replied:\n"
f"{reply[:400]}\n"
f"Generating cells now would produce an index arm answering from source with no "
f"error anywhere — which has happened twice and is invisible in the artifacts."
)
Activity · 10 steps
Flows
fetch_pinned
None acceptance.provision.fetch_pinned(Rubric rubric, Path repo)
Fetch a target's pinned commit into a working tree.
Called by provision, test_existing_checkout_at_the_pin_is_not_refetched, test_fetch_asks_for_the_sha_not_a_branch
Calls _git
Source · 23 lines
def fetch_pinned(rubric: Rubric, repo: Path) -> None:
"""Idempotent: an existing tree already at the pin is left alone, so re-provisioning costs
nothing and a run can resume.
Submodules are NOT initialised. A target that declares one gets a second remote that can be
unreachable, and the pinned commit's own tree is what the rubric was verified against.
@brief Put the pinned commit on disk.
@return None.
@version 1
"""
if (repo / ".git").exists():
head = _git(repo, "rev-parse", "HEAD")
if head == rubric.commit:
return
else:
repo.mkdir(parents=True, exist_ok=True)
_git(repo, "init", "--quiet", ".")
_git(repo, "remote", "add", "origin", f"https://github.com/{rubric.target}.git")
_git(repo, "fetch", "--quiet", "--depth", "1", "origin", rubric.commit)
_git(repo, "checkout", "--quiet", "--force", rubric.commit)
Activity · 10 steps
Flows
main
int acceptance.provision.main()
CLI entry point.
Source · 26 lines
def main() -> int:
"""@brief Provision a target from its rubric.
@return Exit code.
@version 1
"""
parser = argparse.ArgumentParser(prog="acceptance.provision", description=__doc__)
parser.add_argument("--rubric", type=Path, required=True)
parser.add_argument("--root", type=Path, required=True)
args = parser.parse_args()
try:
rubric = load(args.rubric)
except RubricError as exc:
print(f"REFUSED — {exc}", file=sys.stderr)
return 1
try:
out = provision(rubric, args.root)
except ProvisionError as exc:
print(f"REFUSED — {exc}", file=sys.stderr)
return 1
print(f"{rubric.target} @ {rubric.commit[:10]}")
print(f" repo {out.repo}")
print(f" index {out.db} (build {out.build_version})")
print(f" mcp {out.mcp_config}")
return 0
Activity · 19 steps
Flows
provision
Provisioned acceptance.provision.provision(Rubric rubric, Path root)
Version 2 refuses a modified or unidentifiable clew tree before fetching anything.
Tested by
Calls check_declaration_applied, check_index_tools_reachable, check_revision, check_tool_tree, fetch_pinned, read_build_meta, write_mcp_config, write_provision_record
Source · 60 lines
def provision(rubric: Rubric, root: Path) -> Provisioned:
"""Every step refuses rather than degrades, and the order is what makes the refusals mean
something — see the module docstring.
@brief Provision a target.
@return Provisioned.
@version 3
"""
## THE CLEW TREE FIRST, before the fetch and the build — the expensive steps, both
## worthless if the code that would answer cannot be named.
try:
check_tool_tree()
except ValueError as exc:
raise ProvisionError(str(exc)) from exc
root.mkdir(parents=True, exist_ok=True)
root = root.resolve()
repo = root / "repo"
state_home = root / "state"
fetch_pinned(rubric, repo)
try:
check_revision(rubric, repo)
except ValueError as exc:
raise ProvisionError(str(exc)) from exc
declare_file: Path | None = None
if rubric.declare:
import yaml
declare_file = root / "declaration.yaml"
declare_file.write_text(yaml.safe_dump(rubric.declare, sort_keys=False), encoding="utf-8")
build_index(rubric, repo, state_home, declare_file)
## FOUND, NOT COMPUTED. The slug is the server's business; globbing the state root it was
## just given avoids reimplementing that derivation and drifting from it.
built = sorted((state_home / "targets").glob("*/clew.db"))
if len(built) != 1:
raise ProvisionError(
f"expected exactly one index under {state_home}/targets, found {len(built)}: "
f"{[str(b) for b in built]}"
)
db = built[0]
meta = read_build_meta(db)
try:
check_declaration_applied(rubric, meta)
except ValueError as exc:
raise ProvisionError(str(exc)) from exc
config = root / "mcp.json"
write_mcp_config(db, repo, config, state_home)
check_index_tools_reachable(config, repo)
write_provision_record(rubric, db, meta, root / "provision.json")
return Provisioned(
repo=repo,
db=db,
mcp_config=config,
build_version=str(meta.get("build_version", "")),
)
Activity · 33 steps
Flows
read_build_meta
dict acceptance.provision.read_build_meta(Path db)
Read a built index's build_meta rows.
Source · 20 lines
def read_build_meta(db: Path) -> dict:
"""Returns the nested `options` shape `check_declaration_applied` expects, built from the
flat `key`/`value` rows the pipeline stamps.
@brief Build metadata as a mapping.
@return build_meta.
@version 1
"""
if not db.is_file():
raise ProvisionError(f"{db}: no index was written")
conn = sqlite3.connect(str(db))
try:
rows = dict(conn.execute("SELECT key, value FROM build_meta").fetchall())
except sqlite3.Error as exc:
raise ProvisionError(f"{db}: cannot read build_meta: {exc}") from exc
finally:
conn.close()
return rows
Activity · 8 steps
Flows
write_mcp_config
None acceptance.provision.write_mcp_config(Path db, Path repo, Path path, Path state_home)
Write the MCP config the index arm needs.
Called by provision, test_mcp_config_names_the_target, test_mcp_config_refuses_without_an_index, test_the_index_arm_server_gets_the_plugins_environment
Calls _plugin_server_env
Source · 52 lines
def write_mcp_config(db: Path, repo: Path, path: Path, state_home: Path) -> None:
"""WRITTEN LAST, so it cannot exist before the index it points at. A config naming a database
that was never built sends the index arm to an empty index, which answers — badly — rather
than refusing.
@brief Write the index arm's MCP config.
@return None.
@version 2
"""
if not db.is_file():
raise ProvisionError(
f"{db}: refusing to write an MCP config for an index that does not exist"
)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(
json.dumps(
{
"mcpServers": {
"clew": {
## THE CONSOLE SCRIPT, NOT `python -m`. Measured: with
## `-m clew.mcp_server.server` the server appeared to start, emitted no
## error, and registered NO TOOLS AT ALL — not even the tier-0 ones that
## need no database. An agent given that config answered from source and
## the run reported 4/4 ok. `clew-mcp` is the entry point the package
## declares and the only one observed to work.
"command": str(Path(sys.executable).parent / "clew-mcp"),
## ABSOLUTE, AND THIS IS THE SECOND TIME A RELATIVE PATH BROKE THE
## INDEX ARM. The server subprocess inherits the ANSWERING agent's cwd —
## the target checkout — so a relative --repo resolves inside the target,
## finds no database, and registers no query tools.
##
## MEASURED: the server started cleanly, emitted no error, the agent
## raised no denial, and the run reported 4/4 ok. The index arm answered
## WITHOUT ITS INDEX and produced prose indistinguishable from a real
## cell. The only signal was that it made ZERO index calls.
"args": ["--repo", str(repo.resolve())],
## THE SAME STATE ROOT THE BUILD USED. The server derives its database
## from --repo under this root, so config and build cannot disagree.
##
## AND THE PLUGIN'S OWN SERVER ENVIRONMENT (1.4.0): the plugin sets
## `CLEW_WIRE=compact`, so an index arm without it would measure a reply
## shape no plugin user receives. Read from plugin.json, never restated.
"env": {**_plugin_server_env(), "CLEW_STATE_HOME": str(state_home)},
}
}
},
indent=2,
),
encoding="utf-8",
)
Activity · 4 steps
Flows
write_provision_record
None acceptance.provision.write_provision_record(Rubric rubric, Path db, dict meta, Path path)
Record what built this target's index, in a file that survives the run.
Source · 34 lines
def write_provision_record(rubric: Rubric, db: Path, meta: dict, path: Path) -> None:
"""THE ONLY PLACE THE BUILD'S OWN IDENTITY REACHES A COMMITTED FILE. `build_version` was
read here and only PRINTED, so it survived a run solely if the operator happened to redirect
stdout — and the database that carries it is gitignored, deliberately, because it is
reproducible from the pin. The consequence was a published score attributable to a target
and a rubric but not to a version of clew.
WRITTEN AFTER THE INDEX-TOOL PROBE, so a record exists only for a target that an index arm
can actually reach. A record beside an unreachable index would describe a build that no cell
ever queried.
EVERY FIELD IS DROPPED WHEN UNREADABLE rather than written blank — see `acceptance.identity`.
@brief Write provision.json.
@return None.
@version 1
"""
from .identity import tool_identity
record = {
"target": rubric.target,
"commit": rubric.commit,
"rubric_version": rubric.version,
"db": str(db),
**{
key: str(meta[key])
for key in ("build_version", "tool.substrate_version")
if meta.get(key)
},
**tool_identity(),
}
path.write_text(json.dumps(record, indent=2), encoding="utf-8")