chore: drop the flat content mirror and native install support (ADR-0024)

apm becomes the only supported install path. The flat mirror at each plugin
root existed solely so Claude Code's native `claude plugin install` could
convention-scan plugin content (ADR-0017). With no native consumers, it cost
~20,000 tracked lines plus ~2,100 lines of sync tooling and ~88s of every
push to guard content apm never reads — and its only automated gate,
`claude plugin validate --strict`, passes on a plugin with zero content, so
it could not detect the defect ADR-0017 was created to fix.

Removes the mirror (213 files), the six per-plugin manifest pairs,
sync-plugin-content.sh, its 1,289-line test, the orphaned
marketplace-plugins.sh, and the check-plugin-content-sync and
validate-plugins pre-push hooks. The root `marketplace:` block and
.claude-plugin/ catalogue stay: apm's own marketplace consumers read that
same file, so `<name>@holocron` short names keep working.

tests/run-bats.sh now excludes .claude/skills/. apm installs from .apm/,
which carries the tests/ dirs the mirror stripped, so deployed .bats files
would otherwise be discovered and double-run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YR2CjVumUbEGWcMikcoXBD
This commit is contained in:
2026-09-14 16:59:42 +00:00
parent 0dffff3c21
commit 718c79af70
245 changed files with 298 additions and 22602 deletions

View File

@@ -1,20 +0,0 @@
{
"name": "core",
"version": "1.1.2",
"description": "Skills for authoring and auditing a repo's AGENTS.md and the provider adapter files that defer to it.",
"author": {
"name": "Defame1297",
"email": "defame1297@rkdr.net",
"url": "https://git.dev.rkdr.net/Defame1297/"
},
"license": "MIT",
"homepage": "https://git.dev.rkdr.net/Defame1297/holocron/src/branch/main/plugins/core",
"repository": "https://git.dev.rkdr.net/Defame1297/holocron/src/branch/main/plugins/core",
"keywords": [
"agents-md",
"documentation",
"audit",
"provider-adapter",
"governance"
]
}

View File

@@ -1,20 +0,0 @@
{
"name": "core",
"version": "1.1.2",
"description": "Skills for authoring and auditing a repo's AGENTS.md and the provider adapter files that defer to it.",
"author": {
"name": "Defame1297",
"email": "defame1297@rkdr.net",
"url": "https://git.dev.rkdr.net/Defame1297/"
},
"license": "MIT",
"homepage": "https://git.dev.rkdr.net/Defame1297/holocron/src/branch/main/plugins/core",
"repository": "https://git.dev.rkdr.net/Defame1297/holocron/src/branch/main/plugins/core",
"keywords": [
"agents-md",
"documentation",
"audit",
"provider-adapter",
"governance"
]
}

View File

@@ -1,46 +0,0 @@
---
name: agentsmd-audit
description: >
Use when the user wants a repo's AGENTS.md audited for secrets, structure
and drift — "is this AGENTS.md safe to commit" — or after a hand-edit
outside `agentsmd-author`.
Not converting a provider file -> `provider-adapter-author`.
Not writing AGENTS.md -> `agentsmd-author`.
allowed-tools: Bash Read
metadata:
category: docs
source_keys:
- agents-md-official
- context7-websites-agents-md
- context7-agentsmd-agents-md
- governance-secrets-hard-prohibition
version: "0.1.2"
---
## Gotchas
- Always run all three checks — this skill does a single combined pass, not staged/gated passes. Don't skip structure or drift checks just because a secrets FAIL was found.
- Never inspect or mention provider-specific adapter files (`CLAUDE.md`, `.cursor/rules/*.mdc`, `copilot-instructions.md`, etc.) — that's out of scope.
- Gather findings internally; don't narrate PASS/FAIL per check as you go — surface them only in the final report.
## Step 1 — Run the validators
```bash
bash scripts/validate-secrets.sh <repo-root>
bash scripts/validate-structure.sh <repo-root>
bash scripts/validate-drift.sh <repo-root>
```
Each script walks the repo for every `AGENTS.md` file (root and nested, excluding `.git`, `node_modules`, `vendor`, and similar) and prints `FAIL` lines, plus `INFO`/`SUGGESTION` where applicable, with `Why`/`Fix` (or `Note`) per finding. A nonzero exit means at least one FAIL was found in that dimension. If a script cannot execute (`python3` unavailable, Bash denied), fall back to manual review: scan for real-looking credentials, check common sections are present, and spot-check a few referenced commands/paths by hand. Grade a manual finding the way the scripts grade theirs: a missing common section (e.g. no "Security" heading) is informational, not a failure — not every repo needs every section from the checklist. Only flag a FAIL when the file is empty, entirely unfilled placeholder text, or contains a real embedded secret/stale reference.
## Step 2 — Report
Open with a coverage line:
```text
Checked: secrets · structure · drift
```
Then output only findings that were found, in this order within a repo: `### Secrets`, `### Structure`, `### Drift`. Omit a dimension heading entirely if it produced nothing — its absence confirms it passed. Report each finding verbatim as emitted by the scripts (they already carry file:line, Why/Fix or Note).
Close with a `## Result` block holding one line: `PASS`, `PASS (N suggestions)`, or `FAIL (N fails · M suggestions)`, each optionally followed by ` · P info`. Omit the suggestion count when there are none, and omit `· P info` when there are none. INFO and SUGGESTION findings are observational — they never flip PASS to FAIL. Do not fix anything — this skill reports and proposes only. Point the user to `agentsmd-author` to apply fixes.

View File

@@ -1,33 +0,0 @@
# Sources
## agents-md-official
- **URL:** https://agents.md/
- **Description:** Official agents.md website — format spec, common-sections checklist, precedence rules (nearest-file-wins, no merge across files), monorepo nesting patterns
- **Research doc:** plugins/core/docs/research/docs/agentsmd/sources.md
- **Contributing files:** SKILL.md
- **Status:** `extracted`
## context7-websites-agents-md
- **URL:** context7:/websites/agents_md
- **Description:** Context7 index of the official agents.md website — overview, governance, cross-tool compatibility, configuration examples
- **Research doc:** plugins/core/docs/research/docs/agentsmd/sources.md
- **Contributing files:** SKILL.md
- **Status:** `extracted`
## context7-agentsmd-agents-md
- **URL:** context7:/agentsmd/agents.md
- **Description:** Context7 index of the agentsmd/agents.md repository — format spec, nested monorepo patterns, file structure examples
- **Research doc:** plugins/core/docs/research/docs/agentsmd/sources.md
- **Contributing files:** SKILL.md
- **Status:** `extracted`
## governance-secrets-hard-prohibition
- **URL:** (org convention — not a plugin research corpus entry)
- **Description:** Hard prohibition on placing secrets, API keys, tokens, or credentials in code, config, prompts, or any output. Grounds the secrets/credentials check in `scripts/validate-secrets.sh` and Step 1 of SKILL.md — AGENTS.md is committed content, so an embedded real secret is a hard-prohibition violation, not a style nit.
- **Research doc:** core/instructions/governance.md (org convention file, not a plugin research corpus entry; content is inlined here since plugins must be self-contained and this file may not exist wherever the plugin is installed)
- **Contributing files:** SKILL.md
- **Status:** `extracted`

View File

