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.

acceptance/provision.py:293

Show on the map →

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
lines 309–323argv = [ "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()), ]lines 324–324trylines 325–327done = subprocess.run( argv, capture_output=True, text=True, timeout=300, check=False, cwd=str(repo) )lines 328–328reply = str(json.loads(done.stdout).get("result") or "")lines 329–329except (OSError, subprocess.TimeoutExpired, json.JSONDecodeError) as exclines 330–330raise ProvisionError(f"index-tool probe could not run: {exc}") from exclines 341–341◇ if any(phrase in reply.lower() for phrase in CAPACITY_PHRASES)lines 342–347raise 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." )lines 348–348◇ if "NOTOOL" in reply.upper() or "FOUND" not in reply.upper()lines 349–354raise 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." )

Flows

fetch_pinned

None acceptance.provision.fetch_pinned(Rubric rubric, Path repo)

Fetch a target's pinned commit into a working tree.

acceptance/provision.py:105

Show on the map →

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
lines 116–116◇ if (repo / ".git").exists()lines 117–117head = _git(repo, "rev-parse", "HEAD")lines 118–118◇ if head == rubric.commitlines 119–119returnlines 120–120elselines 121–121repo.mkdir(parents=True, exist_ok=True)lines 122–122_git(repo, "init", "--quiet", ".")lines 123–123_git(repo, "remote", "add", "origin", f"https://github.com/{rubric.target}.git")lines 124–124_git(repo, "fetch", "--quiet", "--depth", "1", "origin", rubric.commit)lines 125–125_git(repo, "checkout", "--quiet", "--force", rubric.commit)

Flows

main

int acceptance.provision.main()

CLI entry point.

acceptance/provision.py:468

Show on the map →

Called by none

Calls provision

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
lines 473–473parser = argparse.ArgumentParser(prog="acceptance.provision", description=__doc__)lines 474–474parser.add_argument("--rubric", type=Path, required=True)lines 475–475parser.add_argument("--root", type=Path, required=True)lines 476–476args = parser.parse_args()lines 477–477trylines 478–478rubric = load(args.rubric)lines 479–479except RubricError as exclines 480–480print(f"REFUSED — {exc}", file=sys.stderr)lines 481–481return 1lines 482–482trylines 483–483out = provision(rubric, args.root)lines 484–484except ProvisionError as exclines 485–485print(f"REFUSED — {exc}", file=sys.stderr)lines 486–486return 1lines 487–487print(f"{rubric.target} @ {rubric.commit[:10]}")lines 488–488print(f" repo {out.repo}")lines 489–489print(f" index {out.db} (build {out.build_version})")lines 490–490print(f" mcp {out.mcp_config}")lines 491–491return 0

Flows

provision

Provisioned acceptance.provision.provision(Rubric rubric, Path root)

Version 2 refuses a modified or unidentifiable clew tree before fetching anything.

acceptance/provision.py:405

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
lines 415–415trylines 416–416check_tool_tree()lines 417–417except ValueError as exclines 418–418raise ProvisionError(str(exc)) from exclines 419–419root.mkdir(parents=True, exist_ok=True)lines 420–420root = root.resolve()lines 421–421repo = root / "repo"lines 422–422state_home = root / "state"lines 424–424fetch_pinned(rubric, repo)lines 425–425trylines 426–426check_revision(rubric, repo)lines 427–427except ValueError as exclines 428–428raise ProvisionError(str(exc)) from exclines 430–430declare_file: Path | None = Nonelines 431–431◇ if rubric.declarelines 432–432import yamllines 434–434declare_file = root / "declaration.yaml"lines 435–435declare_file.write_text(yaml.safe_dump(rubric.declare, sort_keys=False), encoding="utf-8")lines 437–437build_index(rubric, repo, state_home, declare_file)lines 440–440built = sorted((state_home / "targets").glob("*/clew.db"))lines 441–441◇ if len(built) != 1lines 442–445raise ProvisionError( f"expected exactly one index under {state_home}/targets, found {len(built)}: " f"{[str(b) for b in built]}" )lines 446–446db = built[0]lines 447–447meta = read_build_meta(db)lines 448–448trylines 449–449check_declaration_applied(rubric, meta)lines 450–450except ValueError as exclines 451–451raise ProvisionError(str(exc)) from exclines 453–453config = root / "mcp.json"lines 454–454write_mcp_config(db, repo, config, state_home)lines 455–455check_index_tools_reachable(config, repo)lines 456–456write_provision_record(rubric, db, meta, root / "provision.json")lines 457–462return Provisioned( repo=repo, db=db, mcp_config=config, build_version=str(meta.get("build_version", "")), )

Flows

read_build_meta

dict acceptance.provision.read_build_meta(Path db)

Read a built index's build_meta rows.

acceptance/provision.py:132

Show on the map →

Called by provision, test_absent_index_is_refused

Calls none

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
lines 140–140◇ if not db.is_file()lines 141–141raise ProvisionError(f"{db}: no index was written")lines 142–142conn = sqlite3.connect(str(db))lines 143–143trylines 144–144rows = dict(conn.execute("SELECT key, value FROM build_meta").fetchall())lines 145–145except sqlite3.Error as exclines 146–146raise ProvisionError(f"{db}: cannot read build_meta: {exc}") from exclines 149–149return rows

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.

acceptance/provision.py:236

Show on the map →

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
lines 245–245◇ if not db.is_file()lines 246–248raise ProvisionError( f"{db}: refusing to write an MCP config for an index that does not exist" )lines 249–249path.parent.mkdir(parents=True, exist_ok=True)lines 250–285path.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", )

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.

acceptance/provision.py:364

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")

Activity · 3 steps
lines 381–381from .identity import tool_identitylines 383–394record = { "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(), }lines 395–395path.write_text(json.dumps(record, indent=2), encoding="utf-8")

Flows