references/agent_instructions_writing_guide.md
<!-- SOURCE-OF-TRUTH: shared/references/agent_instructions_writing_guide.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->
# Agent Instructions Writing Guide
> **SCOPE:** How to author AGENTS.md and CLAUDE.md at the root of a project. Canonical reference for `ln-014-agent-instructions-manager`, `ln-111-root-docs-creator`, `ln-611-docs-structure-auditor`, and `ln-612-semantic-content-auditor`.
## Canonical model: AGENTS.md is the single source
Each harness auto-loads only its own memory file:
| Harness | Auto-loaded file | AGENTS.md auto-loaded? |
|---------|------------------|------------------------|
| Claude Code | `CLAUDE.md` | No — Anthropic docs: *"Claude Code reads CLAUDE.md, not AGENTS.md."* |
| OpenAI Codex CLI, Cursor, Amp, Factory, OpenCode, Zed | `AGENTS.md` | Yes |
Because CLAUDE.md is the file Claude Code loads by default, the naive "put a pointer in CLAUDE.md that says 'see AGENTS.md'" pattern **does not work** — the harness will not follow the pointer automatically. The content must be in the auto-loaded file.
Claude Code solves this with a native `@path` import syntax. The imported file is expanded and loaded into context at launch, exactly as if its content were inlined.
**The pattern:** keep a single canonical `AGENTS.md` at the repo root with all shared content. Make `CLAUDE.md` a thin stub that `@AGENTS.md` and adds only harness-specific deltas. Anthropic documents this pattern verbatim with an example at <https://code.claude.com/docs/en/memory#agents-md>.
Scope boundary: this native `@path` import behavior is the right pattern for Claude Code memory/context files such as `CLAUDE.md`. It is not the repository's canonical execution contract for `SKILL.md`; skills should still use explicit `**MANDATORY READ:** Load ...` for execution-critical references.
```markdown
# CLAUDE.md
@AGENTS.md
## Claude Code
- `/compact` preservation order: architecture decisions, verification status, open TODOs.
- Auto memory is on by default — run `/memory` to inspect.
```
This makes drift structurally impossible: there is one place to edit (`AGENTS.md`) and the stubs carry only genuinely harness-specific content.
## Size budgets
| Target | Limit | Source |
|--------|-------|--------|
| AGENTS.md line count | ≤200 lines (ideally ≤150) | Anthropic official: *"target under 200 lines per CLAUDE.md file. Longer files consume more context and reduce adherence."* |
| CLAUDE.md stub line count | ≤20 lines (≤50 absolute max) | Derived: stub should only carry harness delta |
| User-added imperatives across all loaded files | ≤100 | Empirical: IFScale (arxiv 2507.11538) finds frontier LLMs peak around 150–200 total instructions and degrade past that; Claude Code's built-in system prompt already consumes a significant portion |
Count imperatives as: lines matching `^\s*- ` inside rule sections, plus any line containing `MUST`, `NEVER`, `ALWAYS`, or `DO NOT`.
When AGENTS.md grows past 200 lines, split with progressive disclosure (next section) — do not accept a bigger root file.
## Progressive disclosure: use `.claude/rules/` with `paths:` frontmatter
Anthropic ships a built-in path-scoped rules mechanism. Place markdown files in `.claude/rules/` with YAML frontmatter declaring the glob patterns they apply to. Each file loads into context only when Claude touches a matching file.
```markdown
---
paths:
- "src/api/**/*.ts"
- "src/api/**/*.tsx"
---
# API development rules
- All endpoints must include input validation.
- Use the standard error response format.
```
Rules without a `paths` field load unconditionally with the same priority as `.claude/CLAUDE.md`. Shared rule directories can be symlinked across projects.
**Do not invent a new `agent_docs/` or similar convention.** Anthropic's `.claude/rules/` is the supported mechanism; using anything else gives up path scoping and breaks `/memory show`.
## Auto memory is built-in — do not author a manual Self-Improvement Loop
Claude Code has a first-class auto memory system, enabled by default (`CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` to disable; requires Claude Code v2.1.59+). Claude writes learnings from user corrections to `~/.claude/projects/<project>/memory/MEMORY.md` and optional topic files during every session. The first 200 lines or 25KB of `MEMORY.md` loads automatically.
Public articles sometimes recommend adding a manual `tasks/lessons.md` "Self-Improvement Loop" rule to CLAUDE.md (e.g., Hosni's *"after ANY correction from the user: update `tasks/lessons.md`"*). **Do not do this in our templates.** Claude Code's built-in auto memory already does exactly that, per Anthropic's own documentation. A manually-maintained parallel convention wastes context tokens and duplicates work. Document the equivalence; do not re-implement.
Run `/memory` to inspect or edit what Claude has saved.
## What legitimately belongs in the 50-line harness delta
Put in the CLAUDE.md stub:
- **Harness-specific command terminology**: `/compact`, `/memory show`, `/memory reload`. If it names a command that only works in Claude Code, it's a delta candidate.
- **Harness-specific storage pointers**: `~/.claude/projects/<project>/memory/` is Claude-specific.
- **Harness-specific features that don't exist elsewhere**: `.claude/rules/` with `paths:` frontmatter, nested `CLAUDE.md` on-demand loading, `CLAUDE_CODE_NEW_INIT=1`, `autoMemoryDirectory`, `claudeMdExcludes`.
Put in AGENTS.md (not the stub):
- Project architecture, tech stack, directory map.
- Critical rules that apply regardless of harness.
- Build and test commands.
- Coding standards and naming conventions.
- MCP tool preferences (hex-line, hex-graph, hex-research, etc. — these apply to any harness that can load MCP tools). Include `hex-research` only for projects with `docs/hypotheses/`, `docs/goals/`, or benchmark run manifests where graph state changes planning or validation decisions.
- Navigation tables.
- Compact-instructions preservation lists *(terminology differs per harness — but the preservation priority list itself is shared, so keep the list in AGENTS.md and mention only the command name in the stub)*.
If you find yourself writing the same rule into both AGENTS.md and CLAUDE.md, the rule belongs in AGENTS.md and the import takes care of the rest.
## Anti-patterns
| Anti-pattern | Why it's wrong | Fix |
|--------------|----------------|-----|
| Style / formatting rules (indentation, quote style, naming conventions) inside any instruction file | Instruction files are loaded into context on every session and cost tokens against the ~100-imperative budget; linters and formatters are deterministic, free, and faster | Move to Biome, Prettier, Ruff, EditorConfig, or a Claude Code Stop hook; keep the file free of style content |
| Conditional / non-universal rules (`when working on src/api/...`, `if modifying the billing service`) at the root | Claude Code injects a `<system-reminder>` around CLAUDE.md telling the model to ignore content that isn't clearly relevant; non-universal rules bias the model toward ignoring the *whole* file, not just the irrelevant parts | Move to `.claude/rules/*.md` with a `paths:` frontmatter filter (Anthropic's built-in path scoping) |
| Duplicating AGENTS.md content inside CLAUDE.md | Doubles the maintenance surface, causes drift, wastes tokens (the content is already imported via `@AGENTS.md`) | Replace the duplicated block with a single `@AGENTS.md` line; move any unique content *into* AGENTS.md |
| Hand-maintained "Self-Improvement Loop" / `tasks/lessons.md` section | Claude Code's built-in auto memory already does this (Anthropic docs); a parallel convention wastes context and diverges over time | Delete the section; rely on `~/.claude/projects/<project>/memory/` |
| Large HTML comment blocks at the top of CLAUDE.md for documentation | Block-level HTML comments are stripped before context injection *(Anthropic docs)*, so they cost zero context tokens, but they still clutter the maintainer view of the file | Short maintainer notes only; put detailed guide content in `agent_instructions_writing_guide.md` and point to it |
| Using `/init` without review | `/init` can insert boilerplate that reduces the signal-to-noise ratio of a high-leverage file; bad lines in CLAUDE.md cascade into every future session | Use `CLAUDE_CODE_NEW_INIT=1` for the interactive multi-phase flow with a reviewable proposal, or author by hand |
| Aggregate counts in instruction files (`"we have many skills"`) | Changes every time the repo grows, breaks prompt cache prefix match | Put counts only in README.md badges; everywhere else use qualitative descriptions |
| Timestamps and dates inside the rules text | Same cache-prefix problem | Keep `**Last Updated:** YYYY-MM-DD` at file end only |
## Optional Hosni workflow blocks — opt-in, not default
Hosni's article ("Level Up Your Claude Code with This CLAUDE.md", Feb 2026) proposes six Workflow Orchestration blocks. Our default `agents_md_workflow_principles.md` shard includes **Plan Mode Default**, **Verification Before Done**, **Demand Elegance**, and **Core Principles**. The remaining three are opt-in:
- **Subagent Strategy** — already covered by our orchestrator skills and `hex-line` MCP preferences. Restating at the root adds instruction-budget pressure without new behavior.
- **Self-Improvement Loop** — replaced by Claude Code built-in auto memory (see above).
- **Autonomous Bug Fixing** — requires a permission policy (allow the agent to run CI without asking) that we cannot guarantee uniformly across Claude Code and Codex. Add it manually if your environment supports it.
Users who want a block can add it to AGENTS.md themselves. The ln-014 audit will not flag it as a problem, only count it against the 100-imperative budget.
## Sources
- Anthropic: *How Claude remembers your project* — <https://code.claude.com/docs/en/memory>. Load-bearing claims: "Claude Code reads CLAUDE.md, not AGENTS.md"; the `@AGENTS.md` interop example; size target <200 lines; `.claude/rules/` with `paths:` frontmatter; auto memory at `~/.claude/projects/<project>/memory/`; block-level HTML comments stripped before injection; `CLAUDE_CODE_NEW_INIT=1` interactive flow.
- Hosni, Youssef: *Level Up Your Claude Code with This CLAUDE.md* (Level Up Coding, Feb 2026). Source of the Workflow Orchestration framing and the 6 behavioral blocks. Accessible via friend link embedded in the article.
- HumanLayer (Kyle): *Writing a good CLAUDE.md* (Nov 2025) — <https://www.humanlayer.dev/blog/writing-a-good-claude-md>. Load-bearing claims: non-universal rules bias the model toward ignoring the whole file due to the `<system-reminder>` injected around CLAUDE.md; `@path` imports for progressive disclosure; Claude is not a linter.
- IFScale benchmark — <https://arxiv.org/html/2507.11538v1>. Empirical evidence that frontier LLMs peak around 150–200 instructions then degrade uniformly; load-bearing for the ~100 user-added imperative ceiling.
**Last Updated:** 2026-04-11
references/audit_scoring.md
<!-- SOURCE-OF-TRUTH: shared/references/audit_scoring.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->
# Audit Scoring Algorithm
Mandatory scoring contract for audit workers.
## Formula
```text
penalty = (critical x 2.0) + (high x 1.0) + (medium x 0.5) + (low x 0.2)
score = max(0, 10 - penalty)
```
## Weights
| Severity | Weight | Use for |
|----------|--------|---------|
| CRITICAL | 2.0 | Security vulnerabilities, data loss, RFC/standard violations |
| HIGH | 1.0 | Architecture violations, CVE dependencies, blocking bugs |
| MEDIUM | 0.5 | Best-practice violations, code smells, minor performance issues |
| LOW | 0.2 | Style issues, minor inconsistencies, cosmetic problems |
## Score Bands
| Score | Action |
|-------|--------|
| 10 | No action |
| 8-9 | Low-priority fixes |
| 6-7 | Next-sprint fixes |
| 4-5 | Prioritized fixes |
| 1-3 | Immediate action |
Optional diagnostic sub-scores (`compliance`, `completeness`, `quality`, `implementation`) are informational only; the primary `score` always uses the formula above.
---
**Version:** 2.0.0
**Last Updated:** 2026-03-01
references/audit_summary_contract.md
<!-- SOURCE-OF-TRUTH: shared/references/audit_summary_contract.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->
# Audit Summary Contract
Audit payload rules for 6XX workers using the evaluation-worker summary envelope. Coordinators consume JSON summaries first and read markdown reports only for detailed evidence.
## Envelope
Audit workers emit the shared evaluation-worker envelope:
```json
{
"schema_version": "1.0.0",
"summary_kind": "evaluation-worker",
"run_id": "ln-620-global-...",
"identifier": "global",
"producer_skill": "ln-621",
"produced_at": "2026-03-27T10:00:00Z",
"payload": {
"worker": "ln-621",
"status": "completed",
"operation": "auditing",
"warnings": [],
"audit": {}
}
}
```
Rules:
- `summary_kind` is `evaluation-worker`.
- `run_id` is mandatory; generate a standalone `run_id` when the caller does not pass one.
- `identifier` is stable inside the run and names the domain/target only.
- audit-specific fields live under `payload.audit`.
## Payload
Required `payload.audit` fields:
```json
{
"category": "Security",
"report_path": ".hex-skills/runtime-artifacts/runs/<run_id>/audit-report/ln-621--global.md",
"score": 8.5,
"issues_total": 3,
"severity_counts": {
"critical": 0,
"high": 1,
"medium": 2,
"low": 0
}
}
```
Allowed `payload.status`: `completed`, `skipped`, `error`. `complete` is invalid.
Optional audit fields: `diagnostic_scores`, `domain_name`, `scan_scope`, `metadata`.
## Paths
When `summaryArtifactPath` is passed, write the JSON summary to that exact path and managed filename, normally `{worker}--{identifier}.json`.
When absent, write to the standalone run-scoped path and optionally echo the same summary in structured output.
Canonical paths:
- managed: `.hex-skills/runtime-artifacts/runs/{parent_run_id}/evaluation-worker/{worker}--{identifier}.json`
- standalone: `.hex-skills/runtime-artifacts/runs/{run_id}/evaluation-worker/{worker}--{identifier}.json`
The JSON summary is the transport contract for scores, severity totals, category labels, and report location. The markdown report remains the evidence artifact for findings tables and extended data.
references/audit_worker_core_contract.md
<!-- SOURCE-OF-TRUTH: shared/references/audit_worker_core_contract.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->
# Audit Worker Core Contract
Hard envelope for audit workers that analyze one category and emit one markdown report plus one machine-readable summary.
## Inputs and Paths
Accepted inputs: `codebase_root`, `runId`, `output_dir`, `summaryArtifactPath`, `tech_stack`, `best_practices`, `domain_mode`, `current_domain`, `scan_path`.
Rules:
- `output_dir` is run-scoped runtime output, not public docs.
- Managed mode passes both `runId` and `summaryArtifactPath`.
- Standalone mode lets the worker runtime create the summary path.
- Domain-aware mode scans only `scan_path` and tags findings with `current_domain`.
## Required Runtime Refs
**MANDATORY READ:** Load `references/audit_summary_contract.md`, `references/audit_scoring.md`, and `references/templates/audit_worker_report_template.md`. Load evaluation runtime refs only when directly invoking that runtime.
## Execution Rules
- Report only unless fixes are explicitly allowed.
- Verify Layer 1 candidates before reporting.
- Use precise `file:line` locations when available.
- Apply worker-specific false-positive filters.
- Score with the shared formula.
- Write the markdown report once under `output_dir`.
- Write JSON summary to `summaryArtifactPath` or the standalone runtime path.
## Summary Payload
Minimum payload fields: `worker`, `status`, `operation=auditing`, `warnings`, `audit.category`, `audit.report_path`, `audit.score`, `audit.issues_total`, `audit.severity_counts`, optional `evidence_basis_counts`.
Default omitted finding evidence to `code_evidence`.
## Definition of Done
Input parsed; scan scope resolved; checks completed; findings include severity, location, recommendation, and effort; report and JSON summary written.
references/coordinator_summary_contract.md
<!-- SOURCE-OF-TRUTH: shared/references/coordinator_summary_contract.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->
# Coordinator Summary Contract
Runtime summary envelope for cross-skill routing. Domain fields live in the active family runtime or summary contract.
## Hard Rules
- Write summaries only under the active run output directory or the explicit caller-provided summary path.
- Never write outside `.hex-skills/runtime-artifacts/runs/{run_id}/` unless the active skill contract names another path.
- Resolve the target path before writing and reject absolute or traversal paths from user input.
- Include this envelope; add only active-family fields.
## Shared Envelope
Required fields:
```json
{
"schema_version": "1.0",
"run_id": "string",
"skill": "string",
"status": "completed|partial|failed|skipped",
"summary_type": "string",
"artifacts": [],
"findings": [],
"next_actions": []
}
```
Load only the active family contract for specialized fields.
references/environment_worker_runtime_contract.md
<!-- SOURCE-OF-TRUTH: shared/references/environment_worker_runtime_contract.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->
# Environment Worker Runtime Contract
Runtime contract for `ln-011` through `ln-015`.
Canonical phase/status names: `references/runtime_status_catalog.md`
## Runtime Family
- family: `environment-worker-runtime`
- terminal phases: `PAUSED`, `DONE`
- workers remain standalone-first
- managed mode requires both `runId` and `summaryArtifactPath`
## Manifest Fields
- all workers may receive `targets`, `dry_run`, `runId`, and `summaryArtifactPath`
- `ln-012` consumes `apply_ide_override`
- `ln-013` consumes `plugins` and `auto_install_providers`
## Summary Kinds
| Skill | Summary Kind |
|-------|--------------|
| `ln-011` | `env-agent-install` |
| `ln-012` | `env-mcp-config` |
| `ln-013` | `env-marketplace-align` |
| `ln-014` | `env-instructions` |
| `ln-015` | `env-cleanup` |
Payload shape follows `references/coordinator_summary_contract.md` environment worker rules.
## Guard Rules
- No transition without a checkpoint for the current phase.
- No `DONE` before a validated summary artifact is recorded.
- No `DONE` before self-check passes.
- Managed runs must write the summary to the exact caller-provided path.
- Standalone runs generate their own `run_id` and write to the family-scoped artifact path.
## Worker Independence
- Workers must not require coordinator runtime state.
- Workers may consume coordinator-provided manifests, but the public contract stays standalone-capable.
- Upward ownership stays out of worker public contracts.
---
**Version:** 1.0.0
**Last Updated:** 2026-04-10
references/mcp_tool_preferences.md
<!-- SOURCE-OF-TRUTH: shared/references/mcp_tool_preferences.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->
# Tool Preferences for Code Work
Compact hard rules for skills that materially inspect or edit repository code, config, scripts, or tests.
## Primary Policy
- Use `hex-line` first for repository text reads/search/edits when available.
- Use `hex-graph` first only for semantic code questions: symbol identity, references, architecture, edit blast radius, clone groups, or semantic diff risk.
- Use `hex-research` first only for project researchgraph questions: hypotheses, goals, benchmark runs, evidence, lineage, goal alignment, proposal readiness, or graph drift.
- Use built-in Read/Edit/Write/Grep/Glob or shell only when MCP is unavailable, unsupported, outside scope, or the task is shell-native.
- Do not use repo-wide shell search/read patterns when `hex-line` or `hex-graph` covers the task.
- Do not require `hex-graph` for docs, community, external research, runtime execution, profiling, benchmarking, or other work that does not depend on semantic code structure.
- Do not require `hex-research` unless the project has `docs/hypotheses/`, `docs/goals/`, or `benchmark/runs/*/manifest.yaml` and graph state can change the decision.
## Minimal Flow
| Need | Preferred flow |
|------|----------------|
| Discover files | `inspect_path` with a narrow path |
| Search text | `grep_search(output_mode="summary")`, then narrow before content mode |
| Read code | `outline` or targeted `read_file`; use edit-ready reads only before verified edits |
| Edit code | `read_file(edit_ready=true)` -> `edit_file(base_revision)` -> verify/check changes |
| Semantic risk | `index_project` -> symbol/architecture/edit-region analysis |
| Researchgraph status | `verify_index` -> targeted hypothesis/goal/run query or audit |
## Fallback Contract
Fallbacks are valid for Git history, builds, tests, package managers, containers, images, PDFs, notebooks, external websites, binary/media files, paths outside the project root, unsupported languages, unavailable MCP servers, missing researchgraph layout, or small markdown/metadata reads where MCP setup adds no value.
When falling back, keep the scope narrow and preserve the same evidence standard.
---
**Version:** 5.0.0
**Last Updated:** 2026-03-20
references/templates/agents_md_template.md
<!-- SOURCE-OF-TRUTH: shared/templates/agents_md_template.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->
# {{PROJECT_NAME}}
{{PROJECT_DESCRIPTION}}
<!-- SCOPE: Canonical machine-facing entry point with repo map, critical rules, command overview, and links to detailed documentation ONLY. -->
<!-- DOC_KIND: index -->
<!-- DOC_ROLE: canonical -->
<!-- READ_WHEN: Start here when you need the project map, local rules, or the next canonical document. -->
<!-- SKIP_WHEN: Skip when you already know the exact target document or code area. -->
<!-- PRIMARY_SOURCES: AGENTS.md, docs/README.md -->
## Quick Navigation
| Need | Read |
|------|------|
| Documentation map | [docs/README.md](docs/README.md) |
| Standards | [docs/documentation_standards.md](docs/documentation_standards.md) |
| Principles | [docs/principles.md](docs/principles.md) |
## Agent Entry
- Purpose: Canonical repo map and routing layer for agents.
- Read when: You need the project overview, local rules, or the next canonical doc.
- Skip when: You already know the exact file or document to inspect.
- Canonical: Yes.
- Read next: `docs/README.md`, then the relevant canonical doc for the task.
- Primary sources: `AGENTS.md`, `docs/README.md`.
## Critical Rules
| Category | Rule | When to Apply |
|----------|------|---------------|
| Documentation | Read the relevant canonical doc before editing a domain | Before making non-trivial changes |
| Navigation | Respect `SCOPE` and `Agent Entry` in each document | Before reading deep content |
| Task Management | Follow the provider in `.hex-skills/environment_state.json` | For all task operations |
| Language | Keep project code and documentation in English | For all written project artifacts |
| Research | Prefer configured official documentation sources | Before stack-specific decisions |
<!-- Optional Workflow Principles shard. When ENABLE_WORKFLOW_PRINCIPLES=true, replace the next line with the full content of references/templates/agents_md_workflow_principles.md. When false, leave the line as-is and it will be stripped from the rendered output. -->
{{WORKFLOW_PRINCIPLES_BLOCK}}
## Development Commands
| Task | Windows | Bash |
|------|---------|------|
| Install dependencies | {{INSTALL_WINDOWS}} | {{INSTALL_BASH}} |
| Run tests | {{TEST_WINDOWS}} | {{TEST_BASH}} |
| Start dev server | {{DEV_WINDOWS}} | {{DEV_BASH}} |
| Build | {{BUILD_WINDOWS}} | {{BUILD_BASH}} |
| Lint or format | {{LINT_WINDOWS}} | {{LINT_BASH}} |
## Maintenance
**Update Triggers:**
- When root navigation or canonical document links change
- When core commands change
- When critical project rules change
**Verification:**
- [ ] Links resolve
- [ ] Commands match current project setup
- [ ] Canonical docs listed here still exist
**Last Updated:** {{DATE}}
references/templates/agents_md_workflow_principles.md
<!-- SOURCE-OF-TRUTH: shared/templates/agents_md_workflow_principles.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->
<!-- Opt-in shard. Inserted into agents_md_template.md at {{WORKFLOW_PRINCIPLES_BLOCK}} when ENABLE_WORKFLOW_PRINCIPLES=true. Universal workflow rules only — anything harness-specific, project-specific, or path-scoped goes elsewhere. See references/agent_instructions_writing_guide.md for rationale. -->
## Workflow Principles
**Plan first.** For any task with 3+ steps or architectural impact, produce a written plan before implementing. If something goes sideways during execution, STOP and re-plan rather than patch forward.
**Verify before "done".** Never mark a task complete without evidence: diffs against main where relevant, passing tests, logs showing the new behavior. Ask yourself: "would a staff engineer approve this in review?"
**Demand elegance, not over-engineering.** For non-trivial changes, pause and ask "is there a more elegant approach?" If a fix feels hacky, rewrite it with what you now know. For simple fixes, skip this — don't invent complexity.
**Core principles.** Simplicity first · find root causes, no temporary patches · minimize blast radius, change only what's necessary.
references/templates/audit_worker_report_template.md
<!-- SOURCE-OF-TRUTH: shared/templates/audit_worker_report_template.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->
# Audit Worker Report Template
Markdown evidence envelope for audit workers. Coordinators consume JSON summaries first; this report supports the verdict.
## Path
Write once under `.hex-skills/runtime-artifacts/runs/{run_id}/audit-report/` using a stable name such as `{worker-id}-{slug}.md` or `{worker-id}-{slug}-{domain}.md`.
## Required Shape
```markdown
# {Category Name} Audit Report
<!-- AUDIT-META
worker: ln-62X
category: {Category Name}
domain: {domain_name|global}
scan_path: {scan_path|.}
score: {X.X}
total_issues: {N}
critical: {N}
high: {N}
medium: {N}
low: {N}
status: completed
-->
## Checks
| ID | Check | Status | Details |
|----|-------|--------|---------|
| {check_id} | {name} | {passed|failed|warning|skipped} | {brief evidence} |
## Findings
| Severity | Location | Issue | Principle | Recommendation | Effort |
|----------|----------|-------|-----------|----------------|--------|
| HIGH | path/file.ts:42 | What is wrong | Rule | How to fix | M |
```
## Optional Machine Blocks
Add only when consumed by the worker or coordinator: `FINDINGS-EXTENDED`, `DATA-EXTENDED`, or extra informational score fields. The primary penalty-based `score` remains canonical.
## Writing Rules
- Build the full report before writing; never leave partial reports.
- Sort findings by severity: CRITICAL, HIGH, MEDIUM, LOW.
- Keep recommendations actionable and effort as `S`, `M`, or `L`.
- Also write the JSON summary to the path required by `audit_worker_core_contract.md`.
---
**Version:** 2.0.0
**Last Updated:** 2026-02-15
references/templates/claude_md_template.md
<!-- SOURCE-OF-TRUTH: shared/templates/claude_md_template.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->
# {{PROJECT_NAME}}
<!-- SCOPE: Thin Claude Code projection of AGENTS.md via the @ import. AGENTS.md is the canonical source. Do not duplicate content here — add it to AGENTS.md instead, or scope it to `.claude/rules/*.md` with a `paths:` filter. -->
<!-- DOC_KIND: index -->
<!-- DOC_ROLE: derived -->
<!-- READ_WHEN: Loaded automatically by Claude Code at session start. -->
<!-- SKIP_WHEN: AGENTS.md is already imported, so do not re-read CLAUDE.md separately. -->
<!-- PRIMARY_SOURCES: AGENTS.md -->
@AGENTS.md
## Claude Code
- `/compact` preservation order: architecture decisions, modified files, verification status, open TODOs, tool outputs as summaries only.
- Auto memory is on by default. Claude writes learnings to `~/.claude/projects/<project>/memory/` — run `/memory` to inspect or edit.
- Scope path-specific rules to `.claude/rules/*.md` with a `paths:` frontmatter filter rather than inlining conditional "when working on X" blocks here.
- Nested `CLAUDE.md` files in subdirectories load on demand — prefer them for area-specific guidance over growing this root file.
references/worker_runtime_contract.md
<!-- SOURCE-OF-TRUTH: shared/references/worker_runtime_contract.md. Edit ONLY here; run `node tools/marketplace/shared.mjs sync` -->
# Worker Runtime Contract
Small deterministic runtime contract for stateful L3 workers.
## Runtime Files
Every stateful worker runtime uses:
- `manifest.json` for immutable invocation inputs
- `state.json` for mutable execution snapshot
- `checkpoints.json` for latest checkpoint per phase plus history
- `history.jsonl` for append-only runtime events
Terminal phases: `DONE`, `PAUSED`.
## Required Fields
`run_id`, `skill`, `identifier`, `phase`, `complete`, `paused_reason`, `pending_decision`, `final_result`, `resume_action`.
`resume_action` must be derived from `state.json` and checkpoints only, never from chat memory.
## Artifact Contract
Coordinator-invoked workers must receive `runId` and `summaryArtifactPath`, then write a validated summary artifact before `DONE`. Standalone workers may generate a run id and write the summary to the family-specific run-scoped path. Coordinators consume worker artifacts, not worker prose.
## Independence and Guards
- Workers depend only on shared contracts and their own domain inputs.
- Workers must not encode `Parent`, `Coordinator`, caller hierarchy, or upward orchestration state.
- No transition without a checkpoint for the current phase.
- No `DONE` before self-checks pass and the summary artifact is written.
- Public outputs and runtime artifacts stay separate.
## Family Contracts
Load the matching family contract only when it applies: environment worker, audit worker, task worker, quality worker, test planning, task planning, or planning worker.
---
**Version:** 1.0.0
**Last Updated:** 2026-04-06
SKILL.md
---
name: ln-014-agent-instructions-manager
description: "Creates AGENTS.md canonical and CLAUDE.md @AGENTS.md stub; audits token budget, cache safety, import-pattern compliance. Use when instruction files need alignment."
license: MIT
---
> **Paths:** All file refs relative to skills repo root.
# Agent Instructions Manager
**Type:** L3 Worker
**Category:** 0XX Shared
Creates missing instruction files and audits them (AGENTS.md, CLAUDE.md) for quality, consistency, and best practices. AGENTS.md is the single canonical source of content; CLAUDE.md is a thin `@AGENTS.md` import stub with bounded harness-specific deltas. This skill is the single owner of instruction-file creation and MCP Tool Preferences insertion or replacement.
**MANDATORY READ:** Load `references/coordinator_summary_contract.md`, `references/environment_worker_runtime_contract.md`, and `references/worker_runtime_contract.md`
**MANDATORY READ:** Load `references/mcp_tool_preferences.md`
**MANDATORY READ:** Load `references/agent_instructions_writing_guide.md` — canonical rationale for the `@AGENTS.md` import pattern, size budgets, and anti-patterns. All audit checks below trace back to this guide.
## Input / Output
| Direction | Content |
|-----------|---------|
| **Input** | project context, `dry_run` flag, optional `runId`, optional `summaryArtifactPath` |
| **Output** | Structured summary envelope with `payload.status` = `completed` / `skipped` / `error`, plus created files, audit findings, and warnings in `changes` / `detail` |
If `summaryArtifactPath` is provided, write the same summary JSON there. If not provided, return the summary inline and remain fully standalone. If `runId` is not provided, generate a standalone `run_id` before emitting the summary envelope.
## Runtime
Runtime family: `environment-worker-runtime`
Phase profile:
1. `PHASE_0_CONFIG`
2. `PHASE_1_DISCOVER_FILES`
3. `PHASE_2_CREATE_MISSING_FILES`
4. `PHASE_3_TOKEN_BUDGET_AUDIT`
5. `PHASE_4_PROMPT_CACHE_SAFETY`
6. `PHASE_5_CONTENT_QUALITY`
7. `PHASE_6_IMPORT_PATTERN_COMPLIANCE`
8. `PHASE_7_WRITE_SUMMARY`
9. `PHASE_8_SELF_CHECK`
Runtime rules:
- emit `summary_kind=env-instructions`
- standalone runs generate their own `run_id` and write the default worker-family artifact path
- managed runs require both `runId` and `summaryArtifactPath` and must write the summary to the exact provided path
- always write the validated summary artifact before terminal outcome
## Output Contract
Always build a structured `env-instructions` summary envelope per:
- `references/coordinator_summary_contract.md`
- `references/environment_worker_runtime_contract.md`
Payload fields:
- `files_found`
- `files_created`
- `quality_findings`
- `token_budget`
- `prompt_cache_safety`
- `import_pattern_status`
- `status`
## When to Use
- After editing any instruction file
- After adding/removing MCP servers or hooks
- Before release or publishing
- When sessions degrade (context bloat symptoms)
- First-time project setup (instruction files missing)
## Phase 1: Discover Files
Locate instruction files in target project:
| Agent | Primary | Canonical source | Fallback |
|-------|---------|------------------|----------|
| Claude Code | `CLAUDE.md` | imports `AGENTS.md` via `@AGENTS.md` | `.claude/settings.local.json` |
| Codex / Cursor / Amp / Factory | `AGENTS.md` | canonical | `.codex/instructions.md` |
Report: which files exist (`found` / `missing`), which harnesses share `AGENTS.md` directly vs via import.
## Phase 1b: Plugin Conflict Check
**Skip condition:** No `enabledPlugins` in settings OR all plugins are `@levnikolaevich-skills-marketplace`.
1. Read `~/.claude/settings.json` → parse `enabledPlugins`
2. Filter: enabled=true AND publisher ≠ `levnikolaevich-skills-marketplace`
3. For each external plugin:
- Resolve active install first: matching plugin or marketplace under `~/.claude/plugins/marketplaces/*`
- Read active `plugins/*/skills/*/SKILL.md` descriptions from that install surface
- Only if no active install is available, fall back to the latest cache snapshot under `~/.claude/plugins/cache/{publisher}/{plugin}/*/skills/*/SKILL.md`
- Treat cache as forensic fallback only. Never count multiple cache snapshots as separate active conflicts.
- Match against conflict signal keywords:
| Signal | Keywords in description | Overlap with |
|--------|----------------------|--------|
| Orchestration | "orchestrat", "pipeline", "end-to-end", "lifecycle" | ln-1000 pipeline |
| Planning | "plan.*implement", "brainstorm", "design.*spec" | ln-300 task coordinator |
| Execution | "execut.*plan", "subagent.*task", "task-by-task" | ln-400/ln-401 executors |
| Code review | "code.review.*dispatch", "review.*quality.*spec" | ln-402/ln-310 |
| Quality gate | "quality.*gate", "verification.*complet", "test-driven.*always" | ln-500 quality gate |
| Debugging | "systematic.*debug", "root.*cause.*phase" | problem_solving.md |
| Git isolation | "worktree.*creat", "git.*isolat" | git_worktree_fallback.md |
- Check for `hooks/session-start` directory in the active install surface first
4. Score: 2+ signal categories → CONFLICT. 1 → WARN. 0 → safe
5. CONFLICT: `"CONFLICT: {plugin} overlaps with ln-* pipeline ({signals}). Disable?"` → AskUserQuestion → if yes, set to `false` in settings.json
6. WARN: report, continue
## Phase 2: Create Missing Files
**Skip condition:** All files exist OR `dry_run == true` (report what would be created).
**Canonical model:** AGENTS.md is the single source of content. CLAUDE.md is an `@AGENTS.md` import stub with bounded harness-specific deltas. Create in this order so the stub references a file that already exists.
### Step 2a: Detect Project Context
| Field | Source | Fallback |
|-------|--------|----------|
| PROJECT_NAME | `package.json` → `name` | `basename(cwd)` |
| PROJECT_DESCRIPTION | `package.json` → `description` | `[TBD: Project description]` |
| DATE | current date (YYYY-MM-DD) | — |
| ENABLE_WORKFLOW_PRINCIPLES | Caller input (default `false`) | — |
### Step 2b: Create AGENTS.md (if missing) — canonical
1. **MANDATORY READ:** Load `plugins/documentation-pipeline/skills/ln-111-root-docs-creator/references/templates/agents_md_template.md`
2. Replace `{{PROJECT_NAME}}`, `{{PROJECT_DESCRIPTION}}`, `{{DATE}}`, and `{{DEV_COMMANDS_*}}` placeholders
3. If `ENABLE_WORKFLOW_PRINCIPLES=true`: replace `{{WORKFLOW_PRINCIPLES_BLOCK}}` with the full content of `plugins/documentation-pipeline/skills/ln-111-root-docs-creator/references/templates/agents_md_workflow_principles.md`. Otherwise strip the placeholder line and its leading HTML comment.
4. Mark remaining `{{...}}` as `[TBD: placeholder_name]`
5. Write to target project root
### Step 2c: Create CLAUDE.md (if missing) — import stub
1. **MANDATORY READ:** Load `plugins/documentation-pipeline/skills/ln-111-root-docs-creator/references/templates/claude_md_template.md`
2. Replace `{{PROJECT_NAME}}` only
3. Write to target project root
4. Verify the file contains exactly one `@AGENTS.md` line and is ≤50 lines total
5. Do NOT copy any content from AGENTS.md into CLAUDE.md — the `@` import handles it at session load time
### Step 2e: Report Creations
List each created file with its source (template `agents_md_template.md`, template `claude_md_template.md` stub).
## Phase 3: Token Budget Audit
Line-count budgets align with the Anthropic official target (`<200 lines per CLAUDE.md file`) and the IFScale instruction-ceiling research. See `references/agent_instructions_writing_guide.md` for the full rationale.
| Check | Pass | Warn | Fail |
|-------|------|------|------|
| AGENTS.md line count | ≤150 | 151-200 | >200 |
| CLAUDE.md line count (stub) | ≤20 | 21-50 | >50 |
| User-added imperative count in AGENTS.md | ≤100 | 101-150 | >150 |
**Imperative counter:** lines matching `^\s*- ` inside rule sections, plus any line containing `MUST\|NEVER\|ALWAYS\|DO NOT`. Cite the IFScale benchmark (arxiv 2507.11538) in WARN / FAIL messages.
Report table per file with line count and imperative count (for AGENTS.md).
## Phase 4: Prompt Cache Safety
Check each file for content that breaks prefix-based prompt caching:
| # | Check | Pattern | Severity |
|---|-------|---------|----------|
| 1 | No timestamps | `grep -E '\d{4}-\d{2}-\d{2}.\d{2}:\d{2}'` | WARN |
| 2 | No dates in content | `grep -E '(January|February|March|today|yesterday|Last Updated:)'` except `**Last Updated:**` at file end | WARN |
| 3 | No dynamic counts | `grep -E '\d+ skills\|\d+ tools\|\d+ servers'` (hardcoded counts change) | WARN |
| 4 | No absolute paths | `grep -E '[A-Z]:\\|/home/|/Users/'` (machine-specific) | INFO |
| 5 | Stable structure | No conditional sections (`if X then include Y`) | INFO |
## Phase 5: Content Quality
| # | Check | Pass | Fail |
|---|-------|------|------|
| 1 | Has build/test commands | Found `npm\|cargo\|pytest\|dotnet` commands in AGENTS.md | Missing — add essential commands |
| 2 | No abstract principles | No `"write quality code"`, `"follow best practices"` | Found vague instructions |
| 3 | No redundant docs | No API docs, no full architecture description | Found content discoverable from code |
| 4 | Has hard boundaries | Found `NEVER\|ALWAYS\|MUST\|DO NOT` rules in AGENTS.md | Missing explicit prohibitions |
| 5 | Compact Instructions section | `## Compact Instructions` present in AGENTS.md with preservation priorities | Missing — sessions lose decisions on /compact |
| 6 | MCP Tool Preferences | Canonical policy section in AGENTS.md matches `references/mcp_tool_preferences.md` | Missing or outdated — agents use suboptimal tools |
| 7 | No tool output examples | No large code blocks or command outputs | Found — bloats every turn |
Checks #1–#6 evaluate AGENTS.md only because CLAUDE.md inherits that content via the `@AGENTS.md` import. Checks on the delta itself live in Phase 6.
### Phase 5b: Auto-fix Fixable Issues
For each FAIL in Phase 5, attempt auto-fix before reporting:
**Before any auto-fix insertion:**
1. Verify insertion point exists (exact heading found at specific line)
2. If ambiguous (heading not found) — WARN and skip (report as manual fix needed)
3. After insertion — verify no duplicate `## Compact Instructions` or `## MCP Tool Preferences` sections exist in the file
| # | Issue | Fix | Skip when |
|---|-------|-----|----------|
| 5 | Missing Compact Instructions | Insert `## Compact Instructions` section before `## Navigation` in AGENTS.md | `dry_run: true` |
| 6 | Missing or outdated MCP Tool Preferences | Insert or replace section in AGENTS.md from `references/mcp_tool_preferences.md` | `dry_run: true` |
| 1 | Missing build/test commands | WARN only (project-specific, cannot auto-generate) | -- |
| 2 | Abstract principles found | WARN only (requires human judgment) | -- |
**Compact Instructions template** (insert in AGENTS.md before `## Navigation` or after last rules section):
```markdown
## Compact Instructions
Preserve during /compact: [Critical Rules], [MCP Tool Preferences table],
[Navigation table], [language/communication rules], [hard boundaries (NEVER/ALWAYS)].
Drop examples and explanations first.
```
Because CLAUDE.md `@AGENTS.md`, the preservation list propagates to Claude Code. The harness-specific terminology (`/compact` vs context compression) lives in the stub delta.
## Phase 6: Import Pattern Compliance
AGENTS.md is the canonical source per `DOC_ROLE` metadata. CLAUDE.md must be a thin `@AGENTS.md` import stub with bounded harness-specific deltas.
| # | Check | Pass | Fail |
|---|-------|------|------|
| 1 | CLAUDE.md has `@AGENTS.md` import | Exactly one `@AGENTS.md` line present | Missing or multiple — FAIL |
| 2 | CLAUDE.md delta bounded | Total file ≤50 lines | >50 lines — FAIL with drift report |
| 3 | No content duplication | No section or rule from AGENTS.md reappears in CLAUDE.md | Duplicate found — FAIL, name the specific overlapping lines |
**Drift resolution rule:** AGENTS.md is the canonical source. For each inconsistency:
- (a) If content is missing from AGENTS.md but present in CLAUDE.md → move it to AGENTS.md, then remove from the stub.
- (b) If CLAUDE.md duplicates AGENTS.md content → replace with a single `@AGENTS.md` import line.
- (c) If the stub delta exceeds 50 lines → split genuinely harness-specific content into `.claude/rules/*.md`; everything else moves to AGENTS.md.
**Do not** "suggest which file is source of truth" based on content volume — AGENTS.md is always the source.
If `.hex-skills/environment_state.json` reports `agents.codex.discovery_violation=true`, emit a WARN that Codex skill discovery is drifted and duplicate skill counts from stale cache must not be used as evidence during instruction audits until `ln-013-config-syncer` repairs the marketplace/plugin alignment.
If `.hex-skills/environment_state.json` reports `agents.codex.permissions_default_ready=false`, emit a WARN that Codex CLI startup permissions are drifted from the managed default and instruction audits must not assume full-access startup semantics until `ln-013-config-syncer` repairs `~/.codex/config.toml`.
## Phase 7: Report
```
Agent Instructions Manager:
Created: (omit section if nothing created)
- AGENTS.md (from template, context from package.json)
- CLAUDE.md (import stub)
Audit:
| File | Lines | Imperatives | Cache-safe | Quality | Import pattern | Issues |
|------------|-------|-------------|------------|---------|----------------|--------|
| AGENTS.md | 118 | 47 | OK | 7/7 | n/a | OK |
| CLAUDE.md | 13 | 0 | OK | 7/7 | OK | OK |
Import pattern: OK (or N drift issues listed)
Recommendations:
1. Run /init (ln-100) for full context-aware AGENTS.md with project-specific rules
```
**Cross-agent note:** Codex CLI 0.120 (2026-04-11) now supports `SessionStart` hook with `/clear` vs fresh/resume distinction, matching Claude Code behavior.
## Definition of Done
- [ ] All instruction files discovered
- [ ] Missing files created (AGENTS.md from template first; CLAUDE.md as `@AGENTS.md` import stub second)
- [ ] Token budget within limits: AGENTS.md ≤200 lines, CLAUDE.md ≤50 lines, AGENTS.md imperative count ≤150
- [ ] No prompt cache breakers found (or reported as WARN)
- [ ] Content quality checks passed on AGENTS.md (or issues reported)
- [ ] Auto-fixable issues resolved in AGENTS.md (Compact Instructions, MCP Tool Preferences) or reported if dry_run
- [ ] Import pattern compliance verified: CLAUDE.md contains exactly one `@AGENTS.md` line and no duplicated AGENTS.md content
- [ ] Report generated with creation log, drift findings, and actionable recommendations
- [ ] No conflicting external plugins detected (or user confirmed keep)
- [ ] Structured summary returned
- [ ] Summary artifact written to the managed or standalone runtime path
**Critical Rule: Non-destructive file edits.** Auto-fix inserts sections at verified positions only. Never rewrite the entire instruction file. Preserve all existing content outside the inserted section.
**Version:** 2.2.0
**Last Updated:** 2026-03-25