diff --git a/.gitattributes b/.gitattributes index 1826c2c..37305b3 100644 --- a/.gitattributes +++ b/.gitattributes @@ -23,10 +23,6 @@ *.pptx filter=lfs diff=lfs merge=lfs -text *.pdf filter=lfs diff=lfs merge=lfs -text -# Temporary while checked in, will be auto-generated later on CI. -src/agents/all* filter=lfs diff=lfs merge=lfs -text - - # Make it look like a Rust project to GitHub's linguist. *.scss linguist-detectable=false *.html linguist-detectable=false @@ -34,4 +30,3 @@ src/agents/all* filter=lfs diff=lfs merge=lfs -text *.css linguist-detectable=false *.js linguist-detectable=false *.sh linguist-detectable=false - diff --git a/.github/workflows/common.yml b/.github/workflows/common.yml index def43ac..745896c 100644 --- a/.github/workflows/common.yml +++ b/.github/workflows/common.yml @@ -29,8 +29,8 @@ jobs: - name: Preprocess run: | chmod +x ./scripts/*.sh - bash ./scripts/agents_summary.sh - bash ./scripts/agents_meta.sh + python3 scripts/test_build_skill.py + python3 scripts/build_skill.py bash ./scripts/build_date.sh - name: MdBook Test diff --git a/.gitignore b/.gitignore index 9d2d4f1..4ac11f1 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ output .idea *.local.json .*/**/*.md - +/src/agents/pragmatic-rust-guidelines.zip +__pycache__/ diff --git a/CLAUDE.md b/AGENTS.md similarity index 80% rename from CLAUDE.md rename to AGENTS.md index 12087ac..2fc2be3 100644 --- a/CLAUDE.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ -# CLAUDE.md +# AGENTS.md ## Repository Overview @@ -11,6 +11,8 @@ This repository contains the **Pragmatic Rust Guidelines** - a collection of des ```bash mdbook serve --open # Previews page mdbook build # Builds page +python3 scripts/build_skill.py # Generates the distributable agent skill +python3 scripts/test_build_skill.py # Tests skill packaging ``` Requires [mdbook](https://github.com/rust-lang/mdBook) to be installed. @@ -35,6 +37,8 @@ Content with code examples... - `src/SUMMARY.md` - mdBook table of contents - `src/guidelines/checklist/README.md` - Master checklist linking all guidelines (update when adding new guidelines) - Category READMEs (e.g., `src/guidelines/universal/README.md`) - Include guidelines via mdBook's `{{#include}}` directive +- `skill/SKILL.md` - Template for the skill distributed to other Rust repositories, not installed for this repository +- `scripts/build_skill.py` - Bundles canonical guidelines, category catalogs, and images into the downloadable skill ## Adding New Guidelines @@ -42,6 +46,10 @@ Content with code examples... 2. Add the guideline to the category's `README.md` using `{{#include M-YOUR-GUIDELINE.md}}` 3. Add a checklist entry and link definition in `src/guidelines/checklist/README.md` +After changing guidelines or the skill template, regenerate the archive with `python3 scripts/build_skill.py`. +Do not maintain separate authored copies of the reference Markdown. +The build requires the guideline images to be downloaded through Git LFS. + Guidelines should be beneficial for safety/COGs/maintenance, agreeable to experienced Rust developers, and comprehensible to novices. ## Editing Guidelines diff --git a/README.md b/README.md index 1581353..a691fe9 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,12 @@ A collection of pragmatic design guidelines helping developers to produce idioma 👉 [**Pragmatic Rust Guidelines**](https://microsoft.github.io/rust-guidelines) +## Agent Skill + +Use the [Pragmatic Rust Guidelines agent skill](src/agents/README.md) in your own Rust repository. +The downloadable package contains instructions, category catalogs, the guideline Markdown, and its supporting images. +Agents can read relevant guidelines without loading the entire book or checking out this repository. + ## Development The guidelines use [mdbook](https://github.com/rust-lang/mdBook). Once installed you can view them locally via @@ -12,6 +18,16 @@ The guidelines use [mdbook](https://github.com/rust-lang/mdBook). Once installed mdbook serve --open ``` +To build the distributable skill download, run: + +```bash +python3 scripts/build_skill.py +``` + +The archive is generated at `src/agents/pragmatic-rust-guidelines.zip` and included in the published book. +The `skill/` directory contains the packaging template, not a skill installed for this repository. +The build requires the guideline images to be downloaded through Git LFS. + To submit new guidelines, file a PR. They should be - beneficial for { safety, COGs, maintenance }, diff --git a/scripts/agents_meta.sh b/scripts/agents_meta.sh deleted file mode 100644 index a008840..0000000 --- a/scripts/agents_meta.sh +++ /dev/null @@ -1,78 +0,0 @@ -#!/bin/bash - -# Script to generate .meta files for all .md files in the agents directory -# Each .meta file contains size and token count information -# Excludes README.md files - -set -euo pipefail - -# Get the script directory and project root -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" -AGENTS_DIR="$PROJECT_ROOT/src/agents" - -# Check if agents directory exists -if [[ ! -d "$AGENTS_DIR" ]]; then - echo "Error: $AGENTS_DIR directory not found" - exit 1 -fi - -echo "Generating .meta files for markdown files in $AGENTS_DIR..." - -# Counter for processed files -processed_count=0 - -# Find all .md files in agents directory, excluding READMEs -for md_file in "$AGENTS_DIR"/*.md; do - # Check if file exists (glob expansion protection) - if [[ ! -f "$md_file" ]]; then - continue - fi - - # Skip README files (case insensitive) - basename_file=$(basename "$md_file") - if [[ "${basename_file,,}" == "readme.md" ]]; then - echo " Skipping: $basename_file" - continue - fi - - # Generate .meta file path - meta_file="${md_file%.*}.meta" - - # Get file size in bytes - file_size_bytes=$(wc -c < "$md_file") - - # Format file size - if [[ $file_size_bytes -lt 1024 ]]; then - size_str="${file_size_bytes} bytes" - elif [[ $file_size_bytes -lt $((1024 * 1024)) ]]; then - file_size_kb=$((file_size_bytes / 1024)) - size_str="~${file_size_kb} kb" - else - file_size_mb=$((file_size_bytes / (1024 * 1024))) - size_str="~${file_size_mb} MB" - fi - - # Estimate tokens (roughly 4 characters per token for English text) - estimated_tokens=$((file_size_bytes / 4)) - if [[ $estimated_tokens -lt 1000 ]]; then - estimated_ktokens=0 - else - estimated_ktokens=$((estimated_tokens / 1000)) - fi - - # Generate meta content - meta_content="${size_str}, ~${estimated_ktokens}k tokens" - - # Write .meta file - echo "$meta_content" > "$meta_file" - - echo " $(basename "$md_file") -> $(basename "$meta_file") ($meta_content)" - processed_count=$((processed_count + 1)) -done - -if [[ $processed_count -eq 0 ]]; then - echo "No markdown files found to process (excluding READMEs)" -else - echo "Successfully generated $processed_count .meta files" -fi \ No newline at end of file diff --git a/scripts/agents_summary.sh b/scripts/agents_summary.sh deleted file mode 100644 index 04c2144..0000000 --- a/scripts/agents_summary.sh +++ /dev/null @@ -1,147 +0,0 @@ -#!/bin/bash - -# Script to update agents/all.md with a concatenation of all guidelines -# This script inspects all folders under `guidelines` (except checklist) -# and includes each README.md followed by the M- guidelines in that folder - -set -euo pipefail - -# Get the script directory and project root -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -PROJECT_ROOT="$(dirname "$SCRIPT_DIR")" -SRC_DIR="$PROJECT_ROOT/src" -GUIDELINES_DIR="$SRC_DIR/guidelines" -OUTPUT_FILE="$SRC_DIR/agents/all.txt" -META_FILE="$SRC_DIR/agents/all.meta" - -# Create output directory if it doesn't exist -mkdir -p "$(dirname "$OUTPUT_FILE")" - -# Start with header -cat > "$OUTPUT_FILE" << 'EOF' - - -# Pragmatic Rust Guidelines - -This file contains all guidelines concatenated for easy reference. - ---- - -EOF - -# Function to extract title from README.md (first # heading) -extract_title_from_readme() { - local readme_file="$1" - if [[ -f "$readme_file" ]]; then - # Extract first line that starts with # - grep '^#' "$readme_file" | head -n1 - fi -} - -# Function to process each guidelines subdirectory -process_guidelines_dir() { - local dir="$1" - local dir_name=$(basename "$dir") - - # Skip checklist directory as requested - if [[ "$dir_name" == "checklist" ]]; then - echo "Skipping checklist directory" - return - fi - - # Skip if not a directory - if [[ ! -d "$dir" ]]; then - return - fi - - echo "Processing directory: $dir_name" - - # Add section header using the title from README.md - if [[ -f "$dir/README.md" ]]; then - local title=$(extract_title_from_readme "$dir/README.md") - if [[ -n "$title" ]]; then - echo "" >> "$OUTPUT_FILE" - echo "$title" >> "$OUTPUT_FILE" - echo "" >> "$OUTPUT_FILE" - fi - else - echo "Warning: No README.md found in $dir" - # Fallback section header - echo "" >> "$OUTPUT_FILE" - echo "# $(echo "$dir_name" | tr '[:lower:]' '[:upper:]') Guidelines" >> "$OUTPUT_FILE" - echo "" >> "$OUTPUT_FILE" - fi - - # Include all M-*.md files in alphabetical order - local m_files=() - if ls "$dir"/M-*.md >/dev/null 2>&1; then - for m_file in "$dir"/M-*.md; do - if [[ -f "$m_file" ]]; then - m_files+=("$m_file") - fi - done - - # Sort the array and clean up any carriage returns - IFS=$'\n' m_files=($(printf '%s\n' "${m_files[@]}" | sort)) - unset IFS - - for m_file in "${m_files[@]}"; do - # Strip any carriage returns from the filename - m_file=$(echo "$m_file" | tr -d '\r') - echo "Including: $(basename "$m_file")" - echo "" >> "$OUTPUT_FILE" - # Skip the BOM + copyright line at the top of each file - tail -n +2 "$m_file" >> "$OUTPUT_FILE" - echo "" >> "$OUTPUT_FILE" - done - else - echo "No M-*.md files found in $dir" - fi - - # Add separator between sections - echo "" >> "$OUTPUT_FILE" - echo "---" >> "$OUTPUT_FILE" - echo "" >> "$OUTPUT_FILE" -} - -# Find all subdirectories in guidelines and process them -echo "Generating $OUTPUT_FILE..." - -# Process directories in a consistent order (recursively) -for dir in "$GUIDELINES_DIR"/*/ "$GUIDELINES_DIR"/*/*/; do - if [[ -d "$dir" ]]; then - process_guidelines_dir "$dir" - fi -done - -# Generate metadata file with size and token estimates -if [[ -f "$OUTPUT_FILE" ]]; then - # Get file size in KB - file_size_bytes=$(wc -c < "$OUTPUT_FILE") - file_size_kb=$((file_size_bytes / 1024)) - - # Estimate tokens (roughly 4 characters per token for English text) - estimated_tokens=$((file_size_bytes / 4)) - estimated_ktokens=$((estimated_tokens / 1000)) - - # Format the output - echo "~${file_size_kb} kb, ~${estimated_ktokens}k tokens" > "$META_FILE" - - echo "Successfully generated $OUTPUT_FILE (~${file_size_kb} kb, ~${estimated_ktokens}k tokens)" - echo "Metadata saved to $META_FILE" -else - echo "Error: Output file was not generated successfully" - exit 1 -fi - -echo "File contains guidelines from the following directories:" -for dir in "$GUIDELINES_DIR"/*/ "$GUIDELINES_DIR"/*/*/; do - if [[ -d "$dir" ]]; then - # Get relative path from guidelines directory - rel_path="${dir#$GUIDELINES_DIR/}" - dir_name=$(basename "$dir") - if [[ "$dir_name" != "checklist" ]]; then - echo " - $rel_path" - fi - fi -done diff --git a/scripts/build_skill.py b/scripts/build_skill.py new file mode 100644 index 0000000..c75964b --- /dev/null +++ b/scripts/build_skill.py @@ -0,0 +1,275 @@ +#!/usr/bin/env python3 +"""Build the portable skill download from the canonical guideline sources.""" + +import argparse +import io +from pathlib import Path, PurePosixPath +import posixpath +import re +from urllib.parse import unquote, urlsplit +import zipfile + + +NAME = "pragmatic-rust-guidelines" +INCLUDE = re.compile(r"\{\{#include (M-[A-Z-]+\.md)\}\}") + + +def markdown_cell(text): + return text.replace("|", "\\|").replace("\n", " ") + + +def local_target(filename, link): + url = urlsplit(link) + if url.scheme or url.netloc or not url.path: + return None + return posixpath.normpath( + str(PurePosixPath(filename).parent / unquote(url.path)) + ) + + +def markdown_links(content): + text = content.decode("utf-8-sig") + links = re.findall(r"\]\(([^)\s]+)", text) + links.extend(re.findall(r"^\[[^\]]+\]:\s+(\S+)", text, re.MULTILINE)) + return links + + +def rewrite_links(filename, content, files, identifiers): + def destination(link): + url = urlsplit(link) + if url.scheme or url.netloc: + return link + if url.fragment in identifiers: + target = identifiers[url.fragment] + else: + target = local_target(filename, link) + if target is None: + return link + readme = target.rstrip("/") + "/README.md" + if readme in files: + target = readme + else: + return link + relative = posixpath.relpath(target, str(PurePosixPath(filename).parent)) + return relative + ("#" + url.fragment if url.fragment else "") + + text = content.decode("utf-8-sig") + text = re.sub( + r"(\]\()([^\s)]+)(\))", + lambda match: match[1] + destination(match[2]) + match[3], + text, + ) + text = re.sub( + r"^(\[[^\]]+\]:\s+)(\S+)", + lambda match: match[1] + destination(match[2]), + text, + flags=re.MULTILINE, + ) + return text.encode() + + +def validate_links(files): + for filename, content in files.items(): + if not filename.endswith(".md"): + continue + for link in markdown_links(content): + target = local_target(filename, link) + if target is not None and target not in files: + raise ValueError(f"Unbundled reference in {filename}: {link}") + + +def package_files(root): + files = { + "SKILL.md": (root / "skill/SKILL.md").read_bytes(), + "LICENSE.md": (root / "LICENSE.md").read_bytes(), + } + summary = (root / "src/SUMMARY.md").read_text(encoding="utf-8-sig") + categories = re.findall( + r"^\s*- \[([^\]]+)\]\(\./guidelines/(.+)/README\.md\)$", + summary, + re.MULTILINE, + ) + guidelines = {} + memberships = {} + for title, category in categories: + readme = root / "src/guidelines" / category / "README.md" + content = readme.read_text(encoding="utf-8-sig") + entries = INCLUDE.findall(content) + memberships[category] = entries + for name in entries: + source = readme.parent / name + text = source.read_text(encoding="utf-8-sig") + identifier = source.stem + heading = re.search( + r"^## (.+) \(" + re.escape(identifier) + r"\) \{", + text, + re.MULTILINE, + ) + if not heading: + raise ValueError(f"Missing guideline heading: {source}") + relative = "references/" + source.relative_to(root / "src").as_posix() + guidelines[identifier] = (relative, heading[1], text) + files[relative] = source.read_bytes() + content = INCLUDE.sub( + lambda match: f"- [{Path(match[1]).stem}]({match[1]}): " + + guidelines[Path(match[1]).stem][1], + content, + ) + files[f"references/guidelines/{category}/README.md"] = content.encode() + + overview = [ + "# Guideline Catalog", + "", + "This catalog is generated from Pragmatic Rust Guidelines.", + "Read the relevant category catalog, then follow its links to individual guidelines.", + "Draft guidelines are investigation prompts rather than established recommendations.", + "", + "| Category | Guidelines |", + "| --- | --- |", + ] + version = re.search( + r"^Version: (.+)$", + (root / "src/guidelines/README.md").read_text(encoding="utf-8-sig"), + re.MULTILINE, + ) + if version: + overview[2:2] = [f"Book version: {version[1]}", ""] + for title, category in categories: + catalog_path = f"references/catalogs/{category}.md" + catalog = [ + f"# {title}", + "", + "Read the guidelines relevant to the code under investigation.", + "The reference text, not the catalog keywords, defines each guideline's scope.", + "", + ] + children = [ + (child_title, child) + for child_title, child in categories + if str(PurePosixPath(child).parent) == category + ] + if children: + catalog.extend(["| Subcategory | Catalog |", "| --- | --- |"]) + for child_title, child in children: + link = posixpath.relpath( + f"references/catalogs/{child}.md", + str(PurePosixPath(catalog_path).parent), + ) + catalog.append(f"| {child_title} | [{child_title}]({link}) |") + catalog.append("") + entries = memberships[category] + if entries: + catalog.extend([ + "| Guideline | Description | Keywords | Status |", + "| --- | --- | --- | --- |", + ]) + for name in sorted(entries): + identifier = Path(name).stem + relative, heading, content = guidelines[identifier] + draft = "> Draft" in content or "0.1" in content + keywords = identifier[2:].lower().split("-") + keywords.extend(re.findall(r"`([^`\n]+)`", content)[:4]) + link = posixpath.relpath( + relative, str(PurePosixPath(catalog_path).parent) + ) + catalog.append( + f"| [{identifier}]({link}) | {markdown_cell(heading)} " + f"| {markdown_cell(', '.join('`' + word + '`' for word in dict.fromkeys(keywords)))} " + f"| {'Draft' if draft else 'Not marked as draft'} |" + ) + files[catalog_path] = ("\n".join(catalog).rstrip() + "\n").encode() + count = str(len(entries)) if entries else "See subcategories" + overview.append(f"| [{title}](catalogs/{category}.md) | {count} |") + files["references/CATALOG.md"] = ("\n".join(overview) + "\n").encode() + + identifiers = {key: value[0] for key, value in guidelines.items()} + unavailable = {} + for filename, content in files.items(): + for link in markdown_links(content): + url = urlsplit(link) + if not url.scheme and not url.netloc and re.fullmatch(r"M-[A-Z-]+", url.fragment): + if url.fragment not in identifiers: + unavailable.setdefault(url.fragment, set()).add(filename) + if unavailable: + notes_path = "references/REFERENCE-NOTES.md" + notes = [ + "# Reference Notes", + "", + "These identifiers appear in source cross-references but have no matching guideline Markdown in this edition.", + "No missing guideline text is supplied or inferred.", + ] + for identifier, sources in sorted(unavailable.items()): + identifiers[identifier] = notes_path + notes.extend([ + "", + f'', + "", + f"## {identifier}", + "", + "This guideline is unavailable in this edition.", + "Do not infer its requirements from the identifier.", + "", + "Referenced by:", + "", + ]) + for source in sorted(sources): + link = posixpath.relpath(source, "references") + notes.append(f"- [{PurePosixPath(source).stem}]({link})") + files[notes_path] = ("\n".join(notes) + "\n").encode() + files["references/CATALOG.md"] += ( + "\nSome source cross-references name unavailable guidelines. " + "Read the [reference notes](REFERENCE-NOTES.md) rather than inferring missing guidance.\n" + ).encode() + for filename, content in list(files.items()): + if filename.endswith(".md"): + files[filename] = rewrite_links(filename, content, files, identifiers) + for filename, content in list(files.items()): + if not filename.endswith(".md"): + continue + links = re.findall(r"!\[[^\]]*\]\(([^)\s]+)", content.decode("utf-8-sig")) + for link in links: + target = local_target(filename, link) + if target is None or target in files: + continue + if not target.startswith("references/guidelines/"): + raise ValueError(f"Asset outside guideline sources: {link}") + source = root / "src" / target.removeprefix("references/") + data = source.read_bytes() + if data.startswith(b"version https://git-lfs.github.com/spec/v1"): + raise ValueError(f"Git LFS asset is not downloaded: {source}") + files[target] = data + validate_links(files) + return files + + +def build_archive(root): + output = io.BytesIO() + with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive: + for relative, content in sorted(package_files(root).items()): + info = zipfile.ZipInfo(f"{NAME}/{relative}") + info.compress_type = zipfile.ZIP_DEFLATED + info.create_system = 3 + info.external_attr = 0o100644 << 16 + archive.writestr(info, content) + return output.getvalue() + + +def main(): + root = Path(__file__).resolve().parents[1] + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--output", + type=Path, + default=root / f"src/agents/{NAME}.zip", + help="Destination for the self-contained skill ZIP archive.", + ) + args = parser.parse_args() + content = build_archive(root) + args.output.parent.mkdir(parents=True, exist_ok=True) + if not args.output.exists() or args.output.read_bytes() != content: + args.output.write_bytes(content) + print(f"Built {args.output} ({len(content):,} bytes)") + + +if __name__ == "__main__": + main() diff --git a/scripts/test_build_skill.py b/scripts/test_build_skill.py new file mode 100644 index 0000000..3dd3bc6 --- /dev/null +++ b/scripts/test_build_skill.py @@ -0,0 +1,116 @@ +import io +from pathlib import Path +import tempfile +import unittest +import zipfile + +from build_skill import build_archive, package_files, validate_links + + +class BuildSkillTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + sources = { + "LICENSE.md": "Test license\n", + "skill/SKILL.md": "# Skill\n\n[Catalog](references/CATALOG.md)\n", + "src/SUMMARY.md": ( + "# Summary\n\n- [Universal](./guidelines/universal/README.md)\n" + "- [Libraries](./guidelines/libs/README.md)\n" + " - [UX](./guidelines/libs/ux/README.md)\n" + ), + "src/guidelines/README.md": "# About\n\nVersion: test\n", + "src/guidelines/universal/README.md": ( + "# Universal\n\n{{#include M-CHECK.md}}\n" + ), + "src/guidelines/universal/M-CHECK.md": ( + "## Check code (M-CHECK) { #M-CHECK }\n\n" + "> Draft guideline. Examples needed.\n\n" + "Use `Clippy`, `Result`, and [errors](../libs/ux/#M-ERROR).\n" + "[UX](../libs/ux/)\n\n![Example](example.png)\n" + ), + "src/guidelines/libs/README.md": "# Libraries\n\n[UX](./ux/)\n", + "src/guidelines/libs/ux/README.md": ( + "# UX\n\n{{#include M-ERROR.md}}\n" + ), + "src/guidelines/libs/ux/M-ERROR.md": ( + "## Use errors (M-ERROR) { #M-ERROR }\n\nUse error values.\n" + "[M-CHECK]: ../../universal/#M-CHECK\n" + ), + "src/guidelines/universal/M-UNPUBLISHED.md": "Not a published guideline.\n", + } + for name, content in sources.items(): + path = self.root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + (self.root / "src/guidelines/universal/example.png").write_bytes(b"\x89PNG\r\n\x1a\n") + + def test_portable_bundle_covers_nested_catalogs_and_images(self): + first = build_archive(self.root) + self.assertEqual(first, build_archive(self.root)) + with zipfile.ZipFile(io.BytesIO(first)) as archive: + self.assertIsNone(archive.testzip()) + prefix = "pragmatic-rust-guidelines/" + names = archive.namelist() + self.assertFalse(any("UNPUBLISHED" in name for name in names)) + self.assertEqual( + archive.read(prefix + "references/guidelines/universal/example.png"), + b"\x89PNG\r\n\x1a\n", + ) + catalog = archive.read(prefix + "references/catalogs/universal.md").decode() + self.assertIn("[M-CHECK](../guidelines/universal/M-CHECK.md)", catalog) + self.assertIn("Clippy", catalog) + self.assertIn("`Result`", catalog) + self.assertIn("| Draft |", catalog) + nested = archive.read(prefix + "references/catalogs/libs/ux.md").decode() + self.assertIn("../../guidelines/libs/ux/M-ERROR.md", nested) + self.assertIn("| Not marked as draft |", nested) + parent = archive.read(prefix + "references/catalogs/libs.md").decode() + self.assertIn("[UX](libs/ux.md)", parent) + readme = archive.read(prefix + "references/guidelines/universal/README.md") + self.assertNotIn(b"{{#include", readme) + self.assertIn(prefix + "LICENSE.md", names) + source = self.root / "src/guidelines/libs/ux/M-ERROR.md" + source.write_text(source.read_text() + "\nUpdated source content.\n") + self.assertNotEqual(first, build_archive(self.root)) + + def test_aggregate_links_resolve_to_individual_guidelines(self): + files = package_files(self.root) + text = files["references/guidelines/universal/M-CHECK.md"].decode() + self.assertIn("[errors](../libs/ux/M-ERROR.md#M-ERROR)", text) + self.assertIn("[UX](../libs/ux/README.md)", text) + nested = files["references/guidelines/libs/ux/M-ERROR.md"].decode() + self.assertIn("[M-CHECK]: ../../universal/M-CHECK.md#M-CHECK", nested) + validate_links(files) + + def test_missing_and_lfs_pointer_assets_reject_incomplete_package(self): + asset = self.root / "src/guidelines/universal/example.png" + asset.unlink() + with self.assertRaises(FileNotFoundError): + package_files(self.root) + asset.write_bytes(b"version https://git-lfs.github.com/spec/v1\n") + with self.assertRaisesRegex(ValueError, "Git LFS asset is not downloaded"): + package_files(self.root) + + def test_reference_outside_bundle_is_rejected(self): + source = self.root / "src/guidelines/universal/M-CHECK.md" + source.write_text(source.read_text() + "\n[Missing](../../../outside.md)\n") + with self.assertRaisesRegex(ValueError, "Unbundled reference"): + package_files(self.root) + + def test_unavailable_guideline_is_flagged_without_inventing_content(self): + source = self.root / "src/guidelines/universal/M-CHECK.md" + source.write_text(source.read_text() + "\n[Unavailable](../libs/ux/#M-MISSING)\n") + files = package_files(self.root) + text = files["references/guidelines/universal/M-CHECK.md"].decode() + self.assertIn("[Unavailable](../../REFERENCE-NOTES.md#M-MISSING)", text) + notes = files["references/REFERENCE-NOTES.md"].decode() + self.assertIn('', notes) + self.assertIn("This guideline is unavailable", notes) + self.assertIn("guidelines/universal/M-CHECK.md", notes) + validate_links(files) + + +if __name__ == "__main__": + unittest.main() diff --git a/skill/SKILL.md b/skill/SKILL.md new file mode 100644 index 0000000..a6a59ba --- /dev/null +++ b/skill/SKILL.md @@ -0,0 +1,68 @@ +--- +name: pragmatic-rust-guidelines +description: Apply Pragmatic Rust Guidelines when designing, writing, reviewing, or refactoring Rust applications and libraries. Select relevant guidelines for APIs, ownership, errors, async code, documentation, testing, FFI, performance, and project structure, then assess their rationale against the user's code. +license: MIT +--- + +# Pragmatic Rust Guidelines + +Use this skill on the user's Rust project, not on the book repository. +Resolve all reference paths from this skill's directory. +The package contains its Markdown references and images. +It does not require the book checkout or network access to those references. + +## Select Relevant Guidelines + +Read only the catalogs relevant to the task. +Use [the catalog overview](references/CATALOG.md) when the task crosses categories. +Each catalog lists guideline identifiers, descriptions, search terms, and draft status. + +| Area | Catalog | +| --- | --- | +| General Rust design, naming, formatting, and automated checks | [Universal](references/catalogs/universal.md) | +| Library design overview | [Libraries](references/catalogs/libs.md) | +| External types, traits, and runtime interoperability | [Library Interoperability](references/catalogs/libs/interop.md) | +| Public APIs, builders, errors, modules, and async functions | [Library UX](references/catalogs/libs/ux.md) | +| Invariants, testability, state, and resilience | [Library Resilience](references/catalogs/libs/resilience.md) | +| Features, dependencies, and native library builds | [Library Building](references/catalogs/libs/building.md) | +| Declarative and procedural macros | [Macros](references/catalogs/macros.md) | +| Application errors, allocation, and processor targets | [Applications](references/catalogs/apps.md) | +| Foreign interfaces and native library boundaries | [FFI](references/catalogs/ffi.md) | +| Panics, soundness, and unsafe code | [Correctness](references/catalogs/correctness.md) | +| Allocation, data layout, throughput, and profiling | [Performance](references/catalogs/performance.md) | +| Workspaces, editions, and supported Rust versions | [Project](references/catalogs/project.md) | +| API documentation and examples | [Documentation](references/catalogs/docs.md) | +| AI-readable code, visibility, and meaningful tests | [AI](references/catalogs/ai.md) | + +Follow the catalog links to the individual guidelines needed for the task. +Read linked guidelines when their rationale affects the same decision. +Do not load the entire reference collection. +If the code reveals another relevant area, read that area's catalog. + +## Apply the Guidelines + +1. Establish the crate's role, public API commitments, supported platforms, and compatibility requirements. +2. Read the relevant code, tests, and project instructions before recommending a change. +3. Use the project's configured automated checks for issues those tools already cover. +4. Read the selected guidelines and evaluate their rationale against the actual code. +5. Distinguish required rules from recommendations that permit justified exceptions. +6. If changes are requested, make the smallest change that addresses the identified issue. +7. Preserve behavior and public compatibility unless the user requests a change. +8. Follow the user's execution policy and use the project's existing validation tools. +9. Report the guideline identifiers, affected project locations, evidence, and any justified exceptions. + +For code that is not yet written, use the guidelines to compare design choices before choosing an implementation. +For reviews, report actionable findings rather than applying every guideline mechanically. +Do not rewrite unrelated code solely to satisfy a guideline. + +## Interpret Scope and Evidence + +Apply the spirit of a guideline rather than its wording alone. +If a guideline conflicts with its underlying motivation, explain the conflict instead of following it blindly. +Treat guidelines marked as drafts as investigation prompts, not established rules. +If a source cross-reference names an unavailable guideline, report it rather than inventing guidance. + +For unsafe code, explain the invariants and the evidence that supports them. +For performance changes, distinguish measured improvements from hypotheses. +Do not replace an implementation solely because a reference names a different crate. +State missing evidence and unresolved risks instead of claiming that a guideline proves correctness or performance. diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 8507ffc..7572a93 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -20,6 +20,6 @@ --- -[Agents & LLMs](./agents/README.md) +[Agent Skill](./agents/README.md) [Changelog](./changelog/README.md) [FAQ](./FAQ/README.md) diff --git a/src/agents/.markdownlint.json b/src/agents/.markdownlint.json deleted file mode 100644 index 686305e..0000000 --- a/src/agents/.markdownlint.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "MD004": false, - "MD007": false, - "MD009": false, - "MD012": false, - "MD013": false, - "MD022": false, - "MD024": false, - "MD025": false, - "MD026": false, - "MD031": false, - "MD032": false, - "MD033": false, - "MD034": false, - "MD040": false, - "MD041": false, - "MD042": false, - "MD047": false, - "MD051": false -} diff --git a/src/agents/README.md b/src/agents/README.md index 284b50f..06a0922 100644 --- a/src/agents/README.md +++ b/src/agents/README.md @@ -1,27 +1,46 @@ - - -# Agents & LLMs - -While these guidelines have been carefully handcrafted, they have been written with LLM consumption in mind. -We offer condensed versions you can include in your agent sessions when authoring or reviewing code. - -## Available Resources - -| Name | Size | Description | -|------|------|-------------| -| [all](https://microsoft.github.io/rust-guidelines/agents/all.txt) [📋](#) | {{#include all.meta}} | The entire Pragmatic Rust Guidelines in one file. | - - + + +# Agent Skill + +The Pragmatic Rust Guidelines skill helps agents design, write, review, and refactor Rust code in your own project. +It contains instructions, category catalogs, individual guideline Markdown files, and supporting images. +The agent reads relevant references as needed rather than loading the entire book. + +## Download and Install + +Download the [pragmatic-rust-guidelines skill](pragmatic-rust-guidelines.zip). +Extract the archive into the skills directory supported by your agent. +Keep the complete `pragmatic-rust-guidelines` directory, including `SKILL.md`, `LICENSE.md`, and `references/`. + +For GitHub Copilot, run this command from the root of your target Rust project. +Replace the archive path with the location of your downloaded file. + +```bash +unzip /path/to/pragmatic-rust-guidelines.zip -d .github/skills +``` + +This creates `.github/skills/pragmatic-rust-guidelines/SKILL.md` and its bundled references in your project. +For other agents, use their documented skills directory. +See [GitHub's agent skill documentation](https://docs.github.com/en/copilot/how-tos/copilot-on-github/customize-copilot/customize-cloud-agent/add-skills) for supported installation locations. + +## Use the Skill + +Ask your agent to use `pragmatic-rust-guidelines` when designing an API, writing Rust code, or reviewing an existing crate. +The skill directs the agent to read the relevant catalogs and individual guidelines. +It requires the agent to evaluate each guideline's rationale and to respect your project's compatibility and validation constraints. + +The package works without a checkout of this book or network access to its references. +Draft guidelines remain investigation prompts, not established rules. +The agent must explain justified exceptions rather than applying every guideline mechanically. +Links between guidelines resolve to the bundled files. +If a source cross-reference names an unavailable guideline, the package links to an explicit reference note instead of inventing guidance. + +## Updates and Source + +Each published book build generates a new skill archive from the same guideline sources. +Keep a copy of the archive used by your project when you need reproducible advice. +The catalog records the book version. + +The [skill template](https://github.com/microsoft/rust-guidelines/blob/main/skill/SKILL.md) contains the instructions used in the download. +Its reference files are bundled during packaging, not maintained as a second authored copy. +The package includes the project's MIT license. diff --git a/src/agents/all.meta b/src/agents/all.meta deleted file mode 100644 index e275015..0000000 --- a/src/agents/all.meta +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:36669f3c9766cd684c41b790edd425bb80dce3d796962a57a09b3b624544cad2 -size 21 diff --git a/src/agents/all.txt b/src/agents/all.txt deleted file mode 100644 index 112f61b..0000000 --- a/src/agents/all.txt +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5cf536f19c53ecd003897c2065c044b1abaf17612e0838f69a7fe0ce547ad650 -size 136640 diff --git a/src/changelog/README.md b/src/changelog/README.md index 324ae69..ed554a3 100644 --- a/src/changelog/README.md +++ b/src/changelog/README.md @@ -4,6 +4,12 @@ This page tracks notable changes to the Pragmatic Rust Guidelines. +## 2026.10 + +Added a downloadable [agent skill](../agents/README.md) for use in other Rust repositories. +Each book publication generates a self-contained ZIP with instructions, category catalogs, guideline Markdown, and supporting images. +The skill replaces the consolidated `all.txt` download and lets agents read relevant guidelines as needed. + ## 2026.6 This update substantially expanded the guidelines, adding 41 new entries spanning diff --git a/src/guidelines/README.md b/src/guidelines/README.md index 168f4af..b7e778b 100644 --- a/src/guidelines/README.md +++ b/src/guidelines/README.md @@ -35,6 +35,13 @@ issues and we should update it, or it does not apply (and we might update it any > Before attempting to work around a guideline, you should understand why it exists and what it tries to safeguard. > Likewise, you should not blindly follow a guideline if it becomes apparent that doing so would violate its underlying motivation! +## Agent Skill + +Use the [Pragmatic Rust Guidelines agent skill](../agents/README.md) to apply these guidelines in your own Rust repository. +Download the self-contained package and install it in your agent's supported skills directory. +The skill selects relevant guideline references rather than loading the entire book. +It includes supporting images and treats draft guidelines as investigation prompts rather than established recommendations. + ## Submitting New Guidelines Do you have a practical guideline that leads to better safety, COGS or maintainability? We'd love to hear from you!