Skip to content

Latest commit

 

History

History
185 lines (143 loc) · 19.8 KB

AGENTS.md

File metadata and controls

185 lines (143 loc) · 19.8 KB

AGENTS.md

This file provides guidance to agentic coding agents (Claude Code, etc. — CLAUDE.md is a symlink to it) when working with code in this repository. All code, comments, and commit messages generated by the agent must be in English. Only the discussion with the human can be in French (don't forget the accents !).

🏡 Context Markers

Emoji markers in the chat let the human see at a glance which rules are live and what state the work is in.

  • Every reply starts with 🏡 followed by a space. It proves this file is still in context: a reply without it tells the human the rules were lost (compaction, long session) and must be reloaded. Other markers stack after it, never replace it.
  • Re-read this file after a context compaction and at the end of a long task, and say ♻️ AGENTS.md re-read.
  • Every item of a summary or progress list starts with its marker (e.g. ✅ Committed the xml loader phase, 🧪 resolver tests pass).
  • question: prompts (or q:) get ❓: answer only, no file change, then ask what to do next.
Marker Meaning
🏡 Rules of this file active (mandatory reply starter)
♻️ This file re-read
❗️ Issue flagged proactively: bug, risk, rule conflict, blocker needing the human
❓ Question mode
📈 Progress on a multi-phase task, what is done and what is left
🧪 Build / test / lint result (say which tests ran, and whether it is green or red)
✅ Intermediate commit made
👀 Left for the human to review: uncommitted last step, TO_HUMAN: comments
📝 Suggested commit message for the uncommitted changes
🎓 Semantic anchor taught to the human (see below)

When a skill or a command of .agents/ is running, stack its marker after 🏡. A new skill or command gets its marker in a table here (none yet).

🎓 Semantic Anchors

A semantic anchor is the established name of a principle, pattern or practice (SLAP, Visitor, Golden Master, Test Double…): naming it is more precise than describing it, for the agent and for the human.

  • Teach the name the human does not use. When the human describes a well-known principle, pattern or practice at length without naming it (in a prompt, a spec, a review, a rule of this file), assume they may not know it and teach it, in a short 🎓 block at the end of the reply: the anchor name, who coined it, one sentence on what it is, how it applies to the case at hand, and at most two related anchors. Same when the human uses a name wrongly or approximately.
  • Only real anchors: an established, attributable name with a precise meaning. Never invent one, never stretch one to fit; a convention specific to this project is not an anchor, it stays a rule written in full here.
  • Once per concept per conversation, and never at the expense of the task at hand.

Critical Rules

  • NEVER bump handlebars past 6.4.4, nor swap serde_yaml 0.9.34 for a fork, without the human: they are pinned on purpose (comments in codegenr/Cargo.toml). handlebars keeps rewriting what a partial sees of its caller (6.0 to 6.4.1 lose @key in a partial called from an #each): partials_called_from_an_each_see_its_variables (render.rs) guards it, run it on any bump; serde_yaml 0.9 (libyaml) takes a UTF-8 BOM for a second document, json_from_string strips it first. Since handlebars 6, as in handlebars.js, a partial cannot read the context of its caller through ../: the caller gives it a hash parameter, {{> part required=../required}}.
  • NEVER add a new dependency to codegenr/Cargo.toml without asking the human.
  • NEVER clear/delete a failing test rather than fixing it. If stuck, ask the human.
  • Tests must pass on Linux, macOS and Windows (the CI matrix): an assertion on a path carries its cfg!(windows) expectation with \ separators (see relate_test in loaders/mod.rs, get_templates_from_directory_test in render.rs).
  • Agent assets are shared, in .agents/ (skills in .agents/skills/, one folder per skill; slash commands in .agents/commands/). Whatever the agent (Claude, Codex, …), read them, follow them, and improve them there. Tool-specific folders only hold symlinks into .agents/ (e.g. .claude/skills, .claude/commands) — never create real agent-specific folders or duplicate an asset elsewhere.

Essential Commands

Task Command
Build cargo build
Run all tests just test (cargo test --workspace: unit tests and doctests, a few seconds)
Run single test cargo test -p codegenr --lib -- <module>::tests::<test_name> --exact --nocapture
Run one doctest cargo test -p codegenr --doc -- helpers::strings::TrimCharHelper
nextest cargo nextest run skips the doctests, where most helpers are tested: follow it with cargo test --doc
Lint cargo clippy --workspace --all-targets (the editor runs clippy on save, all features; the CI fails on any warning, -- -D warnings)
Format cargo fmt
Dependencies cargo deny check (advisories, licenses, duplicates, sources; rules and accepted advisories in deny.toml)
Docs just doc (cargo doc --open)
Install the CLI just install (cargo install --path codegenr)
Run a generation cargo run -q -- file (reads codegenr.toml in the current dir), or cargo run -q -- gen -s <source> -o <output> -t <templates>…

Toolchain

Managed via mise.toml: just, jq, cargo-nextest, cargo-deny, bun and node; Rust stable with rustfmt and clippy via rust-toolchain.toml. Install tools with mise install. Bun is the JavaScript runtime and package manager; Node is there only for third-party tools that need it.

Run repository commands through an interactive shell so mise activates the project toolchain (e.g. zsh -lic 'just <recipe>'). A plain non-interactive shell may pick system tools instead of the mise ones.

Architecture

Crate Layout

A Cargo workspace with one crate, codegenr/: the library codegenr_lib (src/lib.rs) and the codegenr binary (src/bin/main.rs). The binary, the CLI parsing (opt.rs, clap derive) and --watch (watch.rs) sit behind the default bin feature, which also pulls anyhow, tracing-subscriber and notify. run_all_codegenr runs each section in two steps, resolve_section then render_section: --watch renders again a section when a .hbs or .rhai of its folders changes, and resolves it again first when a file its source read changes (AllowedSources records them, even when the resolution fails); a change of codegenr.toml restarts it all.

A codegenr.toml holds one section per generation (source, templates, output, custom_helpers, intermediate, global_parameters, allowed_sources, the Options struct of lib.rs); the gen subcommand builds a single section from the command line.

Pipeline: Load → Resolve → Render → Process

resolve_section then render_section (lib.rs) run one section through four steps, each its own module with its own thiserror enum, all gathered in errors::CodegenrError with #[from]. Those enums are large, hence the #[allow(clippy::result_large_err)] on the functions returning them.

  1. Load (loaders/): DocumentPath is a file or a URL (downloaded with blocking reqwest), turned into a serde_json::Value. The format is guessed from the extension, then json_from_string tries a fallback chain of loaders; graphql SDL, xml, csv and toml are all reshaped into JSON.
  2. Resolve (resolver.rs): every $ref (file.yaml#/path/to/obj, #/… in the same document) is replaced by the object it points to, recursively and across files, the paths related with DocumentPath::relate_from. The merged object gets x-fromRef (the original reference) and x-refName (its last segment); a $ref must point to an object. Every document read goes through AllowedSources::check, before the caches: a file under the current folder, the folder of source or an allowed_sources folder, an url only under an allowed_sources url. Two caches of Rc<Value>: the original documents, shared by all the sections of one run_all_codegenr, and the resolved ones, one per section, as they hold what the allowed_sources of their section let them read.
  3. Render (render.rs, helpers/, custom.rs): every .hbs of the template folders is collected, not the hidden files and folders of editors (.#main.hbs); exactly one main template (no _ prefix) across all the folders, partials _name.hbs registered as name, unique names. A fresh Handlebars per section, never reused between sections. Registration order matters: handlebars_misc_setup first, so codegenr helpers override the handlebars_misc_helpers ones of the same name; then the stateless helpers, the stateful ones (the shared get/set store, global_parameter), then the .rhai custom helpers (file stem = helper name). No HTML escaping; dev mode in debug builds.
  4. Process (processor/): the rendered text is read line by line; a line matching ^###[^#]*$ is an instruction, so a #### line is plain content. ### FILE <path> … ### /FILE writes under output on its closing tag (InstructionLineHandler::finish), and skips a file whose content is unchanged; ### CONSOLE … ### /CONSOLE prints; ### CLEAN <glob> has no closing tag and deletes the matching files and folders under output. Both paths go through path_in_output, which refuses an absolute path or a ..: templates and source documents are not trusted. A new instruction implements Instruction and gets registered in get_instructions.

intermediate dumps <name>.resolved.json and <name>.rendered.txt in the current dir: the first thing to look at when a generation goes wrong. run_all_codegenr goes on when a section fails, logs it, and returns a Batch error at the end.

Helpers

Each helper of src/helpers/ is a pub const <NAME>_HELPER: &str, a struct implementing HelperDef, its arguments checked through HandlebarsExt (ensure_arguments_count*, get_param_as_str_or_fail…). Its doc comment is both its documentation on docs.rs and its tests: doctests calling exec_template / exec_template_with_global_params, should_panic for the error cases. A new helper gets registered in handlebars_stateless_setup or handlebars_statefull_setup.

Samples

codegenr/_samples/ holds the fixtures, read by the tests with paths relative to the crate dir (the cwd of cargo test). _samples/render/yaml_output is an end-to-end golden master: cargo run -q -- file run from that folder must leave the committed output.yaml unchanged. The xml loader has its own golden master (read_xml_file_test): each .xml sample has its expected .json next to it, key order included; _samples/loader/xml_shapes.xml holds every shape.

Code Style

  • rustfmt: max_width = 140, tab_spaces = 2, edition 2024.
  • Merged use: one use per crate, its modules and items merged in braces (use std::{fs, io::{self, Read}};), never several lines repeating the same crate or module. The stable rustfmt cannot merge them (imports_granularity = "Crate" is nightly only): they are merged by hand.
  • Line breaks follow the meaning, not the width, in comments, doc comments and markdown: break after a full clause or sentence, never in the middle of one to fill the line. max_width is a ceiling, not a target.
  • Docs read by a French speaker: the docs, README and doc comments stay in English, but a key technical term gets its French translation once, in italics, at its first use: template (gabarit), partial template (gabarit partiel).
  • logging: use tracing::, avoid println!.
  • Error types: suffix with Error, thiserror for the library errors, anyhow for the binary and the tests.
  • no panic!: use clean error handling, avoid .unwrap(), expect(), unreachable!(), panic!(), todo!()… only the tests can panic.
  • no dynamic beyond the source document: the source documents are truly unknown, so the pipeline works on serde_json::Value; anything with a known shape (configuration, options, helper parameters) gets a struct rather than untyped Value navigation.
  • even in tests, prefer anyhow::Result<()> and ? over unwrap() or expect(): cleaner test code and better error messages.
  • Pin upstream bugs with a test: when a bug is found in a dependency (crate, tool, service), write a unit test that asserts the buggy behavior as it is today, with a comment linking the upstream issue (or stating none exists yet) and describing the expected correct behavior. Such a test is a tripwire: once upstream fixes the bug, it fails, which tells us to remove the workaround and turn it into a regular non-regression test. Name it explicitly (e.g. upstream_bug_<crate>_<short_desc>) so it is not mistaken for a regular test. The handlebars 6 regression above is the kind of bug it is for.
  • Commit messages: about 10 words, do not mention the agent as co-author.

🪜 Least Code Ladder

YAGNI, KISS, and the Rule of Least Power (Berners-Lee): write the least code that works. Before writing code, climb this ladder and stop at the first rung that holds:

  1. Does it need to exist? No: skip it, and say so.
  2. Already in this codebase? Reuse it: the existing helpers, HandlebarsExt, StringExt, the loaders.
  3. Rust std does it? Use it.
  4. The template layer does it? A Handlebars built-in, a handlebars_misc_helpers helper, a partial or a user-side .rhai custom helper, before a new Rust helper.
  5. A current dependency does it? Use it. A new one needs the human (see Critical Rules).
  6. One line does it? One line.
  7. Only then the minimum that works, no speculative generality, unless asked.
  • Never on the chopping block: trust-boundary validation (source documents and templates come from the user), data-loss handling (CLEAN deletes, FILE overwrites), security.
  • Fix the root cause: before fixing a bug, grep every caller of what you change.
  • Deliberate shortcuts are visible: a TO_HUMAN: comment says what was skipped and when to add it; the chat summary lists them as skipped: X, add when Y.
  • Reviews also hunt over-engineering: unused abstractions, wrappers, config nobody sets, reimplemented std or helper features, as a delete-list.

Source, for the record only (everything useful is distilled above, no need to re-read it): Ponytail v4.10.0 (MIT), adapted 2026-09-26.

Release

  • Not the business of the agent, the human handles it unless explicitly instructed otherwise: a push to main runs the CI that publishes the crate to crates.io (.github/workflows/main.yaml).

🛠 Security & Shell Guidelines

To avoid self-triggering security blocks and manual confirmations:

  • No Backslash Escapes: Never use ; or |. Use single quotes instead, e.g., -exec ... {} ';' or +.
  • Prefer fd over find: Since it's installed, use fd for all file searches to avoid complex -exec syntax.
  • Redirections: Avoid complex 2>&1 | grep combos if a simpler alternative exists, to bypass "Do you want to proceed?" prompts.
  • Disk full (No space left on device): the agent may, without asking, delete its own temporary scratchpad and run cargo clean on this repository (the next build is slower, nothing else is lost). Never anything else to free space; if that is not enough, stop and tell the human.

Human in the Loop

  • Agent must NEVER change branch, or create PRs, only the human will review the merges and PRs.
  • No git worktree: the human follows the work in the main checkout, in their editor; work done in a worktree is out of their sight. A task that needs another branch than the one checked out asks the human to switch to it, or, when told to switch, does it in the main checkout.
  • Agent must NEVER rewrite the git history, if you need to fix a commit, make a new commit.
  • Agent should NEVER be lazy and remove test cases without assessing the reason & explain with a comment for the human to review.
  • When some doubts arise, the agent should continue with a balanced approach: consider the amount of code needed (has to be as low as possible, see the Least Code Ladder), and the long term maintainability of the codebase.
  • When not obvious, leave code comments to the human to review before commit or merging, begin those comments with TO_HUMAN: so that they are easily searchable.
  • Intermediate commits are expected on long tasks. When a task spans several phases, commit each phase as soon as it is verified: it builds and the tests pass. Never commit a red build — if a phase only compiles together with the next one, they are a single commit. Each commit must be self-contained and describe that phase, still in about 10 words. Say in the chat what was committed and what is left.
  • Reviews live in french language in REVIEW.md at the repo root. Code-review findings land there as a ranked list (most severe first, file:line, one-line why), and nothing gets fixed until the human picks an item. The file is committed with the branch and kept up to date while the branch matures: each item gets its outcome (fixed, skipped and why). Each item starts with its status icon, never a status word: 🟢 done, ⚪ skipped, 🔴 to do, 🟠 needs the human (a decision, more input) or postponed. The same icons mark any list of things to review or fix kept in a working file. It is deleted before the merge: a branch that still holds a REVIEW.md is not ready to merge.
  • A session goes to another machine through HANDOFF.md at the repo root, written when the human asks for a handoff, never on the agent's initiative: what git does not hold, never a journal. It is committed alone, the one commit of a last step the agent makes, with a warning about whatever else is left uncommitted or unpushed. One per branch, and short-lived: a session that starts with a HANDOFF.md at the root reads it first, says HANDOFF.md read, then deletes it (no staging), its content now in the session. A branch that still holds a HANDOFF.md is not ready to merge.
  • Do not auto-commit the last step. Whatever the size of the task, leave the final change uncommitted and unstaged, and stop there so the human reviews it before it enters history. Same for a standalone change — a crate bump, a bug fix, a feature — which is its own last step: explain the diff, stop. During some work in progress with the human, do not stage or unstage anything since the human reviewer uses it to see the latest changes you made.
  • Test code is the agent's call: the tests stay easy to read for the human alone, their speed and factorization come second.
  • Suggest the last step commit message: to sum up what you have just done and help the human follow, suggest a good commit message for the current uncommitted changes.
  • Never git push. More commits must not turn into more things leaving the machine.