agent-context-md 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,317 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent-context-md
3
+ Version: 0.1.0
4
+ Summary: Generate short, useful AGENTS.md files without repeating what the repo already says.
5
+ Author: Osmane B.
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/osmaneb23/agents-md
8
+ Project-URL: Issues, https://github.com/osmaneb23/agents-md/issues
9
+ Keywords: agents.md,ai,cli,codex,claude,developer-tools
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Software Development :: Documentation
18
+ Classifier: Topic :: Software Development :: Quality Assurance
19
+ Requires-Python: >=3.11
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Provides-Extra: anthropic
23
+ Requires-Dist: anthropic>=0.76; extra == "anthropic"
24
+ Provides-Extra: openai
25
+ Requires-Dist: openai>=2.9; extra == "openai"
26
+ Provides-Extra: gemini
27
+ Requires-Dist: google-genai>=1.52; extra == "gemini"
28
+ Provides-Extra: dev
29
+ Requires-Dist: build>=1.3; extra == "dev"
30
+ Requires-Dist: pytest>=9.0; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # agents-md
34
+
35
+ Generate `AGENTS.md` context files that actually help AI coding agents.
36
+
37
+ [![CI](https://github.com/osmaneb23/agents-md/actions/workflows/ci.yml/badge.svg)](https://github.com/osmaneb23/agents-md/actions)
38
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)](pyproject.toml)
39
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
40
+
41
+ ![agents-md terminal demo](docs/demo.svg)
42
+
43
+ *Demo runs on a JS/TS repo. Simpler repos generate shorter files.*
44
+
45
+ ---
46
+
47
+ ETH Zurich [tested AI coding agents](https://arxiv.org/abs/2602.11988) across 8 benchmarks with auto-generated context files, hand-written files, and nothing. Auto-generated files made performance worse in 5 of 8 cases. Inference cost jumped 20-23%. Tasks took more steps.
48
+
49
+ The cause: generators write what agents can already read. Your README, your folder structure, your lint rules — the agent figures all of this out on its own. Putting it in AGENTS.md means reading it again on every task and paying for it each time.
50
+
51
+ `agents-md` reads your existing docs before writing anything. Everything the agent can discover on its own gets filtered out. What's left — exact commands with real flags, conventions the agent would get wrong, hard limits — is what ends up in the file.
52
+
53
+ This repo's own AGENTS.md was generated by `agents-md`.
54
+
55
+ ---
56
+
57
+ ## Contents
58
+
59
+ - [Install](#install)
60
+ - [Usage](#usage)
61
+ - [Sample output](#sample-output)
62
+ - [How deduplication works](#how-deduplication-works)
63
+ - [Quality scoring](#quality-scoring)
64
+ - [GitHub Action](#github-action)
65
+ - [What gets detected](#what-gets-detected)
66
+ - [Alternatives](#alternatives)
67
+ - [Development](#development)
68
+
69
+ ---
70
+
71
+ ## Install
72
+
73
+ ```bash
74
+ # Until the first PyPI release is live:
75
+ python -m pip install "git+https://github.com/osmaneb23/agents-md.git"
76
+
77
+ # After PyPI publication:
78
+ pip install agent-context-md
79
+ ```
80
+
81
+ Zero runtime dependencies. No Node.js, no Docker.
82
+
83
+ LLM provider SDKs are optional extras — the tool works fully offline without them. From a source checkout:
84
+
85
+ ```bash
86
+ python -m pip install -e .[anthropic]
87
+ python -m pip install -e .[openai]
88
+ python -m pip install -e .[gemini]
89
+ ```
90
+
91
+ After PyPI publication, use `pip install agent-context-md[anthropic]` or run it with uv:
92
+
93
+ ```bash
94
+ uvx --from agent-context-md agents-md init
95
+ ```
96
+
97
+ ---
98
+
99
+ ## Usage
100
+
101
+ **Generate:**
102
+
103
+ ```bash
104
+ # Static analysis only, no API key needed
105
+ agents-md init --no-llm
106
+
107
+ # With LLM synthesis (picks up key from env)
108
+ ANTHROPIC_API_KEY=sk-... agents-md init
109
+ OPENAI_API_KEY=sk-... agents-md init
110
+ GEMINI_API_KEY=... agents-md init
111
+
112
+ # Explicit provider + model
113
+ agents-md init --provider anthropic --model <model-id>
114
+
115
+ # Preview without writing anything
116
+ agents-md init --no-llm --dry-run --verbose
117
+
118
+ # Append managed sections to a hand-written file
119
+ agents-md init --merge
120
+ ```
121
+
122
+ **Lint** — works on any AGENTS.md, including hand-written ones:
123
+
124
+ ```bash
125
+ agents-md lint # score ./AGENTS.md
126
+ agents-md lint path/to/AGENTS.md # specific file
127
+ agents-md lint --check --threshold 70 # exit 1 if score < 70
128
+ agents-md lint --fix # remove duplicate and style-rule lines
129
+ agents-md lint --json # machine-readable output
130
+ ```
131
+
132
+ **Keep it current:**
133
+
134
+ ```bash
135
+ agents-md update # refresh managed sections, leave your notes alone
136
+ agents-md diff # show what changed in the repo since last generation
137
+ ```
138
+
139
+ ---
140
+
141
+ ## Sample output
142
+
143
+ `agents-md init --no-llm` on a Next.js + TypeScript repo:
144
+
145
+ ```markdown
146
+ ## Stack
147
+ - CI: GitHub Actions
148
+ - Framework: Next.js 15.3
149
+ - Language: TypeScript (strict mode)
150
+ - Package Manager: pnpm 10.0.0
151
+ - Test Runner: vitest 3.0.0
152
+
153
+ ## Commands
154
+ - install: `pnpm install`
155
+ - run: `pnpm dev`
156
+ - build: `pnpm build`
157
+ - test: `pnpm test`
158
+ - lint: `pnpm lint`
159
+
160
+ ## Testing
161
+ - Full suite: `pnpm test`
162
+ - Single test: `pnpm vitest run src/auth/login.test.ts -t "should reject expired tokens"`
163
+ - Prefer the narrowest test while iterating. Run the full suite before handing off.
164
+
165
+ ## Boundaries
166
+ ### Always Do
167
+ - Run the narrowest relevant test before handing off a code change.
168
+ ### Ask First
169
+ - Ask before running `pnpm db:migrate` — it touches migrations.
170
+ - Ask before deleting files, rewriting history, or changing release metadata.
171
+ ### Never Do
172
+ - Never commit secrets, tokens, or `.env` files.
173
+ - Never overwrite a hand-written AGENTS.md without `--force` or explicit confirmation.
174
+ ```
175
+
176
+ Sections are wrapped in `<!-- agents-md:start/end:section-name -->` markers. `agents-md update` uses them to refresh individual sections without touching anything you added by hand.
177
+
178
+ ---
179
+
180
+ ## How deduplication works
181
+
182
+ Before writing anything, the tool reads every Markdown file in your project root and `docs/`. It extracts facts from them — commands, framework mentions, structural notes. Then for each candidate line from the extractors, it asks: does this add anything the agent can't get from those docs?
183
+
184
+ ```
185
+ README says: "We use pnpm. Run `pnpm install` to get started."
186
+ Extractor: install: pnpm install
187
+
188
+ → Removed. The agent can read the README.
189
+
190
+ README says: "Run the tests before pushing."
191
+ Extractor: single test: pytest tests/test_auth.py::test_login -xvs
192
+
193
+ → Kept. The README is vague. The exact command with flags is new.
194
+ ```
195
+
196
+ Boundaries and security lines are always kept, even when they overlap with the README.
197
+
198
+ Pass `--verbose` to see the full list of what was removed and why.
199
+
200
+ ---
201
+
202
+ ## Quality scoring
203
+
204
+ `agents-md lint` scores any AGENTS.md out of 100 and tells you exactly what to fix.
205
+
206
+ | Criterion | Points |
207
+ |---|---|
208
+ | Commands section with 2+ exact commands | 10 |
209
+ | Commands include real flags (`-x`, `--watch`, etc.) | 15 |
210
+ | Single-test command targeting one file or function | 10 |
211
+ | Three-tier boundaries (Always / Ask First / Never) | 20 |
212
+ | Dedicated testing section | 10 |
213
+ | File under 150 lines | 15 |
214
+ | No README duplication | 15 |
215
+ | No linter-owned style rules | 5 |
216
+
217
+ Score guide:
218
+
219
+ - **85-100** — This file will improve agent performance.
220
+ - **65-84** — A few improvements would help.
221
+ - **45-64** — Key sections are missing or there's redundant content.
222
+ - **0-44** — This file is likely slowing agent sessions down.
223
+
224
+ ---
225
+
226
+ ## GitHub Action
227
+
228
+ Fail PRs when the score drops below a threshold:
229
+
230
+ ```yaml
231
+ - uses: actions/checkout@v6
232
+ - uses: actions/setup-python@v6
233
+ with:
234
+ python-version: "3.13"
235
+ - uses: osmaneb23/agents-md/.github/actions/agents-md-lint@main
236
+ with:
237
+ path: AGENTS.md
238
+ threshold: "70"
239
+ ```
240
+
241
+ Pin to a release tag once you cut the first release.
242
+
243
+ ---
244
+
245
+ ## What gets detected
246
+
247
+ <details>
248
+ <summary><strong>Commands</strong></summary>
249
+
250
+ Scripts and tasks from `package.json`, `Makefile`, `pyproject.toml` (taskipy, poe), `Justfile`, `Taskfile.yml`. Single-test commands are inferred for pytest, unittest, Jest, Vitest, Mocha, Cargo, and Go.
251
+
252
+ </details>
253
+
254
+ <details>
255
+ <summary><strong>Stack</strong></summary>
256
+
257
+ Package manager detected from lock files, never guessed. Framework, language, TypeScript strict mode (from tsconfig), runtime, test runner, linter, type checker, CI system.
258
+
259
+ </details>
260
+
261
+ <details>
262
+ <summary><strong>Conventions</strong></summary>
263
+
264
+ `src/` layout, test naming patterns, TypeScript path aliases, named-export-only modules, barrel files with their import alias, `Result<T,E>` error-as-value patterns, centralized HTTP wrappers, catch blocks that intentionally return fallback values, `.env.example` variables, test fixture and factory directories. Only things an agent would plausibly get wrong on the first attempt.
265
+
266
+ </details>
267
+
268
+ <details>
269
+ <summary><strong>Fingerprint</strong></summary>
270
+
271
+ SHA-256 hashes of key manifests stored in a comment at the bottom of the file. `agents-md diff` compares them against the current state and tells you whether an update is worth running.
272
+
273
+ </details>
274
+
275
+ Supported: **Python**, **JavaScript/TypeScript**, **Go**, **Rust**.
276
+
277
+ ---
278
+
279
+ ## Alternatives
280
+
281
+ | Tool | What it does | Where it falls short |
282
+ |---|---|---|
283
+ | `agents-init` (npm) | Sets up AGENTS.md + MCP config + subagents | No dedup filter. Generates the kind of bloated file the ETH study warns against. |
284
+ | `GenerateAgents.md` (PyPI) | DSPy-based generation, any model | DSPy is a heavy dependency. No dedup. |
285
+ | `AGENTS.md_generator` (Python) | Safe-by-default skeleton | Intentionally minimal. You still fill it in manually. |
286
+ | Hand-written | Full control | Drifts with the codebase. No quality feedback. |
287
+
288
+ ---
289
+
290
+ ## Design decisions
291
+
292
+ - **Zero runtime dependencies.** The core package installs in seconds. LLM SDKs are opt-in extras.
293
+ - **Non-destructive updates.** `agents-md update` only touches content inside managed markers. `lint --fix` creates a `.bak` before writing. `init` prompts before overwriting.
294
+ - **No guessing.** If the package manager can't be determined from lock files, it's left blank. A wrong command is worse than a missing one.
295
+ - **Short over padded.** The LLM synthesis prompt explicitly tells the model to refuse to pad. A 30-line file beats a 150-line one if the repo is simple.
296
+ - **No Node.js required.** Python only, works anywhere Python runs.
297
+
298
+ ---
299
+
300
+ ## Development
301
+
302
+ The project's own [AGENTS.md](AGENTS.md) has the authoritative commands, conventions, and boundaries. Check it before changing code or opening a PR.
303
+
304
+ Before changing scoring weights, deduplication rules, or managed marker formats, open an issue. These are product decisions, not implementation details.
305
+
306
+ Releases go through PyPI Trusted Publishing via `.github/workflows/publish.yml`. To publish: set up a pending publisher for project `agent-context-md`, repository `osmaneb23/agents-md`, workflow `publish.yml`, environment `pypi`, then run the publish workflow.
307
+
308
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for PR expectations.
309
+
310
+ ---
311
+
312
+ ## Sources
313
+
314
+ - ETH Zurich study: [arxiv.org/abs/2602.11988](https://arxiv.org/abs/2602.11988)
315
+ - AGENTS.md open format: [github.com/agentsmd/agents.md](https://github.com/agentsmd/agents.md)
316
+ - GitHub's analysis of 2,500+ AGENTS.md files: [github.blog](https://github.blog/ai-and-ml/github-copilot/how-to-write-a-great-agents-md-lessons-from-over-2500-repositories/)
317
+ - Augment Code guide: [augmentcode.com/guides/how-to-build-agents-md](https://www.augmentcode.com/guides/how-to-build-agents-md)
@@ -0,0 +1,16 @@
1
+ agent_context_md-0.1.0.dist-info/licenses/LICENSE,sha256=jbvVU3M4way6up9Qw6caHhsZbNLTfm8kbOHgvcxCDw8,1066
2
+ agents_md/__init__.py,sha256=P1GcRsT9UCVBKj2k4HpeqKTxV-WDUhmQ4hh0js1FTXc,48
3
+ agents_md/__main__.py,sha256=MHKZ_ae3fSLGTLUUMOx15fWdeOnJSHhq-zslRP5F5Lc,79
4
+ agents_md/cli.py,sha256=S2TnauY14CKKHJtp7-4p-waVKKAEiINU1-XP7UjlSvQ,11921
5
+ agents_md/dedup.py,sha256=R-SlWf6nS3g_5kPKVxT6Ihg9KdbAa6nV8TjE4pPVs70,2359
6
+ agents_md/fingerprint.py,sha256=CJBrDW_tH-55DClAib-jbgBxgF5AeHoNoghM9544D_4,2431
7
+ agents_md/generator.py,sha256=4IarPJicFAoTiCQZQaq6gqVQy93j1ZP1wtcwd6QdcFk,7247
8
+ agents_md/llm.py,sha256=NWD4N58rrMu_1KqN3cQOMuzs6OYnLURtiNeakZi6QWA,5111
9
+ agents_md/quality.py,sha256=fMJ4q663CJClpSuK8ftjpImO6PZ6H78aLc55WR94e-o,9115
10
+ agents_md/scanner.py,sha256=I396vYn2yOgVgdFZW5WD9-mjyXPmsNK4F9e08o9u5C4,30699
11
+ agents_md/types.py,sha256=t9Kk1rys9wO_-RLcmGLO_TRPo3oZ2b4er9j-nL3ybaE,1275
12
+ agent_context_md-0.1.0.dist-info/METADATA,sha256=edmqMGgMgbc2A6rjeQck8nyJuJnAlpysilvHBL1s4cs,11419
13
+ agent_context_md-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
14
+ agent_context_md-0.1.0.dist-info/entry_points.txt,sha256=HpHOJY8cLzsepWtKcyQxYGb0T-nW9nxDea9FMLE4vf4,49
15
+ agent_context_md-0.1.0.dist-info/top_level.txt,sha256=1Z2RjMz96fTECkGK-CK-4h1PTGGadOllGbEQFVZz7QU,10
16
+ agent_context_md-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ agents-md = agents_md.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Osmane B.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ agents_md
agents_md/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """agents-md package."""
2
+
3
+ __version__ = "0.1.0"
agents_md/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
agents_md/cli.py ADDED
@@ -0,0 +1,276 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from . import __version__
8
+ from .fingerprint import compare_fingerprints, extract_fingerprint, fingerprint_repo
9
+ from .generator import has_managed_sections, line_count, render_document, render_sections, replace_managed_sections
10
+ from .llm import LlmError, detect_provider, missing_key_message, synthesize_with_llm
11
+ from .quality import apply_fix, format_human, format_json, lint_file
12
+ from .scanner import scan_repo
13
+
14
+
15
+ def main(argv: list[str] | None = None) -> int:
16
+ parser = build_parser()
17
+ args = parser.parse_args(argv)
18
+ if not hasattr(args, "handler"):
19
+ parser.print_help()
20
+ return 0
21
+ try:
22
+ return args.handler(args)
23
+ except KeyboardInterrupt:
24
+ print("Interrupted.", file=sys.stderr)
25
+ return 130
26
+
27
+
28
+ def build_parser() -> argparse.ArgumentParser:
29
+ parser = argparse.ArgumentParser(prog="agents-md", description="Generate and lint focused AGENTS.md files.")
30
+ parser.add_argument("--version", action="version", version=f"agents-md {__version__}")
31
+ sub = parser.add_subparsers(dest="command")
32
+
33
+ init = sub.add_parser("init", help="Analyze the current repo and generate AGENTS.md.")
34
+ init.add_argument("--no-llm", action="store_true", help="Generate from static extractors only.")
35
+ init.add_argument("--provider", choices=["anthropic", "openai", "ollama", "gemini"], help="LLM provider for synthesis.")
36
+ init.add_argument("--model", help="Override the provider default model.")
37
+ init.add_argument("--output", default="AGENTS.md", help="Output filename.")
38
+ init.add_argument("--no-symlink", action="store_true", help="Do not create CLAUDE.md symlink.")
39
+ init.add_argument("--dry-run", action="store_true", help="Print generated content without writing files.")
40
+ init.add_argument("--force", action="store_true", help="Overwrite existing output without prompting.")
41
+ init.add_argument("--merge", action="store_true", help="Append managed sections to an existing hand-written file.")
42
+ init.add_argument("--no-dedup", action="store_true", help="Skip README/docs deduplication.")
43
+ init.add_argument("--verbose", action="store_true", help="Print scanner diagnostics.")
44
+ init.set_defaults(handler=cmd_init)
45
+
46
+ update = sub.add_parser("update", help="Refresh managed sections of an existing AGENTS.md.")
47
+ update.add_argument("path", nargs="?", default="AGENTS.md")
48
+ update.add_argument("--no-llm", action="store_true", help="Do not call an LLM.")
49
+ update.add_argument("--provider", choices=["anthropic", "openai", "ollama", "gemini"], help="LLM provider for synthesis.")
50
+ update.add_argument("--model", help="Override the provider default model.")
51
+ update.add_argument("--no-dedup", action="store_true", help="Skip README/docs deduplication.")
52
+ update.add_argument("--init-fingerprint", action="store_true", help="Add a fingerprint when updating managed sections.")
53
+ update.set_defaults(handler=cmd_update)
54
+
55
+ lint = sub.add_parser("lint", help="Score an AGENTS.md file.")
56
+ lint.add_argument("path", nargs="?", default="AGENTS.md")
57
+ lint.add_argument("--check", action="store_true", help="Exit non-zero if score is below threshold.")
58
+ lint.add_argument("--threshold", type=int, default=60, help="Minimum score for --check.")
59
+ lint.add_argument("--fix", action="store_true", help="Remove duplicate/style-rule lines after confirmation.")
60
+ lint.add_argument("--yes", action="store_true", help="Confirm --fix without prompting.")
61
+ lint.add_argument("--json", action="store_true", help="Output JSON.")
62
+ lint.set_defaults(handler=cmd_lint)
63
+
64
+ diff = sub.add_parser("diff", help="Show repo changes since AGENTS.md was generated.")
65
+ diff.add_argument("path", nargs="?", default="AGENTS.md")
66
+ diff.set_defaults(handler=cmd_diff)
67
+
68
+ return parser
69
+
70
+
71
+ def cmd_init(args: argparse.Namespace) -> int:
72
+ root = Path.cwd()
73
+ output = root / args.output
74
+ existing = output.read_text(encoding="utf-8") if output.exists() else None
75
+ if existing is not None and args.merge and has_managed_sections(existing):
76
+ print(f"{output.name} already has managed sections. Run `agents-md update` instead.", file=sys.stderr)
77
+ return 1
78
+ if output.exists() and not args.force and not args.dry_run and not args.merge:
79
+ if not _confirm(f"{output.name} already exists. Overwrite it?"):
80
+ print("Aborted; existing file was not changed.", file=sys.stderr)
81
+ return 1
82
+
83
+ if args.merge and not args.no_llm:
84
+ print("LLM synthesis skipped in --merge mode to preserve hand-written content.", file=sys.stderr)
85
+ args.no_llm = True
86
+
87
+ if not args.no_llm:
88
+ provider = detect_provider(args.provider)
89
+ if not provider:
90
+ print(missing_key_message(args.provider), file=sys.stderr)
91
+ if _confirm("Run once in --no-llm mode instead?"):
92
+ args.no_llm = True
93
+ else:
94
+ return 2
95
+
96
+ _progress("Scanning repo")
97
+ scan = scan_repo(root, output_name=output.name)
98
+ if args.verbose:
99
+ _print_scan(scan)
100
+ if not args.no_dedup:
101
+ if scan.docs_read:
102
+ _progress(f"Deduplicating against {', '.join(scan.docs_read)}")
103
+ else:
104
+ _progress("Deduplicating against existing docs")
105
+ _progress("Rendering AGENTS.md")
106
+ content = render_document(scan, no_dedup=args.no_dedup)
107
+ if args.verbose:
108
+ _print_dedup(scan)
109
+ if existing is not None and args.merge:
110
+ content = existing.rstrip() + "\n\n" + _managed_body(content)
111
+ if not args.no_llm:
112
+ provider = detect_provider(args.provider)
113
+ if provider:
114
+ _progress(f"Synthesizing with {provider}")
115
+ try:
116
+ content = synthesize_with_llm(content, provider=provider, model=args.model)
117
+ except LlmError as exc:
118
+ print(f"LLM synthesis failed: {exc}", file=sys.stderr)
119
+ return 2
120
+ if not has_managed_sections(content):
121
+ print("LLM output omitted managed markers; refusing to write it.", file=sys.stderr)
122
+ return 2
123
+
124
+ if args.dry_run:
125
+ print(content, end="")
126
+ _summary(content, output, len(scan.dedup.removed), dry_run=True)
127
+ return 0
128
+
129
+ output.write_text(content, encoding="utf-8")
130
+ if output.name == "AGENTS.md" and not args.no_symlink:
131
+ _ensure_claude_symlink(root, output)
132
+ _summary(content, output, len(scan.dedup.removed), dry_run=False)
133
+ return 0
134
+
135
+
136
+ def cmd_update(args: argparse.Namespace) -> int:
137
+ path = Path(args.path)
138
+ if not path.is_file():
139
+ print(f"{path} does not exist. Run `agents-md init` first.", file=sys.stderr)
140
+ return 1
141
+ existing = path.read_text(encoding="utf-8")
142
+ if not has_managed_sections(existing):
143
+ print("No managed sections found. Run `agents-md init --merge` to add managed sections without overwriting your file.")
144
+ return 1
145
+
146
+ scan = scan_repo(path.parent.resolve(), output_name=path.name)
147
+ sections = render_sections(scan, no_dedup=args.no_dedup)
148
+ updated, changed = replace_managed_sections(existing, sections)
149
+ if args.init_fingerprint and "agents-md:fingerprint" not in updated:
150
+ from .fingerprint import encode_fingerprint
151
+
152
+ updated = updated.rstrip() + "\n" + encode_fingerprint(fingerprint_repo(path.parent.resolve())) + "\n"
153
+ changed.append("fingerprint")
154
+
155
+ if not args.no_llm:
156
+ provider = detect_provider(args.provider)
157
+ if provider:
158
+ try:
159
+ updated = synthesize_with_llm(updated, provider=provider, model=args.model)
160
+ except LlmError as exc:
161
+ print(f"LLM synthesis failed: {exc}", file=sys.stderr)
162
+ return 2
163
+ else:
164
+ print(f"{missing_key_message(args.provider)} Proceeding with static update.", file=sys.stderr)
165
+ path.write_text(updated, encoding="utf-8")
166
+ if changed:
167
+ print(f"Updated: {', '.join(changed)}.")
168
+ else:
169
+ print("No managed section changes detected.")
170
+ print("Preserved: content outside managed markers.")
171
+ return 0
172
+
173
+
174
+ def cmd_lint(args: argparse.Namespace) -> int:
175
+ path = Path(args.path)
176
+ if not path.is_file():
177
+ if args.check:
178
+ return 1
179
+ print(f"{path} does not exist.", file=sys.stderr)
180
+ return 1
181
+ result = lint_file(path)
182
+ if args.fix:
183
+ if not result.issues:
184
+ print("No auto-fixable issues detected.")
185
+ return 0
186
+ if not args.yes and not _confirm(f"Create {path.name}.bak and remove auto-fixable lines?"):
187
+ print("Aborted; file was not changed.", file=sys.stderr)
188
+ return 1
189
+ backup = apply_fix(path, result)
190
+ print(f"Fixed {path}; backup written to {backup}.")
191
+ return 0
192
+ if args.check:
193
+ return 0 if result.score >= args.threshold else 1
194
+ print(format_json(result) if args.json else format_human(result), end="")
195
+ return 0
196
+
197
+
198
+ def cmd_diff(args: argparse.Namespace) -> int:
199
+ path = Path(args.path)
200
+ if not path.is_file():
201
+ print(f"{path} does not exist.", file=sys.stderr)
202
+ return 1
203
+ old = extract_fingerprint(path.read_text(encoding="utf-8"))
204
+ if not old:
205
+ print("No fingerprint found. Run `agents-md init` or `agents-md update --init-fingerprint`.")
206
+ return 1
207
+ current = fingerprint_repo(path.parent.resolve())
208
+ diff = compare_fingerprints(old, current)
209
+ for label in ("added", "removed", "changed"):
210
+ values = diff[label]
211
+ if values:
212
+ print(f"{label}: {', '.join(values)}")
213
+ if not diff["added"] and not diff["removed"] and not diff["changed"]:
214
+ print("No relevant manifest/config changes detected.")
215
+ else:
216
+ print("Recommendation: run `agents-md update` to sync managed sections.")
217
+ return 0
218
+
219
+
220
+ def _confirm(message: str) -> bool:
221
+ if not sys.stdin.isatty():
222
+ return False
223
+ answer = input(f"{message} [y/N] ").strip().lower()
224
+ return answer in {"y", "yes"}
225
+
226
+
227
+ def _progress(message: str) -> None:
228
+ print(f"{message}...", file=sys.stderr)
229
+
230
+
231
+ def _summary(content: str, output: Path, removed: int, *, dry_run: bool) -> None:
232
+ result = None
233
+ if output.exists() and not dry_run:
234
+ result = lint_file(output)
235
+ score = f"{result.score}/100" if result else "not scored in dry-run"
236
+ action = "Would write" if dry_run else "Wrote"
237
+ print(f"{action} {output}: {line_count(content)} lines, quality {score}, dedup removed {removed} item(s).")
238
+
239
+
240
+ def _ensure_claude_symlink(root: Path, output: Path) -> None:
241
+ link = root / "CLAUDE.md"
242
+ if link.exists() or link.is_symlink():
243
+ if link.is_symlink() and link.resolve() == output.resolve():
244
+ return
245
+ print("CLAUDE.md exists and was left unchanged.", file=sys.stderr)
246
+ return
247
+ try:
248
+ link.symlink_to(output.name)
249
+ except OSError as exc:
250
+ print(f"Could not create CLAUDE.md symlink: {exc}", file=sys.stderr)
251
+
252
+
253
+ def _print_scan(scan) -> None:
254
+ print("Detected stack:", file=sys.stderr)
255
+ for fact in scan.stack:
256
+ print(f" - {fact.kind}: {fact.label()} ({fact.source})", file=sys.stderr)
257
+ print("Detected commands:", file=sys.stderr)
258
+ for command in scan.commands:
259
+ print(f" - {command.category}: {command.command} ({command.source})", file=sys.stderr)
260
+ if scan.docs_read:
261
+ print(f"Docs read for dedup: {', '.join(scan.docs_read)}", file=sys.stderr)
262
+
263
+
264
+ def _print_dedup(scan) -> None:
265
+ if scan.dedup.removed:
266
+ print("Dedup removed:", file=sys.stderr)
267
+ for item in scan.dedup.removed:
268
+ print(f" - {item}", file=sys.stderr)
269
+ else:
270
+ print("Dedup removed 0 item(s).", file=sys.stderr)
271
+
272
+
273
+ def _managed_body(content: str) -> str:
274
+ marker = "<!-- agents-md:start:"
275
+ start = content.find(marker)
276
+ return content[start:] if start >= 0 else content