"""Observe which local instruction files Codex includes before model execution."""
from hashlib import sha256
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
def main():
codex = shutil.which("codex.exe") or shutil.which("codex")
git = shutil.which("git")
if not codex or not git:
raise SystemExit("Install Codex CLI and Git and add both to PATH.")
cases = []
with TemporaryDirectory(prefix="mbsky-codex-project-docs-") as temp:
root = Path(temp)
repo = root / "repo"
child = repo / "filter"
sibling = repo / "reports"
home = root / "profile"
other_home = root / "alternate"
for folder in (child, sibling, home, other_home):
folder.mkdir(parents=True)
env = {key: val for key, val in os.environ.items() if not key.startswith(("CODEX_", "GIT_"))}
env.update(CODEX_HOME=str(home), GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull)
subprocess.run([git, "init", "--quiet", "--template=", str(repo)], env=env, check=True, capture_output=True)
def cli(*args, profile=home, cwd=repo):
completed = subprocess.run([codex, *args], cwd=cwd, env=dict(env, CODEX_HOME=str(profile)),
capture_output=True, encoding="utf8", timeout=18)
if completed.returncode:
raise RuntimeError(completed.stderr)
return completed.stdout
def put(directory, name, content):
(directory / name).write_bytes((content + "\n").encode())
def check(name, cwd, expected, *, profile=home, operation, settings=None, watch=None, cd=False):
args = ("-C", str(cwd)) if cd else ()
messages = json.loads(cli(*args, "debug", "prompt-input", "--", "Describe the catalog filters.",
profile=profile, cwd=repo if cd else cwd))
merged = "\n".join(part.get("text", "") for msg in messages for part in msg.get("content", ()))
candidates = watch or markers
actual = [tag for tag in sorted(candidates, key=merged.find) if tag in merged]
assert actual == expected, (name, expected, actual)
cases.append(dict(name="agents_" + name, input=dict(cwd=cwd.relative_to(repo).as_posix(),
profile=profile.name, settings=settings, markers=candidates), operation=operation,
expected=expected, actual=actual))
global_base, global_override, root_base, first, second, leaf_base, leaf_override, alternate = markers = [
"LAB_COMMON_B", "LAB_COMMON_O", "LAB_ROOT_B", "LAB_FALLBACK_FIRST",
"LAB_FALLBACK_SECOND", "LAB_LEAF_B", "LAB_LEAF_O", "LAB_ALTERNATE",
]
put(home, "AGENTS.md", global_base)
put(other_home, "AGENTS.md", alternate)
put(repo, "AGENTS.md", root_base)
put(child, "TEAM_NOTES.md", first)
put(child, ".guide.md", second)
put(sibling, "AGENTS.md", leaf_base)
check("fallback_disabled", child, [global_base, root_base], operation="Read subdirectory without a fallback list")
put(home, "config.toml", 'project_doc_fallback_filenames = ["TEAM_NOTES.md", ".guide.md"]')
check("fallback_order", child, [global_base, root_base, first], cd=True,
settings=["TEAM_NOTES.md", ".guide.md"], operation="Start with -C and add two ordered fallback names")
(child / "TEAM_NOTES.md").unlink()
check("second_fallback", child, [global_base, root_base, second], operation="Remove first fallback from fixture")
put(child, "AGENTS.md", leaf_base)
check("canonical", child, [global_base, root_base, leaf_base], operation="Add canonical leaf file beside a fallback")
put(child, "AGENTS.override.md", leaf_override)
put(home, "AGENTS.override.md", global_override)
check("override", child, [global_override, root_base, leaf_override], operation="Use populated overrides at home and leaf")
check("root_scope", repo, [global_override, root_base], operation="Launch from root with two child directories")
(child / "AGENTS.override.md").write_bytes(b"")
check("empty_override", child, [global_override, root_base], operation="Use a zero-byte leaf override with a populated base")
(child / "AGENTS.override.md").unlink()
check("isolated_home", child, [alternate, root_base, leaf_base], profile=other_home,
operation="Switch to an independent CODEX_HOME while retaining the same repository")
watch = [global_override, root_base, "LAB_TRAILING", leaf_base]
put(repo, "AGENTS.md", root_base + "\n" + "填" * 60 + "\nLAB_TRAILING")
for budget, expected in [(48, [global_override, root_base]), (400, watch)]:
put(home, "config.toml", f"project_doc_max_bytes = {budget}")
check("bytes_" + str(budget), child, expected, watch=watch, settings=budget,
operation="Reopen from leaf and inspect markers with a configured project byte limit")
version = cli("--version").strip()
git_version = subprocess.run([git, "--version"], check=True, env=env, capture_output=True,
encoding="utf8").stdout.strip()
print(json.dumps(dict(version={"python": sys.version.split()[0], "codex": version, "git": git_version},
codex_sha256=sha256(Path(codex).read_bytes()).hexdigest(), cases=cases)))
if __name__ == "__main__":
main()
本例需在 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1、git version 2.54.0.windows.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1、git version 2.54.0.windows.1。
入口文件:projects/codex-agents_md/agents_md_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
agents_md_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1、git version 2.54.0.windows.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a89.zip
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a90.zip