The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(ci): cap every AGENTS.md chain below the context budget it is truncated at
Tekniume1ec584b5729
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex 07f2ad0cc57..82545d1e78e 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -218,14 +218,19 @@ jobs:# The OS lanes import only files carrying the matching marker, so a test that fakes# macOS (is_macos -> True, sys.platform -> "darwin") without `platforms("macos")` is green on- # Linux over a faked branch and never runs on macOS (#111866, AGENTS.md § Don't fake the host OS).+ # Linux over a faked branch and never runs on macOS (#111866, tests/AGENTS.md § Don't fake the host OS).- name: Forbid unmarked macOS fakes in testsrun: python scripts/ci/check_os_marker_fakes.py+ # Every AGENTS.md from the git root down to the working directory loads as one+ # project-context block (30,720 chars on a 128k window); chains are capped at 30k.+ - name: Keep every AGENTS.md under its truncation cap+ run: python scripts/ci/check_agents_md_size.py+# Advisory: profile-scope hazard shapes on the lines this PR adds (child env from os.environ,# raw os.getenv of a platform credential, HOME-only RPC binding, bare-PID liveness). One# process serves many profiles; every pattern leaked the launch profile at least once. Printed- # into the log for the reviewer; never fails the job (root AGENTS.md § Code Shape Rules).+ # into the log for the reviewer; never fails the job (root AGENTS.md § Rules that apply everywhere).- name: Profile-scope patterns on added lines (advisory)if: github.event_name == 'pull_request'continue-on-error: truediff --git a/scripts/check b/scripts/checkindex c6d550389c2..cb318c56f11 100755--- a/scripts/check+++ b/scripts/check@@ -107,6 +107,7 @@ _GUARDS = {"no-tmp": ["scripts/check_no_tmp_literals.py"],"config-writers": ["scripts/check_config_yaml_writers.py"],"os-marker-fakes": ["scripts/ci/check_os_marker_fakes.py"],+ "agents-md": ["scripts/ci/check_agents_md_size.py"],"case-collisions": ["scripts/check-case-collisions.py"],"lazy-deps": ["scripts/ci/check_lazy_deps_imports.py"],"profile-archives": ["scripts/ci/check_profile_archive_boundary.py"],diff --git a/scripts/ci/check_agents_md_size.py b/scripts/ci/check_agents_md_size.pynew file mode 100644index 00000000000..43cdcf6a015--- /dev/null+++ b/scripts/ci/check_agents_md_size.py@@ -0,0 +1,65 @@+#!/usr/bin/env python3+"""Fail when a tracked AGENTS.md would be truncated when an agent loads it.++An agent started in a directory gets every AGENTS.md from the git root down to that directory as+ONE project-context block: ``agent/prompt_builder.py`` joins the chain before truncating it, at 6%+of the context window (30,720 chars on a 128k-token model, a 20k floor on small ones). So the+budget is per CHAIN: each AGENTS.md plus all of its ancestors stays within CHAIN_MAX_CHARS (the+128k budget minus room for the per-file provenance labels), and the root, which is in every+chain, stays within ROOT_MAX_CHARS so area files have room. An area file reached as a+subdirectory hint is also capped by ``_MAX_HINT_CHARS`` in ``agent/subdirectory_hints.py``, read+from the source here so the two can never drift. Shrink a file (move long form to the developer+guide or a sibling doc) instead of raising any number.++Exit codes: 0 = all within their caps, 1 = a file or chain is over (paths and sizes printed).+"""++from __future__ import annotations++import ast+import subprocess+import sys+from pathlib import Path, PurePosixPath++ROOT_MAX_CHARS = 12_000+CHAIN_MAX_CHARS = 30_000+++def _int_constant(source: Path, name: str) -> int:+ for node in ast.walk(ast.parse(source.read_text(encoding="utf-8-sig"))):+ if isinstance(node, ast.Assign) and any(getattr(t, "id", None) == name for t in node.targets):+ return int(ast.literal_eval(node.value))+ raise SystemExit(f"{source}: no {name} assignment; update scripts/ci/check_agents_md_size.py")+++def _chain(rel: str, sizes: dict[str, int]) -> list[str]:+ """Every tracked AGENTS.md from the root down to ``rel``, root first."""+ ancestors = [str(p / "AGENTS.md") if str(p) != "." else "AGENTS.md" for p in PurePosixPath(rel).parents]+ return [p for p in reversed(ancestors) if p in sizes and p != rel] + [rel]+++def main(repo: Path) -> int:+ hint_cap = _int_constant(repo / "agent" / "subdirectory_hints.py", "_MAX_HINT_CHARS")+ tracked = subprocess.run(+ ["git", "ls-files", "-z", "--", "AGENTS.md", "*/AGENTS.md"], cwd=repo, capture_output=True,+ check=True, stdin=subprocess.DEVNULL, timeout=60,+ ).stdout.decode("utf-8").split("\0")+ sizes = {rel: len((repo / rel).read_text(encoding="utf-8-sig")) for rel in filter(None, tracked)}+ over = []+ for rel, size in sorted(sizes.items()):+ cap = ROOT_MAX_CHARS if rel == "AGENTS.md" else hint_cap+ if size > cap:+ over.append(f"{rel}: {size} chars > {cap} cap")+ chain = _chain(rel, sizes)+ total = sum(sizes[p] for p in chain)+ if len(chain) > 1 and total > CHAIN_MAX_CHARS:+ over.append(f"{' + '.join(chain)}: {total} chars > {CHAIN_MAX_CHARS} chain cap")+ for line in over:+ print(line)+ if over:+ print("Move long form into website/docs/developer-guide/ or a sibling doc instead of raising a cap.")+ return 1 if over else 0+++if __name__ == "__main__":+ sys.exit(main(Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parents[2]))diff --git a/tests/scripts/test_check_agents_md_size.py b/tests/scripts/test_check_agents_md_size.pynew file mode 100644index 00000000000..07ed56fdefd--- /dev/null+++ b/tests/scripts/test_check_agents_md_size.py@@ -0,0 +1,37 @@+"""scripts/ci/check_agents_md_size.py: every AGENTS.md chain an agent can load stays under the cap it is truncated at."""++import subprocess+import sys+from pathlib import Path++SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "ci" / "check_agents_md_size.py"+++def _repo(tmp_path, files):+ (tmp_path / "agent").mkdir(parents=True)+ (tmp_path / "agent" / "subdirectory_hints.py").write_text("_MAX_HINT_CHARS = 32_000\n")+ for rel, chars in files.items():+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)+ (tmp_path / rel).write_text("x" * chars)+ (tmp_path / "untracked").mkdir()+ (tmp_path / "untracked" / "AGENTS.md").write_text("u" * 40_000)+ subprocess.run(["git", "init", "-q"], cwd=tmp_path, check=True)+ subprocess.run(["git", "add", "agent", *files], cwd=tmp_path, check=True)+ return tmp_path+++def _check(repo):+ return subprocess.run([sys.executable, str(SCRIPT), str(repo)], capture_output=True, text=True, check=False)+++def test_budget_is_per_chain_from_the_root_down(tmp_path):+ # Each file alone is small; root + app + app/src together is what an agent working in app/src loads.+ fits = {"AGENTS.md": 12_000, "app/AGENTS.md": 10_000, "app/src/AGENTS.md": 8_000, "lib/AGENTS.md": 18_000}+ ok = _check(_repo(tmp_path / "ok", fits))+ assert ok.returncode == 0, ok.stdout+ nested = _check(_repo(tmp_path / "nested", {**fits, "app/src/AGENTS.md": 8_001}))+ assert nested.returncode == 1+ assert "AGENTS.md + app/AGENTS.md + app/src/AGENTS.md: 30001 chars > 30000 chain cap" in nested.stdout+ assert "lib/" not in nested.stdout and "untracked" not in nested.stdout+ root = _check(_repo(tmp_path / "root", {"AGENTS.md": 12_001}))+ assert root.returncode == 1 and "AGENTS.md: 12001 chars > 12000 cap" in root.stdoutdiff --git a/tests/scripts/test_code_health_cli.py b/tests/scripts/test_code_health_cli.pyindex 29d1c700994..904a42eff55 100644--- a/tests/scripts/test_code_health_cli.py+++ b/tests/scripts/test_code_health_cli.py@@ -27,8 +27,9 @@ _GUARD_SCRIPTS = ("scripts/check_no_tmp_literals.py", "scripts/check_config_yaml_writers.py","scripts/ci/check_os_marker_fakes.py", "scripts/check-case-collisions.py","scripts/ci/check_lazy_deps_imports.py", "scripts/ci/check_profile_archive_boundary.py",+ "scripts/ci/check_agents_md_size.py",)-_SUPPORT = ("scripts/ci/profile_scope_patterns.json", *_GUARD_SCRIPTS)+_SUPPORT = ("scripts/ci/profile_scope_patterns.json", "agent/subdirectory_hints.py", *_GUARD_SCRIPTS)_LEGACY = "def legacy(x):\n" + "".join(f" if x == {i}:\n return {i}\n" for i in range(21))_GROWN = _LEGACY + " if x == 99:\n return 99\n"_ENV_COPY = "import os\n\n\ndef child_env():\n env = os.environ.copy()\n return env\n"@@ -94,7 +95,7 @@ def _add_engine(repo: Path, checker: bool = True) -> list[str]:shutil.copy2(REPO / "scripts/check", repo / "scripts/check")shutil.copytree(REPO / "scripts/code_health", repo / "scripts/code_health",ignore=shutil.ignore_patterns("__pycache__"), dirs_exist_ok=True)- return ["scripts", "tests"]+ return ["agent", "scripts", "tests"]def _engine_repo(tmp_path: Path) -> Path: