From 93622a47c0a9bce9e77ab470a18e4539874f1295 Mon Sep 17 00:00:00 2001 From: Mateusz Lewandowski Date: Mon, 23 Nov 2026 18:55:49 +0100 Subject: [PATCH 1/3] Stabilize MCP and Node diagnostics and verify benchmark preparation --- .github/workflows/ci.yml | 9 +- TODO.md | 12 +- docs/BENCHMARKS.md | 56 ++++- docs/MCP_SERVER.md | 4 + examples/benchmarks/real-agent-repair.json | 28 +++ examples/benchmarks/repository-monorepo.json | 38 +++ examples/benchmarks/repository-small.json | 38 +++ scripts/benchmark_real_agent.py | 78 ++++++ scripts/benchmark_repository.py | 244 +++++++++++++++++++ scripts/test_installed_package.py | 17 +- scripts/validate_ci.py | 2 +- src/ai_dev_tools/mcp_server.py | 9 +- src/ai_dev_tools/parsers/logs.py | 37 ++- src/ai_dev_tools/runners/benchmark.py | 50 +++- tests/unit/test_benchmark.py | 54 +++- tests/unit/test_benchmark_gate.py | 42 +++- tests/unit/test_issue_regressions.py | 55 +++++ tests/unit/test_mcp_server.py | 46 +++- 18 files changed, 767 insertions(+), 52 deletions(-) create mode 100644 examples/benchmarks/real-agent-repair.json create mode 100644 examples/benchmarks/repository-monorepo.json create mode 100644 examples/benchmarks/repository-small.json create mode 100644 scripts/benchmark_real_agent.py create mode 100644 scripts/benchmark_repository.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d3181d5..0ad01f3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,7 +31,7 @@ jobs: - run: python -m pip install --upgrade pip - run: python -m pip install -c requirements-dev.lock -e ".[dev]" - run: ruff check . - - run: mypy src tests + - run: mypy src tests scripts - run: coverage run -m pytest - run: coverage report --fail-under=90 - run: python -m build @@ -91,12 +91,17 @@ jobs: with: python-version: "3.13" - run: python -m pip install -c requirements-dev.lock -e ".[dev]" - - name: Run real-agent regression corpus + - name: Run scripted agent workflow regression corpus run: >- ai-dev benchmark corpus --manifest examples/benchmarks/agent-corpus.json --trials 3 --timeout 60 + - name: Verify a primed repository workflow + run: >- + ai-dev benchmark run + --suite examples/benchmarks/repository-small.json + --variant ai-dev --cache-state warm --trials 1 --timeout 120 - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: always() with: diff --git a/TODO.md b/TODO.md index 36d2ddc..d63a482 100644 --- a/TODO.md +++ b/TODO.md @@ -9,10 +9,14 @@ cross-platform behavior are covered where applicable. ## Active work -There are no known incomplete P1 or P2 implementation items for the 1.0-1.2 contracts. The planned -product capability set is complete. New work is maintenance and must be justified by a supported -platform change, security issue, dependency update, reproducible regression, or backward-compatible -integration requirement. +The [development tracker](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/144) links to +current acceptance criteria. The roadmap documents the capabilities shipped in the 1.x contracts. + +| Priority | Issues | +| --- | --- | +| P0 | [MCP metadata #131](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/131), [correctness gate #134](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/134), [agent measurement #133](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/133) | +| P1 | [Node diagnostics #128](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/128), [repository navigation #136](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/136), [MCP symbol lookup #137](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/137), [module responsibilities #135](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/135), [adoption #138](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/138), [failure loops #139](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/139), [affected tests #140](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/140) | +| P2 | [Verified repository knowledge #141](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/141), [FTS5 evaluation #142](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/142), [native profiling #143](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/143) | ## Deferred or explicitly out of scope diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.md index e4a69f7..03f481b 100644 --- a/docs/BENCHMARKS.md +++ b/docs/BENCHMARKS.md @@ -43,11 +43,14 @@ The corpus includes a repeated MCP `build_context` task that compares a forced f an explicitly acknowledged unchanged receipt. Both variants must retain the same outcome, precision, and recall while the receipt satisfies the configured token-reduction threshold. -Cold and warm results are deliberately separate and cannot be compared with each other. A -comparison is valid only when the suite name, fixture version, cache state, and validated outcome -signatures match and every trial succeeds. - -Each run records median end-to-end time, time to an actionable result, standard deviation, +Cold and warm results are compared within the same cache state. Give a suite an optional +`warmup_command` array to prime the cache after each reset and before each measured warm trial. +The warmup must succeed. Its time is recorded separately. Existing suites without a warmup +report `cache_preparation: reset_only`; use their reset semantics when interpreting the label. +A comparison requires the same suite, fixture version, cache preparation, and outcome signatures. + +Each run records median and nearest-rank p95 for end-to-end and measured execution time, +time to an actionable result, standard deviation, commands, validation subprocesses, masked agent-visible bytes, estimated tokens, timeouts, correctness, fixture identity, and a local machine profile. Token estimates use masked_utf8_bytes_divided_by_4; they are a stable approximation, not a model tokenizer claim. @@ -57,7 +60,7 @@ Raw JSON and compact Markdown reports stay under `.ai/benchmarks/`. bounds, required token reduction is not achieved, precision/recall fall below their floors, or false negatives exceed the allowance. Use `--min-token-reduction PERCENT` to require a measured improvement rather than merely permitting no regression. The -versioned corpus runs six representative agent tasks, including adaptive-off versus adaptive-on +versioned corpus runs seven scripted agent tasks, including adaptive-off versus adaptive-on context selection and full versus session-delta feedback, and applies the shared thresholds from `examples/benchmarks/agent-corpus.json`; it is suitable as a CI release gate. @@ -74,8 +77,9 @@ recall were not reported; their zero medians must not be interpreted as measured Use `--client codex|claude|cursor|gemini|generic` to label runs from a real client adapter. A real adapter should emit `input_tokens` or `output_tokens` in its private metrics line. The -`--require-reported-tokens` gate fails unless every candidate trial contains provider-reported -usage; this prevents estimated character counts from being presented as real client token data. +`--require-reported-tokens` gate requires provider-reported usage in every trial of both variants. +Use the same instrumentation in both variants. The gate checks input and output token medians +separately from the estimate gate. Every comparison and gate is advisory and requires human approval. A passing candidate that is both faster and smaller returns `adopt_candidate`; a passing tradeoff returns `keep_baseline`; any @@ -130,3 +134,39 @@ ai-dev benchmark run --suite examples/benchmarks/agent-repair-workflow.json --va ai-dev benchmark run --suite examples/benchmarks/agent-repair-workflow.json --variant ai-dev --trials 3 --cache-state cold ai-dev benchmark compare .ai/benchmarks/runs/.json .ai/benchmarks/runs/.json ~~~ + +## Repository and real-agent trials + +`repository-small.json` and `repository-monorepo.json` use generated Git fixtures. The larger +fixture has 40 Python workspaces and 1,000 workload modules. Each trial measures CLI startup, +scan, index and semantic index, a repeated index invocation, Git inspection after editing a file, +symbol lookup, context building, affected-test planning, and MCP startup plus `project_status`. +The validator independently checks fixture coverage, the edited file hash, old/new symbols, +cache reuse, the expected test selection, and the MCP result. Baseline forces repository index +rebuilds, while the candidate updates incrementally. The optional warmup builds both indexes. + +Run both variants for each cache state and size, serially in a given checkout. Use 20 or more +trials for tail analysis. A nearest-rank p95 from three trials is the maximum of those three. + +~~~bash +ai-dev benchmark run --suite examples/benchmarks/repository-small.json --variant baseline --cache-state cold --trials 3 --timeout 120 +ai-dev benchmark run --suite examples/benchmarks/repository-small.json --variant ai-dev --cache-state cold --trials 3 --timeout 120 +ai-dev benchmark compare +ai-dev benchmark gate +~~~ + +`real-agent-repair.json` runs a disposable synthetic repair through a locally configured agent +driver. Set `AI_DEV_BENCHMARK_AGENT_CONFIG` to an absolute JSON file with `baseline` and `ai-dev` +argument arrays for that driver. The process starts in the disposable fixture and receives +`AI_DEV_BENCHMARK_PROMPT` and `AI_DEV_BENCHMARK_VARIANT`. Keep the same prompt, model version, +permissions and instrumentation on both sides. Enable ai-dev only for the candidate. Configure +the requested client and any provider access outside the harness. The separate validator checks +the edited function with held-out pricing and normalization cases. + +Run both variants with `--client --cache-state cold` and pass the resulting reports to +`benchmark gate --require-reported-tokens`. The driver should record per-tool elapsed time and +source reads from local client events in its own sanitized trial log, and emit counts and actual +provider input/output usage through `AI_DEV_BENCHMARK_METRICS`. Derive selection metrics from +fixture ground truth. Keep missing measurements unavailable and record pricing version, cached +input and provider-specific usage separately if calculating cost. The supplied real-agent fixture +resets to a cold local state. A real-agent warm protocol and matched cost study are tracked in #133. diff --git a/docs/MCP_SERVER.md b/docs/MCP_SERVER.md index 8864415..53658fa 100644 --- a/docs/MCP_SERVER.md +++ b/docs/MCP_SERVER.md @@ -95,6 +95,10 @@ than running it as an unsupervised background daemon. ## Compatibility and testing +`tools/call` accepts the optional MCP `params._meta` object. The server validates the shape of +the optional `progressToken` and accepts extension metadata. Tool handlers receive only the +validated `params.arguments`. The server does not send progress notifications. + The source test suite verifies initialization, tool discovery, notifications, parse errors, strict arguments, preview defaults, read-only status behavior, concise structured results, CLI wiring, and installed-wheel initialization. MCP tool names and required input fields should diff --git a/examples/benchmarks/real-agent-repair.json b/examples/benchmarks/real-agent-repair.json new file mode 100644 index 0000000..3e40fec --- /dev/null +++ b/examples/benchmarks/real-agent-repair.json @@ -0,0 +1,28 @@ +{ + "schema_version": "1.0", + "name": "real-agent-repair", + "fixture_version": "1", + "working_directory": ".", + "reset_command": [ + "python", + "scripts/benchmark_real_agent.py", + "reset" + ], + "validation_command": [ + "python", + "scripts/benchmark_real_agent.py", + "validate" + ], + "variants": { + "baseline": [ + "python", + "scripts/benchmark_real_agent.py", + "baseline" + ], + "ai-dev": [ + "python", + "scripts/benchmark_real_agent.py", + "ai-dev" + ] + } +} diff --git a/examples/benchmarks/repository-monorepo.json b/examples/benchmarks/repository-monorepo.json new file mode 100644 index 0000000..87d9975 --- /dev/null +++ b/examples/benchmarks/repository-monorepo.json @@ -0,0 +1,38 @@ +{ + "schema_version": "1.0", + "name": "repository-monorepo", + "fixture_version": "1", + "working_directory": ".", + "reset_command": [ + "python", + "scripts/benchmark_repository.py", + "monorepo", + "reset" + ], + "warmup_command": [ + "python", + "scripts/benchmark_repository.py", + "monorepo", + "warmup" + ], + "validation_command": [ + "python", + "scripts/benchmark_repository.py", + "monorepo", + "validate" + ], + "variants": { + "baseline": [ + "python", + "scripts/benchmark_repository.py", + "monorepo", + "baseline" + ], + "ai-dev": [ + "python", + "scripts/benchmark_repository.py", + "monorepo", + "ai-dev" + ] + } +} diff --git a/examples/benchmarks/repository-small.json b/examples/benchmarks/repository-small.json new file mode 100644 index 0000000..0cb3021 --- /dev/null +++ b/examples/benchmarks/repository-small.json @@ -0,0 +1,38 @@ +{ + "schema_version": "1.0", + "name": "repository-small", + "fixture_version": "1", + "working_directory": ".", + "reset_command": [ + "python", + "scripts/benchmark_repository.py", + "small", + "reset" + ], + "warmup_command": [ + "python", + "scripts/benchmark_repository.py", + "small", + "warmup" + ], + "validation_command": [ + "python", + "scripts/benchmark_repository.py", + "small", + "validate" + ], + "variants": { + "baseline": [ + "python", + "scripts/benchmark_repository.py", + "small", + "baseline" + ], + "ai-dev": [ + "python", + "scripts/benchmark_repository.py", + "small", + "ai-dev" + ] + } +} diff --git a/scripts/benchmark_real_agent.py b/scripts/benchmark_real_agent.py new file mode 100644 index 0000000..107bb31 --- /dev/null +++ b/scripts/benchmark_real_agent.py @@ -0,0 +1,78 @@ +"""Run a user-configured agent driver against a disposable pricing fixture.""" + +from __future__ import annotations + +import argparse +import json +import os +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +FIXTURE = ROOT / ".ai" / "tmp" / "real-agent-repair" +SOURCE = Path("src/pricing.py") +REFERENCE = ROOT / "examples" / "benchmarks" / "fixtures" / "agent-workflow" / SOURCE +MARKER = "ai-dev real agent fixture v1\n" +PROMPT = ( + "Correct calculate_total so it adds the normalized subtotal and tax. " + "Preserve normalization and preserve unrelated behavior. Edit only src/pricing.py." +) +ORACLE = """\ +import runpy +module = runpy.run_path('src/pricing.py') +total = module['calculate_total'] +for subtotal, tax, expected in ((1000, 230, 1230), (-10, 20, 20), (30, -5, 30), (0, 0, 0)): + assert total(subtotal, tax) == expected, (subtotal, tax, expected) +assert module['format_total'](1230) == '12.30' +print('Verified pricing and normalization') +""" + + +def run_trial(variant: str) -> int: + config = Path(os.environ["AI_DEV_BENCHMARK_AGENT_CONFIG"]).read_text(encoding="utf-8") + argv = json.loads(config)[variant] + if not isinstance(argv, list) or not argv or not all(isinstance(arg, str) for arg in argv): + raise ValueError(f"Configure {variant} as a non-empty JSON array of strings") + env = { + **os.environ, + "AI_DEV_BENCHMARK_VARIANT": variant, + "AI_DEV_BENCHMARK_PROMPT": PROMPT, + } + return subprocess.run(argv, cwd=FIXTURE, env=env, check=False).returncode + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("reset", "baseline", "ai-dev", "validate")) + action = parser.parse_args().action + if action == "reset": + if FIXTURE.resolve() != FIXTURE or (FIXTURE.exists() and not FIXTURE.is_dir()): + raise ValueError(f"Unexpected fixture path: {FIXTURE}") + marker = FIXTURE / ".fixture-marker" + if FIXTURE.exists(): + if not marker.is_file() or marker.read_text(encoding="utf-8") != MARKER: + raise ValueError(f"Refusing to replace unrecognized fixture directory: {FIXTURE}") + shutil.rmtree(FIXTURE) + (FIXTURE / SOURCE).parent.mkdir(parents=True, exist_ok=True) + marker.write_text(MARKER, encoding="utf-8") + source = REFERENCE.read_text(encoding="utf-8").replace( + "return subtotal + tax", "return subtotal - tax", 1 + ) + (FIXTURE / SOURCE).write_text(source, encoding="utf-8", newline="\n") + (FIXTURE / "pyproject.toml").write_text( + '[project]\nname = "pricing-fixture"\nversion = "0"\n', encoding="utf-8" + ) + return 0 + if action == "validate": + return subprocess.run( + [sys.executable, "-I", "-S", "-c", ORACLE], + cwd=FIXTURE, + check=False, + ).returncode + return run_trial(action) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/benchmark_repository.py b/scripts/benchmark_repository.py new file mode 100644 index 0000000..6a60b29 --- /dev/null +++ b/scripts/benchmark_repository.py @@ -0,0 +1,244 @@ +"""Exercise CLI and MCP against a generated Git repository with known outputs.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import shutil +import stat +import subprocess +import sys +from collections.abc import Callable +from pathlib import Path +from types import TracebackType +from typing import Any + +ROOT = Path(__file__).resolve().parents[1] +SCRATCH = ROOT / ".ai" / "tmp" / "repository-benchmark-v1" +SOURCE = "packages/service/pricing.py" +TEST = "tests/test_pricing.py" +SIZES = {"small": (1, 4), "monorepo": (40, 25)} +MARKER = "ai-dev repository benchmark fixture v1\n" + + +def write(path: Path, value: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(value, encoding="utf-8", newline="\n") + + +def read_json(path: Path) -> dict[str, Any]: + value: dict[str, Any] = json.loads(path.read_text(encoding="utf-8")) + return value + + +def run(root: Path, command: list[str], request: str | None = None) -> str: + return subprocess.run( + command, + cwd=root, + input=request, + capture_output=True, + check=True, + encoding="utf-8", + errors="replace", + timeout=90, + ).stdout + + +def git(root: Path, *args: str) -> None: + run(root, ["git", *args]) + + +def cli(root: Path, *args: str, request: str | None = None) -> str: + return run(root, [sys.executable, "-m", "ai_dev_tools", "--json", *args], request) + + +def remove_git_fixture(root: Path) -> None: + def retry_readonly( + operation: Callable[..., object], + path: str, + error: tuple[type[BaseException], BaseException, TracebackType | None], + ) -> None: + target = Path(path) + if ( + os.name != "nt" + or operation is not os.unlink + or not isinstance(error[1], PermissionError) + or root not in target.resolve().parents + ): + raise error[1] + target.chmod(stat.S_IWRITE) + target.unlink() + + shutil.rmtree(root, onerror=retry_readonly) + + +def reset(root: Path, size: str) -> None: + marker = SCRATCH / f"{size}.marker" + if root.resolve() != root: + raise ValueError(f"Unexpected fixture path: {root}") + if root.exists(): + if not marker.is_file(): + raise ValueError(f"Refusing to replace unrecognized fixture directory: {root}") + if marker.read_text(encoding="utf-8") != MARKER: + raise ValueError(f"Unrecognized fixture marker: {marker}") + remove_git_fixture(root) + write(marker, MARKER) + write(root / ".gitignore", ".ai/\n__pycache__/\n.pytest_cache/\n") + write(root / "pyproject.toml", '[project]\nname = "repo-benchmark"\nversion = "0.0.0"\n') + write(root / SOURCE, "def calculate_total():\n return 1\n") + write(root / TEST, "def test_pricing():\n assert True\n") + write(root / "tests/test_unrelated.py", "def test_unrelated():\n assert True\n") + workspaces, modules = SIZES[size] + for workspace in range(workspaces): + path = root / "workspaces" / f"service_{workspace:02d}" + write(path / "pyproject.toml", f'[project]\nname = "service-{workspace}"\nversion = "0"\n') + for module in range(modules): + write(path / f"module_{module:02d}.py", f"def operation_{module}():\n return 0\n") + git(root, "init", "-b", "main", "--template=") + git(root, "add", ".") + git( + root, + "-c", + "user.name=Benchmark", + "-c", + "user.email=benchmark@example.invalid", + "-c", + "commit.gpgSign=false", + "commit", + "-m", + "Fixture", + ) + + +def measure(root: Path, mode: str) -> None: + index_mode = "rebuild" if mode == "baseline" else "update" + semantic_flags = ("--rebuild",) if mode == "baseline" else () + reports: dict[str, Any] = { + "mode": mode, + "primed": (root / ".ai" / "cache" / "semantic-index.json").is_file(), + "version": cli(root, "--version").strip(), + "scan": json.loads(cli(root, "scan")), + "initial_index": json.loads(cli(root, "index", index_mode)), + "repeat_index": json.loads(cli(root, "index", index_mode)), + "initial_semantic": json.loads(cli(root, "semantic", "index", "--backend", "structural")), + } + write(root / SOURCE, "def calculate_adjusted_total():\n return 123\n") + reports.update( + git=json.loads(cli(root, "git", "inspect")), + changed_index=json.loads(cli(root, "index", index_mode)), + changed_semantic=json.loads( + cli(root, "semantic", "index", "--backend", "structural", *semantic_flags) + ), + symbol=json.loads(cli(root, "explain", "--symbol", f"{SOURCE}#calculate_adjusted_total")), + context=json.loads( + cli( + root, + "context", + "build", + "--profile", + "implement", + "--max-files", + "8", + "--task", + "Review calculate_adjusted_total in packages/service/pricing.py", + ) + ), + selection=json.loads(cli(root, "check", "--mode", "changed", "--explain")), + ) + messages = [ + {"id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18"}}, + { + "id": 2, + "method": "tools/call", + "params": { + "name": "project_status", + "_meta": {"progressToken": "fixture"}, + }, + }, + ] + requests = "".join(json.dumps({"jsonrpc": "2.0", **message}) + "\n" for message in messages) + reports["mcp"] = [ + json.loads(line) + for line in cli( + root, + "mcp", + "serve", + request=requests, + ).splitlines() + ] + write(root / ".ai" / "benchmark-evidence.json", json.dumps(reports)) + print("Collected repository workflow evidence") + selected = _selected_tests(reports) + metrics = { + "commands": 12, + "selected_items": len(selected), + "relevant_items": 1, + "true_positive_items": int(TEST in selected), + } + print(f"AI_DEV_BENCHMARK_METRICS={json.dumps(metrics)}", file=sys.stderr) + + +def _selected_tests(reports: dict[str, Any]) -> set[str]: + return { + path.replace("\\", "/") + for path in reports["selection"]["summary"]["changed_analysis"]["selected_tests"] + } + + +def validate(root: Path, size: str) -> None: + reports = read_json(root / ".ai" / "benchmark-evidence.json") + expected_hash = hashlib.sha256(b"def calculate_adjusted_total():\n return 123\n").hexdigest() + index = read_json(root / ".ai" / "cache" / "repository-index.json") + semantic = read_json(root / ".ai" / "cache" / "semantic-index.json") + hashes = {row["path"]: row["sha256"] for row in index["entries"]} + symbols = {row["name"] for row in semantic["symbols"] if row["path"] == SOURCE} + workspaces, modules = SIZES[size] + expected_modules = { + f"workspaces/service_{workspace:02d}/module_{module:02d}.py" + for workspace in range(workspaces) + for module in range(modules) + } + assert reports["version"].startswith("ai-dev ") + assert "python" in reports["scan"]["summary"]["languages"] + assert expected_modules <= hashes.keys() + assert hashes[SOURCE] == expected_hash + assert symbols == {"calculate_adjusted_total"} + symbol = reports["symbol"]["summary"] + assert (symbol["path"], symbol["symbol"], symbol["start_line"]) == ( + SOURCE, + "calculate_adjusted_total", + 1, + ) + assert reports["git"]["summary"]["changed_files"] == [SOURCE] + assert SOURCE in {row["path"] for row in reports["context"]["summary"]["selected_files"]} + assert _selected_tests(reports) == {TEST} + if reports["mode"] == "ai-dev": + assert (reports["initial_index"]["summary"]["hashed"] == 0) == reports["primed"] + assert reports["repeat_index"]["summary"]["hashed"] == 0 + assert reports["changed_index"]["summary"]["hashed"] == 1 + assert reports["mcp"][0]["result"]["protocolVersion"] == "2025-06-18" + assert reports["mcp"][1]["result"]["isError"] is False + print(f"Verified {size} fixture and expected edited symbol") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("size", choices=SIZES) + parser.add_argument("action", choices=("reset", "warmup", "baseline", "ai-dev", "validate")) + args = parser.parse_args() + root = SCRATCH / args.size + if args.action == "reset": + reset(root, args.size) + elif args.action == "warmup": + cli(root, "index", "update") + cli(root, "semantic", "index", "--backend", "structural") + elif args.action == "validate": + validate(root, args.size) + else: + measure(root, args.action) + + +if __name__ == "__main__": + main() diff --git a/scripts/test_installed_package.py b/scripts/test_installed_package.py index a93565f..02106eb 100644 --- a/scripts/test_installed_package.py +++ b/scripts/test_installed_package.py @@ -113,14 +113,25 @@ def _smoke_entrypoint(entrypoint: Path, cwd: Path) -> None: "params": {"protocolVersion": "2025-06-18"}, } ) + project_status = json.dumps( + { + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": {"name": "project_status", "_meta": {"progressToken": "wheel-smoke"}}, + } + ) mcp_result = _run( [str(entrypoint), "--project", str(cwd), "mcp", "serve"], cwd, - input_text=initialize + "\n", + input_text=f"{initialize}\n{project_status}\n", ) - mcp_response = json.loads(mcp_result.stdout) - if mcp_response.get("result", {}).get("serverInfo", {}).get("name") != "ai-dev-cli-tools": + initialized, status_response = (json.loads(line) for line in mcp_result.stdout.splitlines()) + if initialized.get("result", {}).get("serverInfo", {}).get("name") != "ai-dev-cli-tools": raise SmokeError("installed MCP entrypoint did not initialize") + status = status_response.get("result", {}) + if status.get("isError") is not False or "structuredContent" not in status: + raise SmokeError("installed MCP entrypoint did not accept tools/call request metadata") _smoke_check_duration(entrypoint, cwd) diff --git a/scripts/validate_ci.py b/scripts/validate_ci.py index f0db995..9b574ef 100644 --- a/scripts/validate_ci.py +++ b/scripts/validate_ci.py @@ -41,7 +41,7 @@ ] REQUIRED_STEPS = [ "ruff check .", - "mypy src tests", + "mypy src tests scripts", "coverage run -m pytest", "coverage report --fail-under=90", "python -m build", diff --git a/src/ai_dev_tools/mcp_server.py b/src/ai_dev_tools/mcp_server.py index f1ddfcc..a8c0e16 100644 --- a/src/ai_dev_tools/mcp_server.py +++ b/src/ai_dev_tools/mcp_server.py @@ -107,7 +107,14 @@ def _dispatch(self, method: str, params: JsonObject) -> JsonObject | None: return None def _call_tool(self, params: JsonObject) -> JsonObject: - _validate_keys(params, {"name", "arguments"}) + _validate_keys(params, {"name", "arguments", "_meta"}) + metadata = params.get("_meta", {}) + if not isinstance(metadata, dict): + raise ToolInputError("Request metadata must be an object.") + if "progressToken" in metadata: + token = metadata["progressToken"] + if isinstance(token, bool) or not isinstance(token, (str, int, float)): + raise ToolInputError("Progress token must be a string or number.") name = params.get("name") if not isinstance(name, str) or name not in self._tools: raise ToolInputError("Unknown MCP tool.") diff --git a/src/ai_dev_tools/parsers/logs.py b/src/ai_dev_tools/parsers/logs.py index ee90ec1..bb904cf 100644 --- a/src/ai_dev_tools/parsers/logs.py +++ b/src/ai_dev_tools/parsers/logs.py @@ -42,6 +42,9 @@ r"[ \t]+(?P\d+)[ \t]*$", re.MULTILINE, ) +NODE_NON_FAILURE_PATTERN = re.compile(r"^(?:[✔﹣]\s|ok\s+\d+\b|# Subtest:)") +NODE_LOSSY_SPEC_PATTERN = re.compile(r"^\?\s.+ \(\d+(?:\.\d+)?ms\)$") +NODE_FAIL_PATTERN = re.compile(r"^(?:✖\s|not ok\s+\d+\b)") TEST_KINDS = { "passed": "passed", @@ -186,10 +189,10 @@ def parse(self, command: CommandResult) -> ParsedToolResult: BUILTIN_PARSERS: tuple[ToolOutputParser, ...] = ( + NodeTestParser(), RegexToolParser("ruff", ("ruff", "would reformat"), "high"), RegexToolParser("mypy", ("mypy", "success: no issues found", "checked 1 source file"), "high"), RegexToolParser("pytest", ("pytest", "failed tests/", "= short test summary info ="), "high"), - NodeTestParser(), RegexToolParser("coverage", ("coverage", "fail_under"), "medium"), RegexToolParser("jest", ("jest", "test suites:", "fail src/"), "high"), RegexToolParser("vitest", ("vitest", "test files", "duration"), "high"), @@ -340,7 +343,7 @@ def _parsed_from_output( tool: str, parser: str, confidence: str, command: CommandResult ) -> ParsedToolResult: cleaned = clean_output(command.combined_output) - summary = _summary_parts(cleaned) + summary = _summary_parts(cleaned, node_test=parser == "node-test") failed = _as_int(summary.get("failed")) + _as_int(summary.get("errors")) status = "failed" if command.exit_code != 0 or failed else "success" first_failure = _first_failure(tool, cleaned, summary) @@ -365,18 +368,21 @@ def _parsed_from_output( ) -def _summary_parts(output: str) -> dict[str, object]: +def _summary_parts(output: str, *, node_test: bool = False) -> dict[str, object]: lines = [line.strip() for line in clean_output(output).splitlines() if line.strip()] grouped = Counter(lines) - errors = [ - line - for line in lines - if any( - marker in ZERO_ERROR_SUMMARY_PATTERN.sub("", line).lower() for marker in ERROR_MARKERS - ) - ] - frames = _project_frames("\n".join(lines)) test_counts = parse_test_counts(output) + diagnostics = lines + if node_test: + diagnostics = [ + line + for line in lines + if not NODE_NON_FAILURE_PATTERN.match(line) + # A lossy console can render both success and failure glyphs as '?'. + and not (test_counts["failed"] == 0 and NODE_LOSSY_SPEC_PATTERN.match(line)) + ] + errors = [line for line in diagnostics if _is_error_line(line, node_test=node_test)] + frames = _project_frames("\n".join(lines)) tests_total = sum(test_counts.values()) js = JEST_VITEST_PATTERN.search(output) if js and js.group("total"): @@ -398,8 +404,15 @@ def _summary_parts(output: str) -> dict[str, object]: } +def _is_error_line(line: str, *, node_test: bool) -> bool: + if node_test and NODE_FAIL_PATTERN.match(line): + return True + text = ZERO_ERROR_SUMMARY_PATTERN.sub("", line).lower() + return any(marker in text for marker in ERROR_MARKERS) + + def _first_failure(tool: str, output: str, summary: dict[str, object]) -> FailureDetails | None: - match = PYTEST_FAILURE_PATTERN.search(output) + match = None if tool == "node-test" else PYTEST_FAILURE_PATTERN.search(output) if match: message = match.group("message") or _string_or_none(summary.get("first_failure_reason")) return FailureDetails( diff --git a/src/ai_dev_tools/runners/benchmark.py b/src/ai_dev_tools/runners/benchmark.py index 4fcb5cf..a5fdeb3 100644 --- a/src/ai_dev_tools/runners/benchmark.py +++ b/src/ai_dev_tools/runners/benchmark.py @@ -61,11 +61,17 @@ def run_benchmark( rows: list[dict[str, Any]] = [] working = Path(spec["working_directory"]) + warmup_command = spec["warmup_command"] if cache_state == "warm" else None for number in range(1, trials + 1): reset = run_command(spec["reset_command"], working, timeout_seconds) + warmup = ( + run_command(warmup_command, working, timeout_seconds) + if warmup_command is not None and reset.exit_code == 0 + else None + ) execution = ( run_command(variants[variant], working, timeout_seconds) - if reset.exit_code == 0 + if reset.exit_code == 0 and (warmup is None or warmup.exit_code == 0) else _skipped(variants[variant]) ) validation = ( @@ -73,7 +79,12 @@ def run_benchmark( if reset.exit_code == 0 and execution.exit_code == 0 else _skipped(spec["validation_command"]) ) - rows.append(_trial_row(number, reset, execution, validation)) + row = _trial_row(number, reset, execution, validation) + if warmup is not None: + row["exit_codes"]["warmup"] = warmup.exit_code + row["warmup_seconds"] = round(warmup.duration_seconds, 3) + row["timed_out"] |= warmup.timed_out + rows.append(row) correct = sum(bool(row["correct"]) for row in rows) report.status = "success" if correct == len(rows) else "failed" @@ -85,6 +96,7 @@ def run_benchmark( "variant": variant, "client": client, "cache_state": cache_state, + "cache_preparation": "reset_and_warmup" if warmup_command is not None else "reset_only", "trials": rows, "statistics": _statistics(rows), "correct_trials": correct, @@ -223,6 +235,7 @@ def gate_benchmarks( report.issues.extend(comparison.issues) return report try: + baseline_summary = _load_run(project_root, baseline)["summary"] candidate_run = _load_run(project_root, candidate) stats = candidate_run["summary"]["statistics"] except (OSError, ValueError, json.JSONDecodeError, KeyError) as exc: @@ -245,12 +258,22 @@ def gate_benchmarks( _stat_value(stats, "total_false_negative_items") <= max_false_negatives ), "reported_tokens": ( - _stat_value(stats, "reported_token_trials") == len(candidate_run["summary"]["trials"]) + _stat_value(baseline_summary["statistics"], "reported_token_trials") + == len(baseline_summary["trials"]) + and _stat_value(stats, "reported_token_trials") + == len(candidate_run["summary"]["trials"]) if require_reported_tokens else True ), "reported_token_regression": ( - _percent_within(metrics["median_reported_input_tokens"], max_token_regression) + all( + _percent_within(metrics[f"median_reported_{kind}_tokens"], max_token_regression) + and ( + metrics[f"median_reported_{kind}_tokens"]["baseline"] > 0 + or metrics[f"median_reported_{kind}_tokens"]["candidate"] == 0 + ) + for kind in ("input", "output") + ) if require_reported_tokens else True ), @@ -388,6 +411,9 @@ def _load_spec(project_root: Path, path: Path) -> dict[str, Any]: "working_directory": working, "variants": variants, "reset_command": _command(data.get("reset_command"), "reset_command"), + "warmup_command": ( + _command(data["warmup_command"], "warmup_command") if "warmup_command" in data else None + ), "validation_command": _command(data.get("validation_command"), "validation_command"), } @@ -429,6 +455,7 @@ def _trial_row( reset.duration_seconds + execution.duration_seconds + validation.duration_seconds, 3, ), + "execution_seconds": round(execution.duration_seconds, 3), "time_to_actionable_result_seconds": round(reset.duration_seconds + float(actionable), 3), "commands": int(commands), "validation_subprocesses": int(validation_subprocesses), @@ -519,8 +546,12 @@ def values(key: str) -> list[float]: return [float(row[key]) for row in rows] durations = values("duration_seconds") + execution = values("execution_seconds") return { "median_seconds": round(statistics.median(durations), 3), + "p95_seconds": _p95(durations), + "median_execution_seconds": round(statistics.median(execution), 3), + "p95_execution_seconds": _p95(execution), "duration_stdev_seconds": ( round(statistics.stdev(durations), 3) if len(durations) > 1 else 0.0 ), @@ -546,14 +577,17 @@ def values(key: str) -> list[float]: sum( 1 for row in rows - if int(row["reported_input_tokens"]) > 0 - or int(row["reported_output_tokens"]) > 0 + if int(row["reported_input_tokens"]) > 0 or int(row["reported_output_tokens"]) > 0 ), 3, ), } +def _p95(values: list[float]) -> float: + return round(sorted(values)[math.ceil(0.95 * len(values)) - 1], 3) + + def _stat_value(stats: dict[str, Any], key: str) -> float: value = stats.get(key, 0.0) return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else 0.0 @@ -615,6 +649,10 @@ def _validate_comparable(left: dict[str, Any], right: dict[str, Any]) -> None: raise ValueError("Benchmark variants must differ") if left["summary"].get("client", "generic") != right["summary"].get("client", "generic"): raise ValueError("Benchmark client differs") + if left["summary"].get("cache_preparation", "reset_only") != right["summary"].get( + "cache_preparation", "reset_only" + ): + raise ValueError("Benchmark cache preparation differs") def _outcomes(summary: dict[str, Any]) -> list[str]: diff --git a/tests/unit/test_benchmark.py b/tests/unit/test_benchmark.py index fdb7bde..257ddc9 100644 --- a/tests/unit/test_benchmark.py +++ b/tests/unit/test_benchmark.py @@ -46,8 +46,9 @@ def test_benchmark_runs_and_compares_equivalent_variants(tmp_path: Path) -> None assert baseline.status == "success" assert baseline.summary["correct_trials"] == 2 - assert baseline.summary["statistics"]["median_agent_visible_bytes"] > ( - candidate.summary["statistics"]["median_agent_visible_bytes"] + assert ( + baseline.summary["statistics"]["median_agent_visible_bytes"] + > (candidate.summary["statistics"]["median_agent_visible_bytes"]) ) baseline_path = Path(next(item.path for item in baseline.artifacts if item.kind == "json")) candidate_path = Path(next(item.path for item in candidate.artifacts if item.kind == "json")) @@ -67,9 +68,7 @@ def test_benchmark_labels_client_and_can_require_provider_reported_tokens(tmp_pa baseline_path = Path(next(item.path for item in baseline.artifacts if item.kind == "json")) candidate_path = Path(next(item.path for item in candidate.artifacts if item.kind == "json")) - gated = gate_benchmarks( - tmp_path, baseline_path, candidate_path, require_reported_tokens=True - ) + gated = gate_benchmarks(tmp_path, baseline_path, candidate_path, require_reported_tokens=True) assert candidate.summary["client"] == "codex" assert candidate.summary["statistics"]["reported_token_trials"] == 0 @@ -131,6 +130,50 @@ def test_compare_requires_different_variants_and_matching_cache_state(tmp_path: assert compared.summary["reason_code"] == "INCOMPARABLE_BENCHMARK_RUNS" +def test_benchmark_primes_warm_trials_after_each_reset(tmp_path: Path) -> None: + suite = _suite(tmp_path) + spec = json.loads(suite.read_text(encoding="utf-8")) + spec["reset_command"] = [ + sys.executable, + "-c", + "from pathlib import Path; Path('cache').unlink(missing_ok=True)", + ] + spec["warmup_command"] = [ + sys.executable, + "-c", + "from pathlib import Path; Path('cache').touch(exist_ok=False)", + ] + spec["variants"]["ai-dev"] = [ + sys.executable, + "-c", + "from pathlib import Path; print(Path('cache').is_file())", + ] + spec["validation_command"] = [sys.executable, "-c", "print('verified')"] + suite.write_text(json.dumps(spec), encoding="utf-8") + + cold = run_benchmark(tmp_path, suite, "ai-dev", trials=2, cache_state="cold") + warm = run_benchmark(tmp_path, suite, "ai-dev", trials=2, cache_state="warm") + + assert cold.status == warm.status == "success" + assert cold.summary["trials"][0]["agent_visible_bytes"] == len(b"False\nverified") + for row in warm.summary["trials"]: + assert row["agent_visible_bytes"] == len(b"True\nverified") + assert row["exit_codes"]["warmup"] == 0 + assert warm.summary["statistics"]["p95_seconds"] >= warm.summary["statistics"]["median_seconds"] + + +def test_benchmark_does_not_measure_after_failed_warmup(tmp_path: Path) -> None: + suite = _suite(tmp_path) + spec = json.loads(suite.read_text(encoding="utf-8")) + spec["warmup_command"] = [sys.executable, "-c", "raise SystemExit(7)"] + suite.write_text(json.dumps(spec), encoding="utf-8") + + report = run_benchmark(tmp_path, suite, "ai-dev", trials=1, cache_state="warm") + + assert report.status == "failed" + assert report.summary["trials"][0]["exit_codes"]["warmup"] == 7 + + def test_trial_uses_private_execution_metrics_without_counting_them_as_visible_output() -> None: reset = CommandResult(["reset"], 0, "", "", 0.1, False) execution = CommandResult( @@ -169,6 +212,7 @@ def test_invalid_execution_metrics_remain_visible_and_do_not_override_defaults() assert f"{METRICS_PREFIX}[1, 2]" in visible assert "warning" in visible + def test_versioned_agent_workflow_manifests_share_the_final_fixture() -> None: root = Path(__file__).resolve().parents[2] scenarios = ("repair", "affected", "multiturn", "monorepo") diff --git a/tests/unit/test_benchmark_gate.py b/tests/unit/test_benchmark_gate.py index c8a5fa2..1ff7ce5 100644 --- a/tests/unit/test_benchmark_gate.py +++ b/tests/unit/test_benchmark_gate.py @@ -57,16 +57,12 @@ def test_benchmark_gate_enforces_efficiency_and_quality_thresholds(tmp_path: Pat assert failed.summary["rollback_advised"] is True _run(candidate, "ai-dev", seconds=11, tokens=90) - reduced = gate_benchmarks( - tmp_path, baseline, candidate, min_token_reduction=15 - ) + reduced = gate_benchmarks(tmp_path, baseline, candidate, min_token_reduction=15) assert reduced.status == "failed" assert reduced.summary["checks"]["token_reduction"] is False _run(candidate, "ai-dev", seconds=11, tokens=80) - reduced = gate_benchmarks( - tmp_path, baseline, candidate, min_token_reduction=15 - ) + reduced = gate_benchmarks(tmp_path, baseline, candidate, min_token_reduction=15) assert reduced.status == "success" @@ -78,15 +74,43 @@ def test_gate_advises_adoption_only_for_faster_lower_token_candidate( _run(baseline, "baseline", seconds=10, tokens=100) _run(candidate, "ai-dev", seconds=8, tokens=75) - report = gate_benchmarks( - tmp_path, baseline, candidate, min_token_reduction=20 - ) + report = gate_benchmarks(tmp_path, baseline, candidate, min_token_reduction=20) assert report.status == "success" assert report.summary["decision"] == "adopt_candidate" assert report.summary["requires_human_approval"] is True +def test_gate_requires_usage_on_both_sides_and_checks_output_tokens(tmp_path: Path) -> None: + baseline, candidate = (tmp_path / name for name in ("baseline.json", "candidate.json")) + _run(baseline, "baseline", seconds=10, tokens=100) + _run(candidate, "ai-dev", seconds=10, tokens=100) + + def add_usage(path: Path, output_tokens: int) -> None: + data = json.loads(path.read_text(encoding="utf-8")) + data["summary"]["statistics"].update( + reported_token_trials=1, + median_reported_input_tokens=80, + median_reported_output_tokens=output_tokens, + ) + path.write_text(json.dumps(data), encoding="utf-8") + + add_usage(candidate, 80) + missing = gate_benchmarks(tmp_path, baseline, candidate, require_reported_tokens=True) + assert missing.status == "failed" + assert missing.summary["checks"]["reported_tokens"] is False + + add_usage(baseline, 40) + larger = gate_benchmarks(tmp_path, baseline, candidate, require_reported_tokens=True) + assert larger.status == "failed" + assert larger.summary["checks"]["reported_token_regression"] is False + + add_usage(candidate, 40) + assert gate_benchmarks(tmp_path, baseline, candidate, require_reported_tokens=True).status == ( + "success" + ) + + def test_corpus_runs_every_suite_and_aggregates_gates(monkeypatch, tmp_path: Path) -> None: # type: ignore[no-untyped-def] manifest = tmp_path / "corpus.json" manifest.write_text( diff --git a/tests/unit/test_issue_regressions.py b/tests/unit/test_issue_regressions.py index 384a7bc..c575a55 100644 --- a/tests/unit/test_issue_regressions.py +++ b/tests/unit/test_issue_regressions.py @@ -48,6 +48,61 @@ def test_numeric_error_counts_survive_summary() -> None: assert parsed["status"] == "failed" +@pytest.mark.parametrize( + "passing_line", + [ + "✔ storage failure rolls back (1ms)", + "? storage failure rolls back (1ms)", + " ✔ ignores FAILED tests/x.py - example (1ms)", + ], +) +def test_node_passing_case_is_not_failure_evidence(passing_line: str) -> None: + output = f"{passing_line}\nℹ tests 1\nℹ pass 1\nℹ fail 0\nℹ skipped 0\n" + parsed = parse_tool_output("npm test", output, 0) + + assert parsed["parser"] == "node-test" + assert parsed["status"] == "success" + assert parsed["passed"] == 1 + assert parsed["failed"] == 0 + assert parsed["line_count"] == 5 + assert parsed["first_failure"] is None + assert parsed["first_failure_reason"] is None + + +def test_node_tap_subtest_descriptions_are_not_failure_evidence() -> None: + output = ( + "TAP version 13\n# Subtest: storage failure rolls back\n" + "ok 1 - storage failure rolls back\n1..1\n# tests 1\n# pass 1\n# fail 0\n" + ) + parsed = parse_tool_output("node --test", output) + + assert parsed["status"] == "success" + assert parsed["first_failure"] is None + assert parsed["first_failure_reason"] is None + + +@pytest.mark.parametrize( + ("failure_line", "exit_code", "failures"), + [ + ("✖ writes a record (1ms)", 1, 1), + ("not ok 2 - writes a record", 1, 1), + ("Error: process terminated", 2, 0), + ], +) +def test_node_reports_real_failures_after_passing_case( + failure_line: str, exit_code: int, failures: int +) -> None: + output = ( + f"✔ handles storage failure (1ms)\n{failure_line}\n" + f"ℹ tests {1 + failures}\nℹ pass 1\nℹ fail {failures}\nℹ skipped 0\n" + ) + parsed = parse_tool_output("npm test", output, exit_code) + + assert parsed["status"] == "failed" + assert parsed["failed"] == failures + assert parsed["first_failure_reason"] == failure_line + + @pytest.mark.parametrize("extension", ["mjs", "cjs", "js", "unknown"]) def test_selected_tests_keep_broad_command(extension: str) -> None: plan = [CheckTask("npm test", "unit_tests", ["npm", "test"], "medium", "detected")] diff --git a/tests/unit/test_mcp_server.py b/tests/unit/test_mcp_server.py index bd2af6f..08ca2c4 100644 --- a/tests/unit/test_mcp_server.py +++ b/tests/unit/test_mcp_server.py @@ -5,6 +5,8 @@ from pathlib import Path from typing import Any +import pytest + from ai_dev_tools.mcp_server import ( MCP_PROTOCOL_VERSION, SERVER_INSTRUCTIONS, @@ -93,6 +95,15 @@ def test_stdio_transport_returns_json_lines_and_ignores_notifications(tmp_path: "params": {}, }, _request("ping", request_id=2), + _request( + "tools/call", + { + "name": "project_status", + "arguments": {}, + "_meta": {"progressToken": "request-3", "example.com/client": {"trace": 1}}, + }, + request_id=3, + ), ] reader = io.StringIO("\n".join(json.dumps(item) for item in messages) + "\n") writer = io.StringIO() @@ -100,8 +111,41 @@ def test_stdio_transport_returns_json_lines_and_ignores_notifications(tmp_path: assert serve_mcp(tmp_path, reader, writer) == 0 responses = [json.loads(line) for line in writer.getvalue().splitlines()] - assert [item["id"] for item in responses] == [1, 2] + assert [item["id"] for item in responses] == [1, 2, 3] assert responses[1]["result"] == {} + assert responses[2]["result"]["isError"] is False + assert responses[2]["result"]["structuredContent"]["command"] == "project status" + + +@pytest.mark.parametrize("metadata", [{}, {"progressToken": 0}]) +def test_tools_call_accepts_request_metadata(tmp_path: Path, metadata: object) -> None: + response = LocalMcpServer(tmp_path).handle( + _request("tools/call", {"name": "project_status", "_meta": metadata}) + ) + assert response is not None + assert response["result"]["isError"] is False + + +@pytest.mark.parametrize( + ("params", "error"), + [ + ({"_meta": None}, "Request metadata must be an object."), + ({"_meta": []}, "Request metadata must be an object."), + ({"_meta": {"progressToken": True}}, "Progress token must be a string or number."), + ({"_meta": {"progressToken": None}}, "Progress token must be a string or number."), + ({"_meta": {}, "unexpected": True}, "Unknown tool arguments: unexpected"), + ({"_meta": {}, "arguments": {"unexpected": True}}, "Unknown tool arguments: unexpected"), + ({"_meta": {}, "arguments": {"_meta": {}}}, "Unknown tool arguments: _meta"), + ], +) +def test_tools_call_rejects_invalid_metadata_and_arguments( + tmp_path: Path, params: dict[str, object], error: str +) -> None: + response = LocalMcpServer(tmp_path).handle( + _request("tools/call", {"name": "project_status", **params}) + ) + assert response is not None + assert response["error"] == {"code": -32602, "message": error} def test_stdio_transport_reports_parse_and_method_errors(tmp_path: Path) -> None: From e688ed293dd19ec26df17590b240422d5c764fea Mon Sep 17 00:00:00 2001 From: Mateusz Lewandowski Date: Mon, 23 Nov 2026 19:09:57 +0100 Subject: [PATCH 2/3] Check scripted corpus outcomes against independent fixture oracles --- docs/BENCHMARKS.md | 2 + .../benchmarks/agent-adaptive-context.json | 2 +- .../agent-context-acknowledgement.json | 6 +- examples/benchmarks/agent-feedback-delta.json | 2 +- scripts/benchmark_agent_workflow.py | 55 ++++++++++-- scripts/benchmark_mcp_context_ack.py | 86 +++++++++++++------ tests/unit/test_benchmark.py | 43 ++++++++++ 7 files changed, 158 insertions(+), 38 deletions(-) diff --git a/docs/BENCHMARKS.md b/docs/BENCHMARKS.md index 03f481b..b37c11d 100644 --- a/docs/BENCHMARKS.md +++ b/docs/BENCHMARKS.md @@ -42,6 +42,8 @@ ai-dev benchmark gate --require-reported-tokens The corpus includes a repeated MCP `build_context` task that compares a forced full refresh with an explicitly acknowledged unchanged receipt. Both variants must retain the same outcome, precision, and recall while the receipt satisfies the configured token-reduction threshold. +The context acknowledgement, adaptive selection and feedback delta suites store their trial +evidence for a separate validator. Their fixture version is 2 to reflect the stricter oracles. Cold and warm results are compared within the same cache state. Give a suite an optional `warmup_command` array to prime the cache after each reset and before each measured warm trial. diff --git a/examples/benchmarks/agent-adaptive-context.json b/examples/benchmarks/agent-adaptive-context.json index 331f089..6c65bd5 100644 --- a/examples/benchmarks/agent-adaptive-context.json +++ b/examples/benchmarks/agent-adaptive-context.json @@ -1,7 +1,7 @@ { "schema_version": "1.0", "name": "agent-adaptive-context", - "fixture_version": "1", + "fixture_version": "2", "working_directory": "examples/benchmarks/fixtures/agent-workflow", "reset_command": [ "python", diff --git a/examples/benchmarks/agent-context-acknowledgement.json b/examples/benchmarks/agent-context-acknowledgement.json index 264fc4a..91d06a3 100644 --- a/examples/benchmarks/agent-context-acknowledgement.json +++ b/examples/benchmarks/agent-context-acknowledgement.json @@ -1,10 +1,10 @@ { "schema_version": "1.0", "name": "agent-context-acknowledgement", - "fixture_version": "1", + "fixture_version": "2", "working_directory": ".", - "reset_command": ["python", "-c", "pass"], - "validation_command": ["python", "-c", "print('unchanged-context-confirmed')"], + "reset_command": ["python", "scripts/benchmark_mcp_context_ack.py", "reset"], + "validation_command": ["python", "scripts/benchmark_mcp_context_ack.py", "validate"], "variants": { "baseline": ["python", "scripts/benchmark_mcp_context_ack.py", "baseline"], "ai-dev": ["python", "scripts/benchmark_mcp_context_ack.py", "ai-dev"] diff --git a/examples/benchmarks/agent-feedback-delta.json b/examples/benchmarks/agent-feedback-delta.json index d97c8cc..4aaab01 100644 --- a/examples/benchmarks/agent-feedback-delta.json +++ b/examples/benchmarks/agent-feedback-delta.json @@ -1,7 +1,7 @@ { "schema_version": "1.0", "name": "agent-feedback-delta", - "fixture_version": "1", + "fixture_version": "2", "working_directory": "examples/benchmarks/fixtures/agent-workflow", "reset_command": [ "python", diff --git a/scripts/benchmark_agent_workflow.py b/scripts/benchmark_agent_workflow.py index 1ebde54..88495ea 100644 --- a/scripts/benchmark_agent_workflow.py +++ b/scripts/benchmark_agent_workflow.py @@ -15,6 +15,7 @@ ROOT = Path(__file__).resolve().parents[1] FIXTURE = ROOT / "examples" / "benchmarks" / "fixtures" / "agent-workflow" ADAPTIVE_FIXTURE = FIXTURE / ".ai" / "adaptive-context" +TRIAL_EVIDENCE = FIXTURE / ".ai" / "benchmark-evidence.json" PRICING = FIXTURE / "src" / "pricing.py" FIXED = "return subtotal + tax" BROKEN = "return subtotal - tax" @@ -246,6 +247,7 @@ def _adaptive(variant: str, started: float) -> int: visible = json.dumps(report.summary, separators=(",", ":")) selected = _selected_paths(report.summary) actionable = time.monotonic() - started + _write_evidence("adaptive", variant, report.summary) print(visible) _metrics( commands=3, @@ -268,6 +270,7 @@ def _feedback_delta(variant: str, started: float) -> int: ) visible = json.dumps(summary, separators=(",", ":")) actionable = time.monotonic() - started + _write_evidence("feedback-delta", variant, summary) print(visible) _metrics( commands=1, @@ -280,14 +283,7 @@ def _feedback_delta(variant: str, started: float) -> int: def _validate(scenario: str) -> int: if scenario in {"adaptive", "feedback-delta"}: - if scenario == "feedback-delta": - print("verified:feedback-delta:semantic-state-preserved") - return 0 - if not ADAPTIVE_FIXTURE.is_dir(): - print("adaptive context fixture was not created", file=sys.stderr) - return 1 - print("verified:adaptive:complete-selection") - return 0 + return _validate_evidence(scenario) if scenario == "repair" and BROKEN in PRICING.read_text(encoding="utf-8"): print("repair was not applied", file=sys.stderr) return 1 @@ -300,6 +296,49 @@ def _validate(scenario: str) -> int: return 0 +def _write_evidence(scenario: str, variant: str, summary: dict[str, object]) -> None: + TRIAL_EVIDENCE.parent.mkdir(parents=True, exist_ok=True) + TRIAL_EVIDENCE.write_text( + json.dumps({"scenario": scenario, "variant": variant, "summary": summary}), encoding="utf-8" + ) + + +def _validate_evidence(scenario: str) -> int: + if not TRIAL_EVIDENCE.is_file(): + print(f"Missing benchmark evidence for {scenario}.", file=sys.stderr) + return 1 + evidence = json.loads(TRIAL_EVIDENCE.read_text(encoding="utf-8")) + assert evidence["scenario"] == scenario + summary = evidence["summary"] + adaptive_variant = evidence["variant"] == "ai-dev" + if scenario == "adaptive": + expected = {f"module-{index}.md": f"# Public module {index}" for index in range(1, 5)} + selected = {row["path"]: row["content"] for row in summary["selected_files"]} + assert selected.keys() == expected.keys() + assert all(selected[path].startswith(heading) for path, heading in expected.items()) + assert summary["adaptive_context"]["enabled"] is adaptive_variant + else: + validation = summary["validation"] + context = summary["context"] + assert summary["decision"]["ready"] is True + assert summary["changes"]["files"] == ["src/app.py"] + assert validation["status"] == context["status"] == "success" + assert validation["checks_total"] == 24 and validation["checks_failed"] == 0 + assert context["incremental"]["context_id"] == "stable-context" + assert summary["delta"]["state_fingerprint"] == "stable-state" + assert summary["delta"]["reused"] is adaptive_variant + if adaptive_variant: + assert validation["result_count"] == 24 + assert context["selected_file_count"] == 1 + assert summary["observations"]["current_evidence_id"] == "observation:stable" + else: + assert len(validation["results"]) == 24 + assert [row["path"] for row in context["selected_files"]] == ["src/app.py"] + assert summary["observations"]["current"]["evidence_id"] == "observation:stable" + print(f"Verified {scenario} fixture outcome") + return 0 + + def _pytest(tests: list[str]) -> subprocess.CompletedProcess[str]: return subprocess.run( [ diff --git a/scripts/benchmark_mcp_context_ack.py b/scripts/benchmark_mcp_context_ack.py index 23fc22f..d4e9b49 100644 --- a/scripts/benchmark_mcp_context_ack.py +++ b/scripts/benchmark_mcp_context_ack.py @@ -1,40 +1,47 @@ from __future__ import annotations import json -import os -import shutil import sys -import uuid +import tempfile from pathlib import Path from typing import Any from ai_dev_tools.mcp_server import LocalMcpServer from ai_dev_tools.runners.benchmark import METRICS_PREFIX +README_PREFIX = "bounded project context\n" + def main() -> int: - if len(sys.argv) != 2 or sys.argv[1] not in {"baseline", "ai-dev"}: - print("usage: benchmark_mcp_context_ack.py baseline|ai-dev", file=sys.stderr) + if len(sys.argv) != 2 or sys.argv[1] not in {"reset", "baseline", "ai-dev", "validate"}: + print("usage: benchmark_mcp_context_ack.py reset|baseline|ai-dev|validate", file=sys.stderr) return 2 - root = ( - Path.cwd() - / ".ai" - / "tmp" - / f"ai-dev-context-ack-{os.getpid()}-{uuid.uuid4().hex}" - ) - root.mkdir(parents=True) - try: + action = sys.argv[1] + evidence = Path.cwd() / ".ai" / "tmp" / "context-ack-benchmark-evidence.json" + if action == "reset": + evidence.unlink(missing_ok=True) + return 0 + if action == "validate": + return validate(evidence) + + evidence.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(prefix="ai-dev-context-ack-") as temp: + root = Path(temp) (root / "pyproject.toml").write_text( "[project]\nname='context-ack-benchmark'\nversion='0.0.0'\n", encoding="utf-8", ) - (root / "README.md").write_text("bounded project context\n" * 200, encoding="utf-8") + (root / "README.md").write_text(README_PREFIX * 200, encoding="utf-8") server = LocalMcpServer(root) arguments: dict[str, object] = { "task": "inspect project documentation", + "profile": "docs", "max_chars": 20_000, - "max_file_chars": 4_000, + "max_file_chars": 8_000, + "incremental": False, + "adaptive": False, + "write_artifacts": True, } first = _call(server, arguments) first_summary = _summary(first) @@ -44,14 +51,14 @@ def main() -> int: return 1 second_arguments = dict(arguments) - if sys.argv[1] == "baseline": + if action == "baseline": second_arguments["delta"] = False else: second_arguments["acknowledged_state"] = delta["state_fingerprint"] second = _call(server, second_arguments) second_summary = _summary(second) second_delta = second_summary.get("delta") - expected_reuse = sys.argv[1] == "ai-dev" + expected_reuse = action == "ai-dev" if ( second.get("status") != "success" or not isinstance(second_delta, dict) @@ -60,14 +67,17 @@ def main() -> int: print("Repeated context response did not satisfy delta invariants.", file=sys.stderr) return 1 + selected = set(_selected(first_summary if expected_reuse else second_summary)) + expected = {"README.md", "pyproject.toml"} + evidence.write_text( + json.dumps({"variant": action, "first": first, "second": second}), encoding="utf-8" + ) metrics = { - "outcome_signature": "unchanged-context-confirmed", "iterations": 2, - "files_read": 1, - "selected_items": 1, - "relevant_items": 1, - "true_positive_items": 1, - "false_negative_items": 0, + "selected_items": len(selected), + "relevant_items": len(expected), + "true_positive_items": len(selected & expected), + "false_negative_items": len(expected - selected), } print( METRICS_PREFIX + json.dumps(metrics, sort_keys=True, separators=(",", ":")), @@ -75,8 +85,34 @@ def main() -> int: ) print(json.dumps(second, ensure_ascii=False, sort_keys=True, separators=(",", ":"))) return 0 - finally: - shutil.rmtree(root, ignore_errors=True) + + +def _selected(summary: dict[str, Any]) -> dict[str, str]: + return {row["path"]: row.get("content", "") for row in summary.get("selected_files", [])} + + +def validate(evidence: Path) -> int: + if not evidence.is_file(): + print("Missing context acknowledgement evidence.", file=sys.stderr) + return 1 + trial = json.loads(evidence.read_text(encoding="utf-8")) + first = _summary(trial["first"]) + second = _summary(trial["second"]) + selected = _selected(first) + assert trial["first"]["status"] == trial["second"]["status"] == "success" + assert selected.get("README.md") == README_PREFIX * 200 + assert "name='context-ack-benchmark'" in selected.get("pyproject.toml", "") + assert first["delta"]["state_fingerprint"] == second["delta"]["state_fingerprint"] + if trial["variant"] == "ai-dev": + assert second["delta"]["reused"] is True + assert second["delta"]["acknowledged_fingerprint"] == first["delta"]["state_fingerprint"] + assert second["context_receipt"]["selected_file_count"] == len(selected) + assert not _selected(second) + else: + assert second["delta"]["reused"] is False + assert _selected(second) == selected + print("Verified acknowledged README context") + return 0 def _call(server: LocalMcpServer, arguments: dict[str, object]) -> dict[str, Any]: diff --git a/tests/unit/test_benchmark.py b/tests/unit/test_benchmark.py index 257ddc9..56fdace 100644 --- a/tests/unit/test_benchmark.py +++ b/tests/unit/test_benchmark.py @@ -4,6 +4,8 @@ import sys from pathlib import Path +import pytest + from ai_dev_tools.cli import main from ai_dev_tools.runners.benchmark import ( METRICS_PREFIX, @@ -15,6 +17,7 @@ run_benchmark, ) from ai_dev_tools.utils.subprocess import CommandResult +from scripts import benchmark_agent_workflow, benchmark_mcp_context_ack def _suite(root: Path) -> Path: @@ -225,3 +228,43 @@ def test_versioned_agent_workflow_manifests_share_the_final_fixture() -> None: assert spec["working_directory"].name == "agent-workflow" assert set(spec["variants"]) == {"baseline", "ai-dev"} assert spec["validation_command"][-2:] == [scenario, "validate"] + + +@pytest.mark.parametrize("scenario", ["adaptive", "feedback-delta"]) +def test_scripted_corpus_rejects_missing_trial_evidence( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, scenario: str +) -> None: + monkeypatch.setattr(benchmark_agent_workflow, "ADAPTIVE_FIXTURE", tmp_path) + monkeypatch.setattr(benchmark_agent_workflow, "TRIAL_EVIDENCE", tmp_path / "evidence.json") + + assert benchmark_agent_workflow._validate(scenario) == 1 + + +def test_context_ack_oracle_rejects_acknowledged_empty_selection(tmp_path: Path) -> None: + evidence = tmp_path / "evidence.json" + evidence.write_text( + json.dumps( + { + "variant": "ai-dev", + "first": { + "status": "success", + "summary": {"delta": {"state_fingerprint": "same"}, "selected_files": []}, + }, + "second": { + "status": "success", + "summary": { + "delta": { + "state_fingerprint": "same", + "acknowledged_fingerprint": "same", + "reused": True, + }, + "context_receipt": {"selected_file_count": 0}, + }, + }, + } + ), + encoding="utf-8", + ) + + with pytest.raises(AssertionError): + benchmark_mcp_context_ack.validate(evidence) From fa7f99fe2b59de8add7b05fb1f96829932cadce1 Mon Sep 17 00:00:00 2001 From: Mateusz Lewandowski Date: Mon, 23 Nov 2026 19:16:16 +0100 Subject: [PATCH 3/3] Retry reading supervisor metadata published during a stop --- TODO.md | 2 +- src/ai_dev_tools/runtime/runner.py | 3 ++- tests/unit/test_runtime_runner.py | 23 +++++++++++++++++++++++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/TODO.md b/TODO.md index d63a482..4e12135 100644 --- a/TODO.md +++ b/TODO.md @@ -14,7 +14,7 @@ current acceptance criteria. The roadmap documents the capabilities shipped in t | Priority | Issues | | --- | --- | -| P0 | [MCP metadata #131](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/131), [correctness gate #134](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/134), [agent measurement #133](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/133) | +| P0 | [MCP metadata #131](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/131), [correctness gate #134](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/134), [agent measurement #133](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/133), [managed stop race #146](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/146) | | P1 | [Node diagnostics #128](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/128), [repository navigation #136](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/136), [MCP symbol lookup #137](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/137), [module responsibilities #135](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/135), [adoption #138](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/138), [failure loops #139](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/139), [affected tests #140](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/140) | | P2 | [Verified repository knowledge #141](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/141), [FTS5 evaluation #142](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/142), [native profiling #143](https://github.com/MatthiasLew/ai-dev-cli-tools/issues/143) | diff --git a/src/ai_dev_tools/runtime/runner.py b/src/ai_dev_tools/runtime/runner.py index 7a34406..3cdc638 100644 --- a/src/ai_dev_tools/runtime/runner.py +++ b/src/ai_dev_tools/runtime/runner.py @@ -484,7 +484,8 @@ def _read_control_state(path: Path) -> dict[str, object]: ) ): return pending - return state + # The supervisor may publish the temporary file between the two reads. + return state or _read_json(path) def _heartbeat_is_fresh(state: dict[str, object]) -> bool: diff --git a/tests/unit/test_runtime_runner.py b/tests/unit/test_runtime_runner.py index 95164ed..a8f5f31 100644 --- a/tests/unit/test_runtime_runner.py +++ b/tests/unit/test_runtime_runner.py @@ -354,6 +354,29 @@ def test_stop_explain_and_timeout(monkeypatch, tmp_path: Path) -> None: # type: assert timed_out.issues[0].code == "STOP_TIMEOUT" +def test_stop_observes_metadata_published_between_reads( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + metadata = tmp_path / ".ai" / "runtime" / "process.json" + metadata.parent.mkdir(parents=True) + pending = metadata.with_suffix(".json.tmp") + pending.write_text('{"status": "running", "token": "owned-runtime"}', encoding="utf-8") + read = runner._read_json + + def read_during_publication(path: Path) -> dict[str, object]: + if path == pending: + pending.replace(metadata) + return read(path) + + monkeypatch.setattr(runner, "_read_json", read_during_publication) + + report = stop_application(tmp_path, explain=True) + + assert report.status == "success" + assert report.summary["status"] == "would_request_stop" + assert "token" not in report.summary["state"] + + def test_resolve_run_plan_handles_invalid_and_yarn_packages(tmp_path: Path) -> None: package = tmp_path / "package.json" package.write_text("{", encoding="utf-8")