@@ -1,11 +0,0 @@
# scripts/
Deterministic validators this skill shells out to instead of relying on LLM judgment for mechanical checks.
| File | Purpose |
|------|---------|
| `validate-secrets.sh` | Scans every AGENTS.md file (root + nested) for embedded secrets, API keys, tokens, and connection strings |
| `validate-structure.sh` | Checks for empty/placeholder content, the common-sections checklist, and nested-vs-root duplication |
| `validate-drift.sh` | Resolves referenced npm/make commands and file paths against the actual repo state |
All three take a single `<repo-root>` argument, print `FAIL`/`INFO`/`SUGGESTION` findings to stdout, and exit non-zero only on FAIL.

View File

@@ -1,137 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<EOF
Usage: validate-drift.sh <repo-root>
Check every AGENTS.md file in a repo (root and nested) for drift: package
manager scripts and file paths referenced in the text that no longer exist
in the repo. Catches the failure mode that matters most in practice — an
agent running a documented command that was renamed or deleted.
Arguments:
repo-root Path to the repository root to scan.
Exit codes:
0 No FAIL findings (INFO may still be printed, e.g. no package.json found)
1 One or more FAIL findings
EOF
}
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
usage
exit 0
fi
if [[ $# -lt 1 ]]; then
echo "Error: repo-root is required." >&2
echo "" >&2
usage >&2
exit 1
fi
python3 -u - "$1" <<'PYTHON'
import sys
import os
import re
import json
repo_root = os.path.abspath(sys.argv[1])
if not os.path.isdir(repo_root):
print(f"Error: '{repo_root}' is not a directory.", file=sys.stderr)
sys.exit(1)
EXCLUDE_DIRS = {".git", "node_modules", "vendor", ".venv", "venv", "dist", "build"}
def find_agents_md(root):
results = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [d for d in dirnames if d not in EXCLUDE_DIRS and not d.startswith(".")]
for fname in filenames:
if fname == "AGENTS.md":
results.append(os.path.join(dirpath, fname))
return sorted(results)
def load_package_scripts(root):
pkg_path = os.path.join(root, "package.json")
if not os.path.isfile(pkg_path):
return None
try:
with open(pkg_path, encoding="utf-8") as f:
data = json.load(f)
except (json.JSONDecodeError, OSError):
return None
return set(data.get("scripts", {}).keys())
def load_make_targets(root):
make_path = os.path.join(root, "Makefile")
if not os.path.isfile(make_path):
return None
with open(make_path, encoding="utf-8", errors="replace") as f:
content = f.read()
return set(re.findall(r'(?m)^([a-zA-Z0-9_-]+)\s*:(?!=)', content))
NPM_RUN_RE = re.compile(r'\b(?:npm|pnpm|yarn)\s+run\s+([a-zA-Z0-9:_-]+)')
MAKE_RE = re.compile(r'\bmake\s+([a-zA-Z0-9_-]+)')
# Backticked relative file paths, e.g. `scripts/bootstrap.sh`, `src/index.ts`.
# Requires a path separator and file extension to avoid matching bare commands/words.
PATH_RE = re.compile(r'`([A-Za-z0-9_.\-]+(?:/[A-Za-z0-9_.\-]+)+\.[A-Za-z0-9]+)`')
has_fail = False
package_scripts = load_package_scripts(repo_root)
make_targets = load_make_targets(repo_root)
for fpath in find_agents_md(repo_root):
rel = os.path.relpath(fpath, repo_root)
with open(fpath, encoding="utf-8", errors="replace") as f:
content = f.read()
for m in NPM_RUN_RE.finditer(content):
script_name = m.group(1)
if package_scripts is None:
print(f"INFO Cannot verify referenced script '{script_name}' — {rel}")
print(f" Note: AGENTS.md references an npm/pnpm/yarn script, but no package.json was found at the repo root to check it against.")
print()
elif script_name not in package_scripts:
has_fail = True
print(f"FAIL Referenced script '{script_name}' not found in package.json — {rel}")
print(f" Why: AGENTS.md tells agents to run '{script_name}', but package.json has no matching \"scripts\" entry — the command will fail.")
print(f" Fix: Update AGENTS.md to reference an existing script, or add '{script_name}' to package.json's scripts.")
print()
for m in MAKE_RE.finditer(content):
target_name = m.group(1)
if make_targets is None:
print(f"INFO Cannot verify referenced make target '{target_name}' — {rel}")
print(f" Note: AGENTS.md references a make target, but no Makefile was found at the repo root to check it against.")
print()
elif target_name not in make_targets:
has_fail = True
print(f"FAIL Referenced make target '{target_name}' not found in Makefile — {rel}")
print(f" Why: AGENTS.md tells agents to run 'make {target_name}', but the Makefile has no matching target — the command will fail.")
print(f" Fix: Update AGENTS.md to reference an existing target, or add '{target_name}' to the Makefile.")
print()
file_dir = os.path.dirname(fpath)
for m in PATH_RE.finditer(content):
candidate = m.group(1)
resolved = (
os.path.isfile(os.path.join(repo_root, candidate))
or os.path.isfile(os.path.join(file_dir, candidate))
or os.path.isdir(os.path.join(repo_root, candidate))
or os.path.isdir(os.path.join(file_dir, candidate))
)
if not resolved:
has_fail = True
print(f"FAIL Referenced path '{candidate}' does not exist — {rel}")
print(f" Why: AGENTS.md points agents to '{candidate}', but it isn't present in the repo (checked relative to repo root and to the AGENTS.md's own directory).")
print(f" Fix: Update AGENTS.md to reference the correct path, or restore/create '{candidate}'.")
print()
if has_fail:
sys.exit(1)
sys.exit(0)
PYTHON

View File

@@ -1,120 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<EOF
Usage: validate-secrets.sh <repo-root>
Scan every AGENTS.md file in a repo (root and nested) for embedded secrets,
API keys, tokens, or connection strings. AGENTS.md is committed content —
real credentials in it are a hard-prohibition violation, not a style nit.
Placeholders (<your-key>, \$ENV_VAR, YOUR_TOKEN_HERE, example.com, etc.) are
not flagged.
Arguments:
repo-root Path to the repository root to scan.
Exit codes:
0 No findings
1 One or more FAIL findings
EOF
}
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
usage
exit 0
fi
if [[ $# -lt 1 ]]; then
echo "Error: repo-root is required." >&2
echo "" >&2
usage >&2
exit 1
fi
python3 -u - "$1" <<'PYTHON'
import sys
import os
import re
repo_root = os.path.abspath(sys.argv[1])
if not os.path.isdir(repo_root):
print(f"Error: '{repo_root}' is not a directory.", file=sys.stderr)
sys.exit(1)
EXCLUDE_DIRS = {".git", "node_modules", "vendor", ".venv", "venv", "dist", "build"}
def find_agents_md(root):
results = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [d for d in dirnames if d not in EXCLUDE_DIRS and not d.startswith(".")]
for fname in filenames:
if fname == "AGENTS.md":
results.append(os.path.join(dirpath, fname))
return sorted(results)
PLACEHOLDER_RE = re.compile(
r'(?i)(your[_-]|my[_-]|example|xxx+|placeholder|changeme|<[^>]+>|\$\{|\$[A-Z_][A-Z0-9_]*|\.\.\.|redacted)'
)
PATTERNS = [
("AWS access key ID", re.compile(r'AKIA[0-9A-Z]{16}')),
("Private key block", re.compile(r'-----BEGIN [A-Z ]*PRIVATE KEY-----')),
("GitHub token", re.compile(r'gh[pousr]_[A-Za-z0-9]{36,}')),
("Slack token", re.compile(r'xox[baprs]-[A-Za-z0-9-]{10,}')),
("GitLab token", re.compile(r'glpat-[A-Za-z0-9_-]{20,}')),
("Generic API-style secret token", re.compile(r'\bsk-[A-Za-z0-9]{20,}\b')),
(
"Credential-bearing connection string",
re.compile(r'[a-zA-Z][a-zA-Z0-9+.-]*://[^:@/\s]+:[^@/\s]+@[^\s\'"]+'),
),
(
"Assigned secret/password/token literal",
re.compile(
r'(?i)\b(api[_-]?key|secret|token|password|passwd|pwd|access[_-]?key)\b'
r'\s*[:=]\s*[\'"]?([A-Za-z0-9+/_.\-]{12,})[\'"]?'
),
),
]
findings = []
def emit_fail(desc, fpath, lineno, why, fix):
findings.append((desc, fpath, lineno, why, fix))
for fpath in find_agents_md(repo_root):
rel = os.path.relpath(fpath, repo_root)
with open(fpath, encoding="utf-8", errors="replace") as f:
lines = f.readlines()
for i, line in enumerate(lines, start=1):
for label, pattern in PATTERNS:
m = pattern.search(line)
if not m:
continue
# Scope the placeholder allowlist to the matched secret-candidate
# substring only. Checking the whole line would let an unrelated
# placeholder-looking token elsewhere on the line (e.g. in a
# trailing comment) suppress detection of a real credential.
value = m.group(0)
if PLACEHOLDER_RE.search(value):
continue
emit_fail(
f"Possible {label}",
f"{rel}:{i}",
i,
"AGENTS.md is committed content; this line matches a real-looking credential pattern rather than a placeholder.",
"Remove the embedded credential and replace it with an environment variable reference or placeholder (e.g. $API_KEY, <your-token>).",
)
break
if not findings:
sys.exit(0)
for desc, fpath, _lineno, why, fix in findings:
print(f"FAIL {desc} — {fpath}")
print(f" Why: {why}")
print(f" Fix: {fix}")
print()
sys.exit(1)
PYTHON

View File

@@ -1,118 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<EOF
Usage: validate-structure.sh <repo-root>
Check every AGENTS.md file in a repo (root and nested) for structural
completeness against the agents.md spec's common-sections checklist
(setup/build, code style, testing, security, commit/PR conventions).
Missing individual sections are informational (not every repo needs every
section) — only an empty or entirely unfilled file is a hard failure.
Arguments:
repo-root Path to the repository root to scan.
Exit codes:
0 No FAIL findings (INFO/SUGGESTION may still be printed)
1 One or more FAIL findings
EOF
}
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
usage
exit 0
fi
if [[ $# -lt 1 ]]; then
echo "Error: repo-root is required." >&2
echo "" >&2
usage >&2
exit 1
fi
python3 -u - "$1" <<'PYTHON'
import sys
import os
import re
PLACEHOLDER_RE = re.compile(r'(?i)FILL IN:|TODO:\s*write|lorem ipsum')
COMMON_SECTIONS = [
("setup/build commands", re.compile(r'(?im)^#{1,3}\s*(setup|install|build|getting started)')),
("code style", re.compile(r'(?im)^#{1,3}\s*(code style|style guide|conventions)')),
("testing instructions", re.compile(r'(?im)^#{1,3}\s*(test|testing)')),
("security considerations", re.compile(r'(?im)^#{1,3}\s*security')),
("commit/PR conventions", re.compile(r'(?im)^#{1,3}\s*(commit|pr|pull request)')),
]
repo_root = os.path.abspath(sys.argv[1])
if not os.path.isdir(repo_root):
print(f"Error: '{repo_root}' is not a directory.", file=sys.stderr)
sys.exit(1)
EXCLUDE_DIRS = {".git", "node_modules", "vendor", ".venv", "venv", "dist", "build"}
def find_agents_md(root):
results = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = [d for d in dirnames if d not in EXCLUDE_DIRS and not d.startswith(".")]
for fname in filenames:
if fname == "AGENTS.md":
results.append(os.path.join(dirpath, fname))
return sorted(results)
has_fail = False
file_contents = {} # rel path -> content, for the duplication pass below
for fpath in find_agents_md(repo_root):
rel = os.path.relpath(fpath, repo_root)
with open(fpath, encoding="utf-8", errors="replace") as f:
content = f.read()
file_contents[rel] = content
if not content.strip():
has_fail = True
print(f"FAIL AGENTS.md is empty — {rel}")
print(" Why: An empty file provides no instructions and gives agents nothing to act on.")
print(" Fix: Add at least a project overview and setup/test commands, per the agents.md common-sections checklist.")
print()
continue
if PLACEHOLDER_RE.search(content):
has_fail = True
print(f"FAIL Unfilled placeholder content — {rel}")
print(" Why: A 'FILL IN:' or template stub left in place means the file has no repo-specific instructions yet.")
print(" Fix: Replace the placeholder with real, repo-specific content.")
print()
continue
for label, pattern in COMMON_SECTIONS:
if not pattern.search(content):
print(f"INFO No {label} section — {rel}")
print(f" Note: The agents.md common-sections checklist includes {label}; not every repo needs every section, but confirm this omission is deliberate.")
print()
# --- Nested-vs-root duplication check ---
root_content = file_contents.get("AGENTS.md")
if root_content:
root_lines = {ln.strip() for ln in root_content.splitlines() if ln.strip()}
for rel, content in file_contents.items():
if rel == "AGENTS.md":
continue
nested_lines = [ln.strip() for ln in content.splitlines() if ln.strip()]
if not nested_lines:
continue
overlap = sum(1 for ln in nested_lines if ln in root_lines)
ratio = overlap / len(nested_lines)
if ratio >= 0.7:
print(f"SUGGESTION Nested AGENTS.md largely duplicates the root file — {rel}")
print(f" Why: {ratio:.0%} of this file's content lines already appear in the root AGENTS.md; per the spec's nearest-file-wins precedence, nested files don't inherit from the root, but they also shouldn't just restate it.")
print(f" Fix: Trim {rel} down to only what's specific to this package/directory.")
print()
if has_fail:
sys.exit(1)
sys.exit(0)
PYTHON

View File

@@ -1,43 +0,0 @@
---
name: agentsmd-author
description: >
Use when the user wants a repo's AGENTS.md written or updated, root or
nested, including "document this for AI coding tools". Writes only verified
conventions. Not review-only -> `agentsmd-audit`. Not converting CLAUDE.md ->
`provider-adapter-author`.
allowed-tools: Bash Read Write Edit
metadata:
category: docs
source_keys:
- agents-md-official
- context7-websites-agents-md
- context7-agentsmd-agents-md
version: "0.1.2"
---
## Gotchas
- Never invent a command. Every line under a setup/test/build section must come from something you actually found in the repo (`package.json` scripts, a `Makefile` target, a CI workflow step, a README). If you can't verify a command, don't include it.
- Never write to a provider file yourself, in any circumstance: `CLAUDE.md`, `.cursor/rules/*.mdc`, `.github/copilot-instructions.md` and their equivalents are `provider-adapter-author`'s to own. That holds even when the user asks for one in the same breath as AGENTS.md, and even when the file is merely stale or missing a pointer rather than duplicating anything. Detect it and hand off.
## Step 1 — Explore the target repo
Before writing anything, gather real facts: package manager and scripts (`package.json`, `pyproject.toml`, `Cargo.toml`, etc.), a `Makefile` or task runner, CI config (`.github/workflows/`, etc.) for the commands it actually runs, linter/formatter config files, and any existing docs (`README.md`, existing `AGENTS.md`) describing conventions. Note whether any subdirectory looks like its own package with a different stack.
## Step 2 — Decide placement
- No `AGENTS.md` at the repo root yet → create one there first, covering whole-repo conventions.
- A subdirectory has materially different build/test tooling or conventions than the root → create or update a nested `AGENTS.md` there, scoped to what's different. Convenience is not a reason to create one — without a distinct stack you are duplicating content the root already covers. **Don't repeat root-level content** in a nested file: the nearest-file-wins rule means it is read alone, never merged back with the root.
- Otherwise → update the existing file(s) in place.
## Step 3 — Write or update
AGENTS.md has no required schema. Use only sections that reflect something real about the repo — never fill in every common-sections-checklist heading just because it exists, because a thin accurate file beats a padded generic one. Read `references/content-guide.md` for section-by-section guidance, a worked example, and what separates useful content from generic padding, before writing.
## Step 4 — Check for an existing provider file
Look for `CLAUDE.md`, `.cursor/rules/*.mdc`, `.github/copilot-instructions.md`, or similar in the target repo. If one exists, invoke the `provider-adapter-author` skill on it to reconcile — whether it duplicates content the AGENTS.md you just wrote/updated now owns, or is merely stale or missing a pointer to it. Never edit it yourself in either case.
## Step 5 — Audit and report
Invoke the `agentsmd-audit` skill on the target repo root — its validators take a `<repo-root>` and walk the tree for every AGENTS.md themselves; there is no per-file entry point. This closeout is mandatory, not optional, even when the change looks trivial — never sign the work off on your own judgment. Resolve any FAIL findings before considering the work done — re-invoke this skill's own writing steps to fix them, then re-run the audit, same as any other close-the-loop check. Report what was created/changed, whether a provider file was reconciled, and the audit's final result.

View File

@@ -1,118 +0,0 @@
---
source_keys:
- agents-md-official
- context7-websites-agents-md
- context7-agentsmd-agents-md
---
# What good AGENTS.md content looks like
AGENTS.md has no required schema — there's no field to fill in, only sections that either
earn their place or don't. Agents treat this file as a set of live directives, not
documentation: they will actually run the commands it lists and fix failures before
finishing a task. That means a wrong or stale line is worse than a missing one. Verify
every command against something real in the repo before writing it down.
## Section-by-section guidance
**Setup / build commands** — the install and dev-server commands, exactly as they appear
in `package.json` scripts, a `Makefile`, or a `Cargo.toml`/`pyproject.toml` equivalent. One
line per command, each with a one-clause note on what it does if the name alone isn't
obvious. Skip this section if there's genuinely nothing beyond "clone and run" — don't pad
it with a restated `git clone`.
**Code style** — only conventions that aren't already enforced by a linter/formatter config
the agent will pick up on its own (a `.eslintrc`, `rustfmt.toml`, etc. speaks for itself).
Write down the conventions that live only in people's heads: naming patterns, module
boundaries, patterns to avoid, anything a linter can't catch. If the repo has no
undocumented conventions beyond what tooling enforces, skip this section.
**Testing instructions** — the exact command(s) to run the suite, where to find
per-package or per-workflow test configuration (e.g. `.github/workflows/`), and any
non-obvious requirement (a service that must be running, an env var that must be set).
State plainly that the agent should run tests before considering a change done and fix
failures — don't leave this implicit.
**Security considerations** — only repo-specific hazards: a data-handling boundary, a
credential pattern to never hardcode, a destructive command that needs a confirmation
step. Do not restate general security advice ("don't commit secrets") that any agent
already assumes — that's padding, not a directive.
**Commit / PR conventions** — the title/format convention if one exists (e.g. a
Conventional Commits type prefix, a ticket-number requirement), and any check that must
pass before a PR is opened (lint, test, type-check). Point at the real command, not
"make sure it passes."
**Dev environment tips** — the handful of things that save real time and are easy to miss:
how to jump to a specific package in a monorepo without `ls`-ing around, how to register a
new package so the toolchain sees it, where to look up a canonical name/id. This section
is for genuine friction points observed in this repo, not generic advice.
## What separates useful content from padding
A useful section names a real file, command, or path that exists in this repo right now.
A padded section could be pasted into any repo unchanged and still "make sense" — that's
the tell. If a sentence would read the same in a different codebase, it doesn't belong.
Prefer four accurate lines over twelve generic ones.
## Worked example (minimal project)
```markdown
# AGENTS.md
## Setup commands
- Install deps: `pnpm install`
- Start dev server: `pnpm dev`
- Run tests: `pnpm test`
## Code style
- TypeScript strict mode
- Single quotes, no semicolons
- Use functional patterns where possible
## Dev environment tips
- Use `pnpm dlx turbo run where <project_name>` to jump to a package instead of scanning with `ls`.
- Run `pnpm install --filter <project_name>` to add the package to your workspace so Vite, ESLint, and TypeScript can see it.
- Check the `name` field inside each package's `package.json` to confirm the right name.
## Testing instructions
- Find the CI plan in the `.github/workflows` folder.
- Run `pnpm turbo run test --filter <project_name>` to run every check defined for that package.
- From the package root you can just call `pnpm test`. The commit should pass all tests before you merge.
- Fix any test or type errors until the whole suite is green.
- Add or update tests for the code you change, even if nobody asked.
## PR instructions
- Title format: [<project_name>] <Title>
- Always run `pnpm lint` and `pnpm test` before committing.
```
Every line above names a real command or path — that's the standard to hold this repo's
version to, not the specific tooling shown (a Python/Cargo/Go repo's AGENTS.md should look
nothing like this one in its specifics, only in how concrete each line is).
## Monorepo / nested placement
```
my-monorepo/
├── AGENTS.md # Root-level: applies to the whole repo
├── packages/
│ ├── api/
│ │ └── AGENTS.md # API-specific instructions; overrides root for this package
│ ├── web/
│ │ └── AGENTS.md # Web app-specific instructions
│ └── shared/
│ └── AGENTS.md # Shared library instructions
```
Precedence rule: the file nearest the edited path wins. Nested files are **not** merged
with the root file — an agent editing inside `packages/api/` reads only
`packages/api/AGENTS.md`, never the root file in addition. Consequences:
- A nested file must stand alone. Don't write "also see the root file" — write what the
agent needs, full stop.
- Don't duplicate root content in a nested file "just in case." If a nested file repeats
root-level setup instructions verbatim, that's a sign it shouldn't exist as a separate
file at all — the subtree isn't actually different enough to warrant one.
- Only create a nested file when the subtree has a genuinely different stack, build tool,
or convention than the root (see `SKILL.md` Step 2 for the placement decision itself).

View File

@@ -1,25 +0,0 @@
# Sources
## agents-md-official
- **URL:** https://agents.md/
- **Description:** Official agents.md website — format spec, common-sections checklist, precedence rules (nearest-file-wins, no merge across files), monorepo nesting patterns
- **Research doc:** plugins/core/docs/research/docs/agentsmd/sources.md
- **Contributing files:** SKILL.md, references/content-guide.md
- **Status:** `extracted`
## context7-websites-agents-md
- **URL:** context7:/websites/agents_md
- **Description:** Context7 index of the official agents.md website — overview, governance, cross-tool compatibility, configuration examples
- **Research doc:** plugins/core/docs/research/docs/agentsmd/sources.md
- **Contributing files:** SKILL.md, references/content-guide.md
- **Status:** `extracted`
## context7-agentsmd-agents-md
- **URL:** context7:/agentsmd/agents.md
- **Description:** Context7 index of the agentsmd/agents.md repository — format spec, nested monorepo patterns, file structure examples
- **Research doc:** plugins/core/docs/research/docs/agentsmd/sources.md
- **Contributing files:** SKILL.md, references/content-guide.md
- **Status:** `extracted`

View File

@@ -1,52 +0,0 @@
---
name: provider-adapter-author
description: >
Use when a provider file (CLAUDE.md, .cursor rules, copilot-instructions)
duplicating the repo's AGENTS.md should be cut to a thin adapter — "make
CLAUDE.md just import AGENTS.md".
Not writing the AGENTS file -> `agentsmd-author`.
Not auditing the AGENTS file -> `agentsmd-audit`.
allowed-tools: Bash Read Edit Write
metadata:
category: docs
source_keys:
- adr-0002-0003-two-tier-claude-md
version: "0.1.1"
---
## Gotchas
- Assume a provider has no cross-file import mechanism until you have confirmed it has one. Claude Code is the exception, not the rule: a `CLAUDE.md` may consist of nothing but `@path` lines, while the same `@AGENTS.md` line in a Cursor rule or a Copilot instructions file is inert text no tool resolves. Pass `--no-import-syntax` to `scripts/validate-adapter.sh` for those providers.
- Works standalone or composed-into by `agentsmd-author` — behave identically either way; do not assume a caller skill exists. Detect the provider file, confirm `AGENTS.md`, and run the closeout validator yourself in both cases (`references/provider-matrix.md`).
## Step 1 — Detect
Find the provider instruction file to convert. Before searching, read `references/provider-matrix.md` — skip it only when the target is already a known root `CLAUDE.md`, which is the common case.
Then confirm `AGENTS.md` exists at the repo root. If it does not, stop and tell the user to run `agentsmd-author` first — there is nothing to adapt to.
## Step 2 — Diff and rewrite
Read the provider file and `AGENTS.md` side by side. Separate the provider file's content into two buckets: lines that restate what `AGENTS.md` already owns (universal rules, conventions, project overview) versus lines that are genuinely provider-specific (tool syntax, IDE behavior, model-specific instructions). Rewrite the provider file:
- **Providers with import syntax** (Claude Code): replace the redundant bucket with an `@AGENTS.md` (or correct relative path) import on a line of its own, keep the provider-specific bucket below it. An import folded into a sentence is not the thin-adapter shape and `scripts/validate-adapter.sh` will not credit it — nor one inside a code fence, an indented block, or an HTML comment, nor one whose path does not resolve to a real, non-empty file on disk.
- **Providers without import syntax** (Cursor, Copilot, etc.): replace the redundant bucket with a short sentence pointing at `AGENTS.md` ("See AGENTS.md at the repo root for ..."), keep the provider-specific bucket. A bare or negated mention is not a pointer and will not be credited.
The provider file is the only file this skill ever writes. Never create or edit `AGENTS.md` — not in this step, not in any step, whatever the payoff looks like.
Strip only what is genuinely redundant. Provider-specific material stays even when it is short — the goal is thin, not empty.
## Step 3 — Self-validate
Run the bundled check before finishing — this is the skill's own closeout gate; there is no separate paired audit skill for this concern:
```bash
bash scripts/validate-adapter.sh [--no-import-syntax] [--max-lines N] <adapter-file> <agents-md-file>
```
Fix any `FAIL` by editing the provider file, and re-run until it exits `0`. Exits `2` and `3` are not `FAIL`s and nothing was graded under either, so neither is a reason to touch the adapter: `2` means the invocation or the input is wrong (a bad, missing, or extra argument, an unknown option, or a file that is not UTF-8), and `3` means a named file exists but could not be read.
## Step 4 — Report
State which file was converted, what was removed versus kept, and the validator's final result.

View File

@@ -1,32 +0,0 @@
---
source_keys:
- adr-0002-0003-two-tier-claude-md
---
# Known provider instruction files
Which files to look for when detecting a provider-specific instruction file, whether each provider
resolves a cross-file import, and what a thin adapter therefore looks like for it.
| Provider | File(s) | Import syntax | Thin adapter shape | Validator flag |
|---|---|---|---|---|
| Claude Code | `CLAUDE.md` at the repo root, plus any deployed copies | Yes — `@path` lines, e.g. `@AGENTS.md` | One or more `@` import lines; no other content is required | none |
| Cursor | `.cursor/rules/*.mdc` | No | A short sentence pointing at `AGENTS.md`, plus the rule's own frontmatter and provider-specific body | `--no-import-syntax` |
| GitHub Copilot | `.github/copilot-instructions.md` | No | A short sentence pointing at `AGENTS.md`, plus Copilot-only instructions | `--no-import-syntax` |
| Anything else | tool-specific instruction file at whatever path the tool documents | Assume no | Text pointer, as above | `--no-import-syntax` |
A provider not listed here is not evidence it has an import mechanism. Confirm against that tool's
own documentation before emitting an `@`-style line; an unresolved import reads as literal text and
silently drops every rule the adapter was supposed to defer to.
Detection is a search, not a lookup: a repo may hold more than one of these, and each one converts
independently against the same `AGENTS.md`.
## Standalone and composed runs behave identically
This skill is reached two ways: invoked directly by a user, and composed into by `agentsmd-author`
once it has written or updated the repo's `AGENTS.md`. Behave identically either way — do not
assume a caller skill exists. Detect the provider file yourself, confirm `AGENTS.md` yourself, and
run the closeout validator yourself, rather than treating any step as already done by the caller or
as something the caller will do afterwards. No handshake exists to rely on, and no state is
passed in beyond the file paths.

View File

@@ -1,9 +0,0 @@
# Sources
## adr-0002-0003-two-tier-claude-md
- **URL:** (in-repo precedent — not an external source or plugin research corpus entry)
- **Description:** This repo's own two-tier CLAUDE.md/AGENTS.md pattern: AGENTS.md is the provider-agnostic source of always-on rules; provider-specific files (CLAUDE.md) become thin adapters that import it (`@AGENTS.md` plus provider-specific additions). Grounds this skill's entire adapter-conversion design — the "thin adapter" shape, the `@`-import convention, and the size/duplication expectations enforced by `scripts/validate-adapter.sh`.
- **Research doc:** docs/adr/0002-two-tier-claude-md.md, docs/adr/0003-agents-md-provider-agnostic-entry-point.md, providers/claude-code/CLAUDE.md (in-repo ADRs and a live example, not a plugin research corpus entry; referenced here since this skill's design is modeled directly on an existing implementation rather than external research)
- **Contributing files:** SKILL.md, references/provider-matrix.md
- **Status:** `extracted`

View File

@@ -1,28 +0,0 @@
# scripts/
Deterministic self-check this skill shells out to instead of relying on LLM judgment for a mechanical check.
| File | Purpose |
|------|---------|
| `validate-adapter.sh` | Checks a rewritten provider file (CLAUDE.md, etc.) has a working reference to AGENTS.md, doesn't duplicate its content, and stays under a thin-file line threshold |
Takes exactly `<adapter-file> <agents-md-file>`, with optional `--no-import-syntax` and `--max-lines N` flags (also accepted as `--max-lines=N`). A third positional argument or an unknown option is an error, not something quietly ignored.
## What counts as a reference to AGENTS.md
Both modes require the named path to be a real path segment ending in `AGENTS.md` — `AGENTS.md` or `…/AGENTS.md`, not `NOTAGENTS.md` — that resolves on disk, relative to the adapter file, to a non-empty file. An adapter deferring to a path that is not there defers to nothing, so the check has to touch the disk rather than pattern-match the line.
A reference only counts where something would actually resolve it. A line inside a fenced code block, an indented code block, or an HTML comment is not credited in either mode: Claude Code resolves an import in none of those, so a fenced `@AGENTS.md` is the silent-drop failure this gate exists to catch, not a pass.
Default mode wants a real import: `@AGENTS.md` alone on its own line, indented no more than three spaces. `--no-import-syntax` wants a prose pointer that reads as one — the sentence naming `AGENTS.md` must carry a deference cue (see, read, refer to, documented in, conventions, …) and must not be negated. `Do NOT read AGENTS.md; it is obsolete.` and `We deleted AGENTS.md last year.` name the file while pointing the reader away from it, and neither is a pointer.
## Exit codes
The distinction matters because the skill's closeout tells the agent to fix any non-zero exit by editing the provider file. That is right for exactly one of these.
| Code | Meaning | What to do |
|------|---------|------------|
| `0` | Passes every check | Nothing |
| `1` | One or more `FAIL` findings printed to stdout — empty adapter, no working reference to AGENTS.md, excessive duplication, or not thin | Edit the provider file |
| `2` | Usage or input error: a bad, missing, or extra argument, an unknown option, a path that is not a file, or a file that is not UTF-8. Nothing was graded, so there is no `FAIL` line | Fix the invocation or the file's encoding — do not edit the adapter |
| `3` | A named input file exists but could not be read (permissions, I/O error). Nothing was graded and the adapter's contents are unknown | Fix the file's readability — do not edit the adapter |

View File

@@ -1,496 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<EOF
Usage: validate-adapter.sh [--no-import-syntax] [--max-lines N] <adapter-file> <agents-md-file>
Self-check gate for provider-adapter-author. Checks that a rewritten
provider-specific instruction file (CLAUDE.md, .cursor/rules/*.mdc,
copilot-instructions.md, etc.) is actually a thin adapter over AGENTS.md,
not a duplicate copy of it.
Arguments:
adapter-file Path to the provider-specific file to check.
agents-md-file Path to the AGENTS.md file it should defer to.
Exactly two positional arguments are accepted. Extra ones are rejected
rather than ignored: a third path silently graded nothing but the first
two, so a typo'd invocation passed against the wrong file.
Options:
--no-import-syntax The target provider has no native cross-file import
mechanism. Require a plain-text pointer line naming
"AGENTS.md" instead of an @import-style line; an
@AGENTS.md line alone does not satisfy it, because
such a provider never resolves it. Without this flag
an actual @import line is required, and naming
AGENTS.md in prose alone does not satisfy it.
--max-lines N Max non-blank lines allowed in the adapter file before
it's considered no longer "thin". Must be a
non-negative integer. Default: 60.
--help, -h Show this help and exit 0.
-- End of options; every later argument is positional.
Both flags also accept the --flag=value form (--max-lines=40). An unknown
option is reported as an unknown option, not as a missing file.
What counts as a reference:
In both modes the named path must be a real path segment ending in
AGENTS.md ("AGENTS.md" or ".../AGENTS.md" — not NOTAGENTS.md), and it must
resolve on disk, relative to the adapter file, to a non-empty file. An
adapter deferring to a path that is not there defers to nothing.
A mention inside a fenced code block, an indented code block, or an HTML
comment is not credited in either mode. Nothing resolves those, so an
adapter whose only "import" is fenced silently defers to nothing.
With --no-import-syntax the pointer must read as a pointer: the sentence
naming AGENTS.md has to carry a deference cue (see, read, refer to,
documented in, conventions, ...) and must not be a negation ("do not read
AGENTS.md", "we deleted AGENTS.md"). A bare mention is not a pointer.
Exit codes:
0 Adapter file passes all checks
1 One or more checks failed (empty file, no reference to AGENTS.md,
excessive duplication, or file too long)
2 Usage or input error — a bad, missing, or extra argument, an unknown
option, a path that is not a file, or a file that is not UTF-8. Nothing
was graded, so there is no FAIL line and no adapter edit to make: fix
the invocation or the file's encoding and re-run. Kept distinct from 1
because the skill's own closeout tells the agent to fix every non-zero
exit by editing the provider file, which for a mistyped flag edits the
wrong file forever.
3 A named input file exists but could not be read (permissions, a
directory swapped in mid-run, I/O error). Also not a FAIL: nothing was
graded and the adapter's contents are unknown, so editing it is
guesswork. Fix the file's readability and re-run.
EOF
}
NO_IMPORT_SYNTAX=0
MAX_LINES=60
ARGS=()
END_OF_OPTS=0
require_int() {
# $1 = the value to validate
if [[ ! "$1" =~ ^[0-9]+$ ]]; then
echo "Error: --max-lines expects a non-negative integer, got '$1'." >&2
exit 2
fi
}
while [[ $# -gt 0 ]]; do
if [[ $END_OF_OPTS -eq 1 ]]; then
ARGS+=("$1")
shift
continue
fi
case "$1" in
--)
END_OF_OPTS=1
shift
;;
--help|-h)
usage
exit 0
;;
--no-import-syntax)
NO_IMPORT_SYNTAX=1
shift
;;
--no-import-syntax=*)
echo "Error: --no-import-syntax is a flag and takes no value (got '$1')." >&2
exit 2
;;
--max-lines)
if [[ $# -lt 2 ]]; then
echo "Error: --max-lines requires a value (a non-negative integer)." >&2
exit 2
fi
MAX_LINES="$2"
require_int "$MAX_LINES"
shift 2
;;
--max-lines=*)
MAX_LINES="${1#--max-lines=}"
if [[ -z "$MAX_LINES" ]]; then
echo "Error: --max-lines requires a value (a non-negative integer)." >&2
exit 2
fi
require_int "$MAX_LINES"
shift
;;
-*)
# Reported as an unknown option rather than falling through to the
# positional bucket, where it used to surface as "'--bogus' is not a
# file" — the right exit code attached to a diagnostic that sends the
# reader looking for a path they never typed.
echo "Error: unknown option '$1'." >&2
echo "" >&2
usage >&2
exit 2
;;
*)
ARGS+=("$1")
shift
;;
esac
done
if [[ ${#ARGS[@]} -lt 2 ]]; then
echo "Error: adapter-file and agents-md-file are required." >&2
echo "" >&2
usage >&2
exit 2
fi
if [[ ${#ARGS[@]} -gt 2 ]]; then
echo "Error: expected exactly 2 positional arguments (adapter-file and agents-md-file), got ${#ARGS[@]}: ${ARGS[*]}." >&2
echo "" >&2
usage >&2
exit 2
fi
python3 -u - "${ARGS[0]}" "${ARGS[1]}" "$NO_IMPORT_SYNTAX" "$MAX_LINES" <<'PYTHON'
import sys
import os
import re
adapter_path, agents_md_path, no_import_syntax, max_lines = sys.argv[1:5]
no_import_syntax = no_import_syntax == "1"
max_lines = int(max_lines)
EXIT_FAIL = 1
EXIT_USAGE = 2
EXIT_UNREADABLE = 3
if not os.path.isfile(adapter_path):
print(f"Error: '{adapter_path}' is not a file.", file=sys.stderr)
sys.exit(EXIT_USAGE)
if not os.path.isfile(agents_md_path):
print(f"Error: '{agents_md_path}' is not a file.", file=sys.stderr)
sys.exit(EXIT_USAGE)
def read_text(path):
r"""File contents as text, UTF-8, every BOM stripped.
The BOM strip is not cosmetic. IMPORT_RE anchors on `^ {0,3}@`, and a BOM
is not whitespace in Python, so a CLAUDE.md saved by an editor that emits
one had its first line — the `@AGENTS.md` import, which is the whole
adapter — silently treated as prose. The check then said "no reference to
AGENTS.md" and told the author to add the line already sitting in front of
them. Same class of silent BOM miss recorded in scripts/skill-size-check.sh;
strip it at the reader so no later check has to know about it.
Every U+FEFF goes, not just one at offset 0. Stripping exactly the first
one left the mirror-image false FAIL for a doubled BOM (two concatenated
files, or a tool that re-adds one) and for a BOM mid-file at the head of
the import line. U+FEFF has no meaning as a character in a markdown
instruction file, so removing all of them cannot lose signal.
Decoding is strict, not errors="replace". Replacement mangles the file and
the checks then grade the mangling: a UTF-16 adapter whose first line is
`@AGENTS.md` decoded to interleaved NULs and failed as "no reference",
which is a true FAIL for a false reason and points the fix at the wrong
thing. But strict UTF-8 alone does not catch it — BOM-less UTF-16LE/BE and
UTF-32LE are *valid* UTF-8, because NUL is a legal code point, so they
decoded clean and produced exactly that false diagnosis anyway. The NUL
byte is the complete signal and is checked first: no plausible markdown
adapter contains one, and every UTF-16/32 encoding of ASCII is full of
them. A file this gate cannot read gets an encoding diagnostic and exit 2,
the same policy the ADR-0020 validators' read_text() uses.
A file that exists but cannot be read at all is neither a pass nor a FAIL —
nothing was graded — so it exits 3 rather than 1. Exit 1 sends the skill's
closeout into "fix the FAIL by editing the provider file", which for a file
it cannot open is an instruction to edit blind.
"""
try:
with open(path, "rb") as fh:
raw = fh.read()
except OSError as exc:
print(f"Error: '{path}' exists but could not be read ({exc.strerror}). "
"Nothing was checked — fix whatever is blocking the read "
"(permissions, ownership, the underlying device) and re-run; do "
"not edit the adapter on the strength of this.", file=sys.stderr)
sys.exit(EXIT_UNREADABLE)
if b"\x00" in raw:
print(f"Error: '{path}' is not valid UTF-8 — it contains NUL bytes, so "
"it is almost certainly UTF-16 or UTF-32 (with or without a BOM). "
"Re-save it as UTF-8; this check does not guess at other "
"encodings.", file=sys.stderr)
sys.exit(EXIT_USAGE)
try:
text = raw.decode("utf-8")
except UnicodeDecodeError as exc:
print(f"Error: '{path}' is not valid UTF-8 ({exc.reason} at byte "
f"{exc.start}) — re-save it as UTF-8; this check does not guess "
"at other encodings.", file=sys.stderr)
sys.exit(EXIT_USAGE)
return text.replace("\ufeff", "")
adapter_content = read_text(adapter_path)
agents_md_content = read_text(agents_md_path)
adapter_dir = os.path.dirname(os.path.abspath(adapter_path))
has_fail = False
if not adapter_content.strip():
print(f"FAIL Adapter file is empty — {adapter_path}")
print(" Why: An empty adapter carries no reference to AGENTS.md and no provider-specific content.")
print(" Fix: Add at least an import (or text pointer) to AGENTS.md.")
print()
sys.exit(EXIT_FAIL)
# --- Inert regions -----------------------------------------------------------
#
# A reference only counts where something would actually resolve it. Fenced
# code blocks, indented code blocks and HTML comments are shown to the reader
# (or hidden from them) as literal text; Claude Code resolves an @import in
# none of them. Without this, a ```-fenced `@AGENTS.md` — the exact
# copy-the-example-into-the-file mistake this gate exists to catch — exited 0
# with the adapter deferring to nothing.
#
# Indented code blocks are handled by IMPORT_RE's `^ {0,3}` instead of by the
# mask: four leading spaces is what opens an indented code block in CommonMark,
# so an import has to sit within three. The mask deliberately does not apply
# that rule to prose pointers, where four-space indentation is ordinary list
# continuation rather than code.
FENCE_RE = re.compile(r'^( {0,3})(`{3,}|~{3,})(.*)$')
COMMENT_RE = re.compile(r'<!--.*?(?:-->|\Z)', re.DOTALL)
def line_offsets(text):
"""[(char offset, line without its terminator)] over `text`."""
out = []
off = 0
for raw in text.splitlines(keepends=True):
out.append((off, raw.rstrip("\r\n")))
off += len(raw)
return out
def build_inert_mask(text, offsets):
"""Per-character flags: 1 where a reference would never be resolved."""
mask = bytearray(len(text))
fence = None # (fence char, opening run length)
for start, line in offsets:
m = FENCE_RE.match(line)
if fence is None:
if m:
fence = (m.group(2)[0], len(m.group(2)))
for i in range(start, start + len(line)):
mask[i] = 1
continue
for i in range(start, start + len(line)):
mask[i] = 1
if (m and m.group(2)[0] == fence[0]
and len(m.group(2)) >= fence[1]
and not m.group(3).strip()):
fence = None
for m in COMMENT_RE.finditer(text):
if m.start() < len(mask) and mask[m.start()]:
continue # a literal "<!--" printed inside a fence opens nothing
for i in range(m.start(), min(m.end(), len(mask))):
mask[i] = 1
return mask
# --- Reference shapes --------------------------------------------------------
#
# `\S*AGENTS\.md` had no path-separator boundary, so `@NOTAGENTS.md` and
# `@zzzAGENTS.md` counted as imports of AGENTS.md. The matched path must end in
# AGENTS.md as a whole segment.
IMPORT_RE = re.compile(r'^ {0,3}@(?P<path>\S+?)\s*$')
# A mention in prose: an optional relative path, then AGENTS.md, with no
# identifier character glued to the front (so NOTAGENTS.md does not match) and
# nothing glued to the back.
MENTION_RE = re.compile(r'(?<![0-9A-Za-z_.\-/])((?:[\w.\-~]+/)*AGENTS\.md)(?![0-9A-Za-z])')
# A pointer has to read as a pointer. `"AGENTS.md" in ln` passed
# "Do NOT read AGENTS.md; it is obsolete." and "We deleted AGENTS.md last
# year." — both of which point the reader away from the file. Require a
# deference cue in the naming sentence, and reject a negated one.
DIRECTIVE_RE = re.compile(
r'\b(see|read|refer|refers|referring|consult|consults|follow|follows|'
r'defer|defers|deferring|described|documented|documents|covered|covers|'
r'found|listed|specified|defined|governed|per|use|uses|using|apply|obey|'
r'start|check|live|lives|contains|holds|carries|inherit|inherits|import|'
r'imports|conventions|instructions|guidelines|guidance|rules|standards|'
r'reference|setup)\b', re.I)
NEGATION_RE = re.compile(
r"(\bnot\b|n't\b|\bnever\b|\bno longer\b|\bdeleted\b|\bremoved\b|"
r"\bobsolete\b|\bdeprecated\b|\bignore\b|\bignores\b|\bignoring\b|"
r"\bdisregard\b|\bsuperseded\b|\bgone\b|\bunused\b|\bstale\b)", re.I)
SENTENCE_SPLIT_RE = re.compile(r'(?<=[.;:!?])\s+')
def sentence_around(line, index):
"""(sentence of `line` containing character `index`, its start offset)."""
bounds = [0]
for m in SENTENCE_SPLIT_RE.finditer(line):
bounds.append(m.end())
bounds.append(len(line) + 1)
for i in range(len(bounds) - 1):
if bounds[i] <= index < bounds[i + 1]:
return line[bounds[i]:bounds[i + 1]], bounds[i]
return line, 0
def reads_as_pointer(line, match):
"""Does the sentence naming AGENTS.md actually point the reader at it?
The matched path is blanked out before the cues are applied. It is a
filename, not prose, and leaving it in let its own characters vote: the
perfectly ordinary `docs/does/not/exist/AGENTS.md` tripped the negation
cue on the `not` path segment, so a pointer got rejected for the wrong
reason and the near-miss line then reported the wrong diagnosis.
"""
sentence, sentence_start = sentence_around(line, match.start())
rel_start = match.start() - sentence_start
rel_end = match.end() - sentence_start
probe = sentence[:rel_start] + " AGENTS.md " + sentence[rel_end:]
if NEGATION_RE.search(probe):
return False
return bool(DIRECTIVE_RE.search(probe))
def resolve(raw_path):
"""An import/pointer path resolved the way the provider would resolve it."""
p = os.path.expanduser(raw_path)
if not os.path.isabs(p):
p = os.path.join(adapter_dir, p)
return os.path.normpath(p)
def target_problem(raw_path):
"""None if `raw_path` names a real, non-empty file; else why not."""
resolved = resolve(raw_path)
if not os.path.isfile(resolved):
return f"'{raw_path}' resolves to {resolved}, which does not exist"
try:
if os.path.getsize(resolved) == 0:
return f"'{raw_path}' resolves to {resolved}, which is empty"
with open(resolved, "rb") as fh:
if not fh.read().strip():
return f"'{raw_path}' resolves to {resolved}, which is blank"
except OSError as exc:
return f"'{raw_path}' resolves to {resolved}, which cannot be read ({exc.strerror})"
return None
def names_agents_md(path):
return path == "AGENTS.md" or path.endswith("/AGENTS.md")
offsets = line_offsets(adapter_content)
lines = [line for _, line in offsets]
mask = build_inert_mask(adapter_content, offsets)
def is_inert(abs_index):
return abs_index < len(mask) and bool(mask[abs_index])
# Lines shaped like an @AGENTS.md import, whether or not the target resolves.
# Used to exclude them from the duplication denominator and from the prose
# pointer scan, both of which only care about the shape.
import_shaped_lines = set()
# (line, raw path) for every import whose target actually resolves.
live_imports = []
# Diagnostics for imports that are the right shape but resolve to nothing.
dead_imports = []
# Imports that exist only inside a fence or an HTML comment.
inert_imports = []
for start, line in offsets:
m = IMPORT_RE.match(line)
if not m or not names_agents_md(m.group("path")):
continue
at_index = start + line.index("@")
if is_inert(at_index):
inert_imports.append(line.strip())
continue
import_shaped_lines.add(line)
problem = target_problem(m.group("path"))
if problem:
dead_imports.append(problem)
else:
live_imports.append(line)
live_pointers = []
dead_pointers = []
inert_pointers = []
mention_only = []
for start, line in offsets:
if line in import_shaped_lines:
continue
for m in MENTION_RE.finditer(line):
if is_inert(start + m.start()):
inert_pointers.append(line.strip())
continue
if not reads_as_pointer(line, m):
mention_only.append(sentence_around(line, m.start())[0].strip())
continue
problem = target_problem(m.group(1))
if problem:
dead_pointers.append(problem)
else:
live_pointers.append(line)
if no_import_syntax:
has_reference = bool(live_pointers)
near_misses = dead_pointers + [f"{d} (inside a code fence or HTML comment)" for d in inert_pointers]
near_misses += [f"'{s}' names AGENTS.md but does not point at it" for s in mention_only]
else:
has_reference = bool(live_imports)
near_misses = dead_imports + [f"'{d}' is inside a code fence or HTML comment, where no import is resolved" for d in inert_imports]
if not has_reference:
has_fail = True
print(f"FAIL Adapter has no reference to AGENTS.md — {adapter_path}")
if no_import_syntax:
print(" Why: This provider resolves no cross-file import, so the adapter must point at AGENTS.md in prose; an `@AGENTS.md` line here is inert text. The pointer has to read as a pointer and name a file that is really there — a bare or negated mention (\"we deleted AGENTS.md\") defers nothing, and neither does a mention buried in a code fence or an HTML comment.")
print(" Fix: Add a sentence like \"See AGENTS.md at the repo root for shared conventions.\", outside any fence, naming a path that exists relative to this file.")
else:
print(" Why: A thin adapter must import AGENTS.md with an `@AGENTS.md` line of its own, indented no more than three spaces, and the path must resolve to a real non-empty file. Naming the file mid-sentence or inside backticks is prose this check will not credit; putting the line inside a ``` fence, an indented code block, or an HTML comment is worse, because nothing resolves it and it looks right.")
print(" Fix: Put `@AGENTS.md` (or the equivalent relative path) alone on its own line at the top level of the file, or pass --no-import-syntax if this provider resolves no imports.")
for miss in near_misses:
print(f" Near miss: {miss}")
print()
# --- Duplication check ---
non_import_lines = [ln for ln in lines if ln not in import_shaped_lines]
adapter_lines = [ln.strip() for ln in non_import_lines if ln.strip()]
agents_lines = {ln.strip() for ln in agents_md_content.splitlines() if ln.strip()}
if adapter_lines:
overlap = sum(1 for ln in adapter_lines if ln in agents_lines)
ratio = overlap / len(adapter_lines)
if ratio > 0.3:
has_fail = True
print(f"FAIL Adapter duplicates AGENTS.md content — {adapter_path}")
print(f" Why: {ratio:.0%} of the adapter's non-import lines already appear verbatim in AGENTS.md. A thin adapter should import shared content, not restate it.")
print(" Fix: Remove the duplicated lines and rely on the AGENTS.md import (or pointer) instead.")
print()
# --- Size check ---
non_blank_count = len([ln for ln in lines if ln.strip()])
if non_blank_count > max_lines:
has_fail = True
print(f"FAIL Adapter is not thin — {adapter_path}")
print(f" Why: {non_blank_count} non-blank lines exceeds the {max_lines}-line threshold for a thin adapter.")
print(" Fix: Delete the lines already covered by AGENTS.md; keep only genuinely provider-specific additions here.")
print()
if has_fail:
sys.exit(EXIT_FAIL)
sys.exit(0)
PYTHON