Claude Skill

agents-brain

Imported from paulrberg/agent-skills/skills/agents-brain.

LLM Mart · 0 points · 0 views 2 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download paulrberg-agent-skills-skills_agents-brain-913232a.zip · 14 KB
Part of paulrberg/agent-skills — 42 skills

Install

skills CLI npx skills add https://github.com/PaulRBerg/agent-skills/tree/main/skills/agents-brain
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install paulrberg-agent-skills@llmmart
Git git clone https://github.com/PaulRBerg/agent-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole paulrberg/agent-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

Agents Brain

If these instructions are already present in the conversation from a slash or dollar invocation, follow them directly; do not invoke this skill again through a skill tool.

Create or polish repo-local context as one coherent system: human-facing README.md files, agent-facing AGENTS.md files (with companion CLAUDE.md symlinks only for pre-native Claude Code, per Claude Code Compatibility below), existing project-installed skills under .agents/skills, eligible source-catalog skills under skills/<name>/, and context docs — any other Markdown files, under any name or directory, whose content is durable guidance for agents or humans, such as conventions, command catalogs, data-format rules, workflow runbooks, and reference material.

Success means every selected target is grounded in repository evidence, respects its audience and scope, spends agent context only on guidance that changes behavior, and passes the narrowest repository-defined validation. Stop after reporting completed or planned changes, validation, and any blockers.

Model and Context Optimization

Optimize skills and other agent-facing context for GPT-6.1 Sol and Claude Opus 5.5 while preserving README.md as clear human-facing documentation. Before complex, long-running, multi-tool, or orchestration-heavy context work, resolve scripts/fetch-guidance.sh relative to this skill directory, run it once for gpt-6.1-sol and once for claude-opus-5-5, and read both returned files completely. The helper retrieves the official GPT-6.1 Sol prompting guidance and Claude Opus 5.5 prompting guidance because their recommendations may evolve. OpenAI publishes Sol guidance in the shared GPT-6 guide; evaluate its family-wide prompting recommendations on GPT-6.1 Sol. Simple context work does not require either guide.

Accept an integrity-valid cached guide for 24 hours. Use --refresh for explicitly latest or change-sensitive work, materially disputed guidance, or conflicts with observed model behavior. Interpret helper diagnostics precisely:

  • cached reused a guide validated no more than 24 hours ago without network access.
  • revalidated refreshed validation metadata after a successful conditional 304 response.
  • fetched atomically replaced the cache with integrity-valid content from the pinned official URL.
  • stale reused a guide validated no more than seven days ago after live retrieval failed. Proceed only after reading it and disclose the validation timestamp and retrieval failure under open issues and caveats.

Forced refreshes, expired entries, integrity failures, and unexpected redirects fail closed. If either required guide cannot be returned, stop qualifying work before writing instead of substituting memory or another source. Never create the cache in a repository or skill installation.

Keep only content that changes a decision, prevents an evidenced mistake, or supplies a non-discoverable constraint. State each meaning once at the narrowest reliable load scope, except where independently installed artifacts need to stay self-contained. Preserve authority, safety, material exceptions, semantic success criteria, and exact machine-consumed text. Documentation-only authority does not permit changing helpers or schemas; report an extraction opportunity instead.

Choose a Workflow

Choose exactly one workflow and read only its reference.

For skill creation, first inspect applicable repository instructions. When they define a source catalog and lifecycle, stop and follow that repository-owned workflow. Use skill-writing only when no catalog-specific workflow exists.

User intent Workflow Reference
Update, refresh, sync, prune, polish, repair, or fix context polish references/polish.md
Create, initialize, generate, or regenerate context files create references/create-docs.md
Audit, check, review, inspect, or suggest changes without edits polish in --dry-run mode references/polish.md
Create or scaffold a skill Stop Use repository catalog lifecycle or skill-writing
Install, discover, remove, or rename a skill Stop Use a dedicated skill-management workflow

If the intent is unclear, select polish in --dry-run mode and report the smallest useful planned change set.

Authority

  • Apply explicit user instructions and established authorization before this skill's defaults. Do not ask again for an unchanged decision; preserve host restrictions and required destructive-action approval.
  • Explicit create, update, polish, repair, fix, or equivalent intent authorizes in-scope local writes. Inspection-only intent and --dry-run do not.
  • Require explicit confirmation before deleting README.md, AGENTS.md, regular CLAUDE.md files, or context-doc targets. --force authorizes documented overwrites, not deletions. The one standing exception is a CLAUDE.md symlink to a sibling AGENTS.md when the installed Claude Code reads AGENTS.md natively (see Claude Code Compatibility): delete it without asking.
  • Resolve scope from the requested outcome. Preview a large change set, then continue when it is already authorized; file count alone is not an approval boundary. Ask only when an unresolved choice changes scope or intended meaning.
  • Do not expand from documentation work into source changes, skill creation, or external writes.

Complete authorized discovery, edits, and validation before reporting completion. When one target needs input, continue independent targets and identify the exact unresolved choice. If a skill rule requires a pause, cite that rule and explain why existing authorization does not cover the next action.

Arguments

  • path: Optional repo-relative subtree. Restrict documentation, package-root, project-skill, source-catalog skill, and context-doc discovery to that subtree.
  • target ...: Optional filters during polish: skill names from existing .agents/skills/<name>/ or eligible skills/<name>/ trees, or repo-relative Markdown paths selecting specific context docs.
  • --root-only: Select only root README.md, AGENTS.md, and CLAUDE.md targets. Exclude project-installed skills, source-catalog skills, and context docs unless explicitly selected by target.
  • --dry-run: Report planned writes and concise diffs without changing files.
  • --preserve: During polish, keep accurate user-authored prose and structure; fix only drift and obvious noise.
  • --minimal: Produce the smallest context that still meets the completion bar.
  • --thorough / --full: Perform deeper analysis only where it adds durable, repository-specific context.
  • --force: During create, regenerate existing README.md or AGENTS.md targets without prompting. Never applies to skills or deletions.

If --minimal and --thorough / --full are both present, make no writes and ask the user to choose. Report unrecognized flags; continue only when they cannot change scope, safety, or write behavior.

Repository Guard Rail

Run before discovery or writes:

cwd="$(pwd -P)"
case "$cwd" in
  /) printf 'abort: refusing to run at the filesystem root\n' >&2; exit 1 ;;
esac
repo_root="$(git rev-parse --show-toplevel 2>/dev/null)" || {
  printf 'abort: not inside a git repository\n' >&2; exit 1; }
managed_skill_root=
case "$repo_root" in
  /|"$HOME") printf 'abort: unsupported repo root: %s\n' "$repo_root" >&2; exit 1 ;;
  "$HOME/.agents"|"$HOME/.codex"|"$HOME/.claude") managed_skill_root="$repo_root/skills" ;;
  "$HOME/.agents/"*|"$HOME/.codex/"*|"$HOME/.claude/"*)
    printf 'abort: repo root is nested under an agent configuration repository: %s\n' "$repo_root" >&2; exit 1 ;;
esac
if [ -n "$managed_skill_root" ]; then
  case "$cwd" in
    "$managed_skill_root"|"$managed_skill_root/"*)
      printf 'abort: installed skills must be edited in their source catalog: %s\n' "$cwd" >&2; exit 1 ;;
  esac
fi

When managed_skill_root is set, allow README.md, AGENTS.md, and CLAUDE.md work elsewhere in that repository, but exclude the entire installed skills/ tree from every workflow. Apply the exclusion before discovery, canonicalization, or symlink traversal. If path, a target, or an explicit request would enter that tree, make no writes there and report that the skill must be edited in its source catalog. --force does not override this boundary.

Outside managed agent-config roots, eligible git-tracked skills/<name>/ source catalogs are in scope for polish per references/polish.md.

Claude Code Compatibility

Claude Code v2.1.277 and later read AGENTS.md directly whenever no CLAUDE.md, .claude/CLAUDE.md, or CLAUDE.local.md exists in the working directory or above it, so a CLAUDE.md symlink is no longer needed. Detect the installed version once per run before either workflow touches CLAUDE.md:

claude_version=$(claude --version 2>/dev/null | awk '{ print $1; exit }')
agents_md_native=false
if [ -n "$claude_version" ] &&
  [ "$(printf '%s\n' 2.1.277 "$claude_version" | sort -V | head -n 1)" = 2.1.277 ]; then
  agents_md_native=true
fi

When agents_md_native=true:

  • Do not create CLAUDE.md symlinks.
  • Delete every CLAUDE.md that is a symlink resolving to its sibling AGENTS.md, in the same pass and across the whole selected tree, using git rm when tracked. Leave regular CLAUDE.md and CLAUDE.local.md files untouched and report them: any such file at or above the repository root still suppresses direct AGENTS.md loading unless the user sets Project instructions to claude-md-and-agents-md in /config.

When claude is missing or older, keep the pre-native behavior: create or refresh a sibling symlink only where CLAUDE.md is missing or already a symlink, and never delete one.

Snapshot git status --short before broad edits. Preserve unrelated pre-existing changes and re-check expected paths after generators or broad commands.

Discovery and Tool Routing

Use git-aware discovery, canonicalize every candidate beneath repo_root, and exclude VCS, dependency, environment, and build outputs. Deliberately include ignored .agents/skills/*/SKILL.md only when project skills are selected. Discover git-tracked, non-ignored, non-symlinked skills/*/SKILL.md only outside managed agent-config roots and only when source-catalog skills are selected. Parse each selected skill's YAML frontmatter. Inspect only a project-installed skill's declared write boundary before deciding whether it qualifies for a coordination exemption. Prefer fd, fall back once on suspiciously narrow results, and synthesize independent repository evidence before writing.

Discover context docs by following Markdown links from README.md, AGENTS.md, CLAUDE.md, and SKILL.md files, then by scanning remaining tracked Markdown whose content qualifies. Classify by content, never by file name or location. Exclude changelogs, licenses, legal and policy notices, generated or vendored documentation, and prose that is product content rather than guidance. When classification is uncertain, leave the file out of scope and report it as a candidate.

Completion and Report

After writes, run repository-defined Markdown formatting or checks when present. If skill frontmatter or agents/openai.yaml changed in a project-installed skill, run its invocation metadata check. Verify that no CLAUDE.md symlink remains when agents_md_native=true, and that every retained or created symlink resolves to its sibling AGENTS.md otherwise. In --dry-run, report commands that would depend on planned files instead of running them.

Lead with ### ✅ Context updated only after writes and required validation pass, ### ⚠️ Context updated — validation failed when files were written but required checks fail, ### 🔎 Context preview — no files written in dry-run mode, or ### ⛔ Context blocked — no files written for a pre-write stop. Follow with the workflow and scope, material changes, exact validation commands and outcomes, and any remaining limitation. Use short prose for a small change; add headings or tables only when they organize repeated information, and a tree only when directory ownership matters. Follow the user's requested report format.

When issues need a separate section, group verified fixes with evidence as Resolved and remaining problems as Open, with impact and next action. Omit empty groups and report each item once. Reserve blocker for something preventing required work and risk for a specific potential adverse outcome. A workaround leaves the underlying issue open.

Keep paths, commands, guard-rail errors, symlink targets, and user-authored content exact and undecorated. Omit empty detail and stop once the selected targets meet the completion bar.

References

  • polish: read references/polish.md.
  • create: read references/create-docs.md.
Files (agent-skills)
  • agents
    • openai.yaml 42 B
      policy:
        allow_implicit_invocation: true
      
  • references
    • create-docs.md 4.7 KB
      # Create Docs Workflow
      
      Create missing README.md and AGENTS.md context from repository evidence. Regenerate existing targets only with `--force`
      or an equally explicit overwrite instruction. Create other context docs only on explicit request. Never create skills.
      
      Success means each selected package root has the requested human and agent context, CLAUDE.md handling matches the
      installed Claude Code (see Claude Code Compatibility in SKILL.md), and generated claims pass repository-defined
      validation.
      
      ## Select Targets
      
      Package roots are the repository root and directories containing one of these manifests:
      
      - `package.json`
      - `Cargo.toml`
      - `pyproject.toml`
      - `setup.py`
      - `go.mod`
      - `foundry.toml`
      - `Gemfile`
      - `composer.json`
      
      Create README.md only at package roots. Create package-root AGENTS.md files there as well. Apply `path` and
      `--root-only` before analyzing targets.
      
      Nested AGENTS.md files may also be created when the user explicitly requests broad context creation and a subtree has a
      distinct command runner, generated-file boundary, ownership rule, deployment or data constraint, safety requirement, or
      review workflow. Otherwise, report the recommendation without writing it. Never create README.md in an arbitrary leaf
      directory.
      
      For each selected target, classify README.md, AGENTS.md, and CLAUDE.md as missing, reusable, safely replaceable, or
      blocked. Without overwrite authority, skip existing README.md and AGENTS.md files and report them; do not silently route
      them through `polish`.
      
      ## Ground the Content
      
      Derive claims from the nearest manifests and metadata, task runners, lock files, CI and lint configuration,
      generated-file notices, and relevant source boundaries. Use a user-provided description when present, but verify any
      factual claims it adds.
      
      Do not invent project purpose, badges, links, commands, conventions, ownership, or safety rules. When evidence is
      missing, narrow the generated document instead of guessing.
      
      ## Generate README.md
      
      Keep README.md human-facing:
      
      - Add a title and short factual description.
      - Add only verified documentation, homepage, demo, package, changelog, citation, funding, reference, or license links
        that materially help readers.
      - Add a short contributing pointer to sibling AGENTS.md.
      - Include a short operator-run setup guide only for dotfiles, infrastructure, homelab, personal tooling, or an explicit
        setup request.
      
      Do not add developer command inventories, directory trees, configuration manuals, contribution rules, marketing copy, or
      placeholders.
      
      ## Generate AGENTS.md
      
      Keep AGENTS.md concise, imperative, and scoped:
      
      - Name the stack and preferred package manager only when useful for choosing commands.
      - Include commands whose runner, order, side effects, environment, or failure behavior matters.
      - Include non-obvious architecture, style, naming, generated-file, ownership, safety, external-disclosure, credential,
        deployment, financial, recipient-scoped data-handling, and review constraints supported by evidence.
      - Exclude generic tool tutorials, long directory trees, and package-script inventories that add no preference or
        warning.
      
      Parent files hold shared defaults; nested files contain only local deltas.
      
      ## Handle CLAUDE.md
      
      Run the version check from Claude Code Compatibility in SKILL.md. When `agents_md_native=true`, create no CLAUDE.md
      symlinks and delete any existing symlink to a sibling AGENTS.md in the selected tree. Otherwise, create a sibling
      compatibility symlink for each created AGENTS.md:
      
      ```sh
      (cd "$dir" && ln -sfn AGENTS.md CLAUDE.md)
      ```
      
      Write only when CLAUDE.md is missing or already a symlink. A regular CLAUDE.md blocks only that symlink target; leave it
      untouched and report the conflict.
      
      ## Create Context Docs on Request
      
      Create a Markdown context doc outside the default set — a conventions file, command catalog, data-format reference, or
      workflow runbook — only when the user explicitly names its path and purpose. Ground its content in repository evidence
      like any other target, keep it scoped to that purpose, and link it from the nearest AGENTS.md or README.md when that
      improves discoverability. Do not scan for missing context docs; at most report a recommendation without writing it.
      
      ## Handle CONTRIBUTING.md
      
      Never edit CONTRIBUTING.md. If it exists next to a target, put only stable, relevant contribution guidance in AGENTS.md
      and advise the user to merge any remaining useful instructions manually before deleting CONTRIBUTING.md.
      
      ## Finish
      
      Run the completion checks and use the report contract from SKILL.md. In dry-run mode, show selected paths and concise
      section-level previews or diffs. Stop after the requested files are created or regenerated and validated; do not polish
      unrelated existing context.
      
    • polish.md 9.3 KB
      # Polish Workflow
      
      Update existing context for factual accuracy, useful placement, and lower noise. Do not create README.md, AGENTS.md,
      context docs, or skills, and do not broadly restyle accurate user-authored content.
      
      Success means each changed claim is verified against the repository, each instruction lives at the narrowest useful
      scope, and no unrelated content or user work is disturbed.
      
      ## Discover and Inspect
      
      Select existing README.md and AGENTS.md files, sibling CLAUDE.md entries, in-scope context docs, and any in-scope
      existing skill targets under `.agents/skills/<name>/` or eligible `skills/<name>/` trees. Apply `path`, `--root-only`,
      and `target` filters before reading deeply.
      
      Use the nearest manifests, task runners, lock files, lint and CI configuration, generated-file notices, and relevant
      source files to verify claims. Check paths, commands, scripts, recipes, environment variables, ownership rules, default
      branches, and local conventions.
      
      Detect CONTRIBUTING.md next to documentation targets. Never edit it; advise the user when stable agent guidance should
      move into sibling AGENTS.md.
      
      Preview unexpectedly large target sets against the requested outcome. Continue within existing authorization; ask only
      before adding outcomes or changing meaning the user has not authorized, not merely because many files are involved.
      
      ## Context Economy Audit
      
      Before applying the file-specific decisions below, classify each agent-facing target by how it enters context: always
      loaded, inherited through a scope chain, conditional or path-scoped, or independently loaded on demand.
      
      - For every retained block, identify the decision it changes, the mistake it prevents, or the non-discoverable fact it
        supplies. Remove generic defaults, tutorials, history, inventories, stale rationale, and other prose with no durable
        behavioral effect.
      - Remove exact and semantic duplication from the same effective load chain. Put shared meaning in the parent and keep a
        child to its delta or override; do not deduplicate independently loaded artifacts when that would break
        self-containment.
      - Replace equivalent lists of prohibitions with one positive decision rule. Retain rationale only when it changes how a
        rule is interpreted, and retain one minimal example only for an exact requirement or an evidenced failure.
      - Route specialized guidance to the deepest existing applicable context or an existing on-demand doc or skill. When no
        suitable target exists, recommend creation through the `create` workflow instead of creating or moving files here.
      - Preserve authority, safety, material exceptions, semantic completion criteria, exact commands and machine-consumed
        text, and clarity. Re-read the effective load chain after pruning to ensure no required constraint is orphaned or
        contradicted.
      
      ## README.md Decisions
      
      Keep README.md useful to humans browsing the repository, package registry, or project page:
      
      - Preserve an accurate project description, badges, documentation and package links, references, acknowledgments,
        funding, and license information.
      - Keep a short contributing pointer to sibling AGENTS.md.
      - Keep short operator-run setup instructions only for dotfiles, infrastructure, homelab, personal tooling, or when the
        user explicitly requests them.
      - Move developer commands, architecture constraints, review rules, configuration manuals, and contribution workflow into
        AGENTS.md when they provide durable value there.
      - Remove directory trees, command inventories, placeholders, and generic explanations that are cheaply discoverable or
        add no decision guidance.
      
      With `--preserve`, retain accurate custom prose and structure. Make the smallest edit that restores truth or correct
      placement.
      
      ## AGENTS.md Decisions
      
      Keep AGENTS.md terse, imperative, repository-specific, and scoped to its directory tree:
      
      - Preserve commands when their preferred order, runner, side effects, environment, or failure behavior matters.
      - Preserve non-obvious architecture, style, naming, review, generated-file, safety, external-disclosure, credential,
        deployment, financial, and recipient-scoped data-handling constraints.
      - Preserve speed traps, flaky checks, shell quirks, migration constraints, and external-system notes that prevent
        observed mistakes.
      - Remove generic tutorials, historical authoring notes, file inventories, lists of installed skills, and command lists
        with no preference or warning.
      
      Move subtree-specific rules to the deepest common ancestor where they apply. Promote duplicated child guidance only when
      every affected child shares it. Recommend a missing nested AGENTS.md only for a distinct command, safety rule,
      generated-file boundary, ownership rule, data constraint, or review requirement; route actual creation through the
      `create` workflow.
      
      Never delete an empty or obsolete AGENTS.md automatically. Report it as a deletion candidate, together with any sibling
      CLAUDE.md symlink, and require explicit confirmation.
      
      ## CLAUDE.md Decisions
      
      Run the version check from Claude Code Compatibility in SKILL.md.
      
      When `agents_md_native=true`, delete every CLAUDE.md in the selected tree that is a symlink resolving to its sibling
      AGENTS.md (`git rm` when tracked), without confirmation. Also retire repository checks, hooks, and instructions that
      require the symlink, and report any remaining regular CLAUDE.md or CLAUDE.local.md that still suppresses direct
      AGENTS.md loading.
      
      Otherwise, create or refresh a sibling symlink only when CLAUDE.md is missing or already a symlink:
      
      ```sh
      (cd "$dir" && ln -sfn AGENTS.md CLAUDE.md)
      ```
      
      Before writing, require `test -L "$dir/CLAUDE.md" || test ! -e "$dir/CLAUDE.md"`. A regular CLAUDE.md blocks only that
      target; leave it untouched and report the conflict.
      
      After changing placement or symlinks, rediscover affected targets and confirm no local constraint was orphaned.
      
      ## Context Doc Decisions
      
      Polish selected context docs — conventions, command catalogs, data-format rules, workflow runbooks, and similar
      reference material — wherever they live and whatever they are named:
      
      - Verify commands, paths, flags, formats, environment variables, versions, and rules against the repository with the
        same rigor as AGENTS.md.
      - When repository instructions assign a document class to a repository-owned lifecycle or workflow, fix only factual
        drift in those docs and report structural or placement changes as recommendations.
      - Preserve each doc's audience, depth, structure, and voice; a deep reference stays a deep reference. Do not compress it
        to AGENTS.md terseness or inline it into AGENTS.md.
      - Fix broken links between context docs, README.md, AGENTS.md, and skills. Do not move or rename docs.
      - Recommend relocating guidance only when it is clearly misplaced, such as stable repo-wide rules living solely in a
        deep doc nothing links to; perform the move only with explicit confirmation.
      - Report an obsolete doc whose central subject no longer exists as a deletion candidate; never delete or hollow it out.
      
      ## Skill Decisions
      
      Polish only these existing skill classes:
      
      - Project-installed skills under `.agents/skills`. A minimal factual fix may touch SKILL.md or its existing bundled
        files.
      - Source-catalog skills under `skills/<name>/` when `SKILL.md` is git-tracked, the tree is neither ignored nor
        symlinked, and the repository root is neither a managed agent-config root nor nested under one, as enforced by the
        Repository Guard Rail. Edit only the SKILL.md body and existing bundled Markdown, such as files under `references/`.
      
      Never create, delete, or rename skill or bundled files, or change a skill's purpose or structure.
      
      For a project-installed skill:
      
      - Confirm frontmatter parses and `name` matches the directory. Fix only mechanical, unambiguous drift.
      - Classify its declared default write boundary. If it writes no repository files or only repository metadata, add
        `coordination: exempt` when absent. Add the standard body sentence near the top:
        `This skill is coordination-exempt: skip the ai-coord gate for its declared work.` Explicitly authorized escalation
        beyond that declared behavior enters the gate.
      - Otherwise, omit `coordination`; remove a stale `coordination: exempt` field and its matching standard body sentence
        when repository evidence establishes that the exemption is unsafe. Do not invent another `coordination` value. Keep
        frontmatter fields alphabetized, with `description` last.
      
      For a source-catalog skill, treat frontmatter, `agents/openai.yaml`, `metadata.install-targets`, the bundled-file set,
      and file structure as report-only. Report drift in those surfaces or in the skill's purpose as recommendations; never
      edit them.
      
      For each selected skill:
      
      - Verify referenced `references/`, `scripts/`, `assets/`, and `examples/` paths relative to the skill directory.
      - Read only the bundled files needed to verify paths, commands, flags, environment variables, versions, symbols,
        ownership, and repository conventions.
      - Preserve structure and voice; use the smallest factual edit span.
      - Leave third-party behavior and paths outside the repository unchanged unless current repository evidence
        authoritatively establishes the correction.
      - Report an obsolete skill whose central subject no longer exists; do not delete or hollow it out.
      
      ## Finish
      
      Run the completion checks and use the report contract from SKILL.md. Stop after the selected existing targets are
      accurate and validated; do not create recommended context or perform adjacent cleanup.
      
  • scripts
    • fetch-guidance.sh 9 KB
      #!/bin/bash
      
      set -euo pipefail
      
      fresh_limit_seconds=86400
      stale_limit_seconds=604800
      lock_wait_seconds=35
      stale_lock_seconds=60
      
      usage() {
        cat >&2 <<'EOF'
      Usage: fetch-guidance.sh [--refresh] <gpt-6.1-sol|claude-opus-5-5>
      
      Reuse fresh cached prompting guides and revalidate older fixed official artifacts.
      Prints the absolute cached file path on stdout.
      EOF
      }
      
      die() {
        printf 'agents-brain: %s\n' "$1" >&2
        exit "${2:-1}"
      }
      
      refresh=false
      if [ "${1:-}" = '--refresh' ]; then
        refresh=true
        shift
      fi
      
      if [ "$#" -ne 1 ]; then
        usage
        exit 64
      fi
      
      artifact=$1
      case "$artifact" in
        gpt-6.1-sol)
          source_url='https://developers.openai.com/api/docs/guides/latest-model.md'
          body_name='gpt-6.1-sol-prompting.md'
          content_marker='### GPT-6.1 Sol'
          ;;
        claude-opus-5-5)
          source_url='https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5.md'
          body_name='claude-opus-5-5-prompting.md'
          content_marker='title: Prompting Claude Opus 5.5'
          ;;
        *)
          die "unknown artifact '$artifact'" 64
          ;;
      esac
      
      umask 077
      
      if [ -n "${AGENTS_BRAIN_CACHE_DIR:-}" ]; then
        cache_root=$AGENTS_BRAIN_CACHE_DIR
      elif [ -n "${XDG_CACHE_HOME:-}" ]; then
        cache_root=$XDG_CACHE_HOME/agents-brain
      elif [ "$(uname -s)" = 'Darwin' ]; then
        [ -n "${HOME:-}" ] || die 'HOME is required to resolve the cache directory'
        cache_root=$HOME/Library/Caches/agents-brain
      else
        [ -n "${HOME:-}" ] || die 'HOME is required to resolve the cache directory'
        cache_root=$HOME/.cache/agents-brain
      fi
      
      mkdir -p "$cache_root" || die "cannot create cache directory: $cache_root"
      cache_root=$(cd "$cache_root" && pwd -P) || die "cannot resolve cache directory: $cache_root"
      
      body_file=$cache_root/$body_name
      metadata_file=$cache_root/$artifact.meta
      lock_dir=$cache_root/$artifact.lock
      
      headers_tmp=''
      body_tmp=''
      metadata_tmp=''
      lock_owned=false
      
      cleanup() {
        if [ -n "$headers_tmp" ]; then
          rm -f "$headers_tmp"
        fi
        if [ -n "$body_tmp" ]; then
          rm -f "$body_tmp"
        fi
        if [ -n "$metadata_tmp" ]; then
          rm -f "$metadata_tmp"
        fi
        if [ "$lock_owned" = true ]; then
          rmdir "$lock_dir" 2>/dev/null || true
        fi
      }
      
      trap cleanup EXIT
      trap 'exit 129' HUP
      trap 'exit 130' INT
      trap 'exit 143' TERM
      
      lock_attempt=0
      while ! mkdir "$lock_dir" 2>/dev/null; do
        now_epoch=$(date -u +%s)
        lock_epoch=$(stat -f '%m' "$lock_dir" 2>/dev/null || stat -c '%Y' "$lock_dir" 2>/dev/null || printf '0\n')
        case "$lock_epoch" in
          ''|*[!0-9]*) lock_epoch=0 ;;
        esac
      
        if [ "$lock_epoch" -gt 0 ] && [ $((now_epoch - lock_epoch)) -gt "$stale_lock_seconds" ]; then
          if rmdir "$lock_dir" 2>/dev/null; then
            continue
          fi
        fi
      
        lock_attempt=$((lock_attempt + 1))
        if [ "$lock_attempt" -ge "$lock_wait_seconds" ]; then
          die "cache lock remained busy for $lock_wait_seconds seconds: $artifact"
        fi
        sleep 1
      done
      lock_owned=true
      
      metadata_value() {
        local key=$1
        local file=$2
      
        [ -f "$file" ] || return 1
        sed -n "s/^${key}=//p" "$file" | sed -n '1p'
      }
      
      validate_body() {
        local file=$1
        local byte_count
      
        [ -f "$file" ] || return 1
        byte_count=$(wc -c <"$file" | tr -d '[:space:]')
        case "$byte_count" in
          ''|*[!0-9]*) return 1 ;;
        esac
        [ "$byte_count" -ge 1024 ] || return 1
        grep -Fq -- "$content_marker" "$file"
      }
      
      allowed_effective_url() {
        [ "$1" = "$source_url" ]
      }
      
      final_header_value() {
        local header_name=$1
        local file=$2
      
        awk -v wanted="$header_name" '
          /^HTTP\// { value = "" }
          {
            line = $0
            sub(/\r$/, "", line)
            separator = index(line, ":")
            if (separator > 0 && tolower(substr(line, 1, separator - 1)) == tolower(wanted)) {
              value = substr(line, separator + 1)
              sub(/^[[:space:]]+/, "", value)
            }
          }
          END { print value }
        ' "$file"
      }
      
      write_metadata() {
        local effective_url=$1
        local etag=$2
        local last_modified=$3
        local validated_epoch=$4
        local validated_utc=$5
      
        metadata_tmp=$(mktemp "$cache_root/.fetch-guidance.metadata.XXXXXX")
        {
          printf 'format=1\n'
          printf 'effective_url=%s\n' "$effective_url"
          printf 'etag=%s\n' "$etag"
          printf 'last_modified=%s\n' "$last_modified"
          printf 'validated_at_epoch=%s\n' "$validated_epoch"
          printf 'validated_at_utc=%s\n' "$validated_utc"
        } >"$metadata_tmp"
        mv -f "$metadata_tmp" "$metadata_file"
        metadata_tmp=''
      }
      
      current_format=$(metadata_value format "$metadata_file" 2>/dev/null || true)
      current_effective_url=$(metadata_value effective_url "$metadata_file" 2>/dev/null || true)
      current_etag=$(metadata_value etag "$metadata_file" 2>/dev/null || true)
      current_last_modified=$(metadata_value last_modified "$metadata_file" 2>/dev/null || true)
      current_validated_epoch=$(metadata_value validated_at_epoch "$metadata_file" 2>/dev/null || true)
      current_validated_utc=$(metadata_value validated_at_utc "$metadata_file" 2>/dev/null || true)
      
      have_valid_cache=false
      if [ "$current_format" = 1 ] && [ -n "$current_validated_utc" ] && \
        allowed_effective_url "$current_effective_url" && validate_body "$body_file"; then
        case "$current_validated_epoch" in
          ''|*[!0-9]*) ;;
          *) have_valid_cache=true ;;
        esac
      fi
      
      cache_age=''
      if [ "$have_valid_cache" = true ]; then
        now_epoch=$(date -u +%s)
        cache_age=$((now_epoch - current_validated_epoch))
      fi
      
      if [ "$refresh" = false ] && [ "$have_valid_cache" = true ] && \
        [ "$cache_age" -ge 0 ] && [ "$cache_age" -le "$fresh_limit_seconds" ]; then
        printf 'agents-brain: cached %s last validated at %s (%s)\n' \
          "$artifact" "$current_validated_utc" "$current_effective_url" >&2
        printf '%s\n' "$body_file"
        exit 0
      fi
      
      headers_tmp=$(mktemp "$cache_root/.fetch-guidance.headers.XXXXXX")
      body_tmp=$(mktemp "$cache_root/.fetch-guidance.body.XXXXXX")
      
      response_code=''
      effective_url=''
      
      fetch_once() {
        local conditional=$1
        local curl_output
        local curl_rc
        local curl_args
      
        : >"$headers_tmp"
        : >"$body_tmp"
      
        curl_args=(
          --connect-timeout 10
          --dump-header "$headers_tmp"
          --fail
          --location
          --max-time 30
          --output "$body_tmp"
          --proto '=https'
          --proto-redir '=https'
          --show-error
          --silent
          --write-out '%{http_code}\n%{url_effective}\n'
        )
      
        if [ "$conditional" = true ] && [ -n "$current_etag" ]; then
          curl_args+=(--header "If-None-Match: $current_etag")
        elif [ "$conditional" = true ] && [ -n "$current_last_modified" ]; then
          curl_args+=(--header "If-Modified-Since: $current_last_modified")
        fi
      
        set +e
        curl_output=$(curl "${curl_args[@]}" "$source_url")
        curl_rc=$?
        set -e
        if [ "$curl_rc" -ne 0 ]; then
          return 1
        fi
      
        response_code=$(printf '%s\n' "$curl_output" | sed -n '1p')
        effective_url=$(printf '%s\n' "$curl_output" | sed -n '2p')
        return 0
      }
      
      print_success() {
        local cache_state=$1
        local validated_utc=$2
        local final_url=$3
      
        printf 'agents-brain: %s %s at %s (%s)\n' "$cache_state" "$artifact" "$validated_utc" "$final_url" >&2
        printf '%s\n' "$body_file"
      }
      
      use_stale_cache() {
        local now_epoch
        local stale_age
      
        [ "$refresh" = false ] || return 1
        [ "$have_valid_cache" = true ] || return 1
      
        now_epoch=$(date -u +%s)
        stale_age=$((now_epoch - current_validated_epoch))
        [ "$stale_age" -ge 0 ] || return 1
        [ "$stale_age" -le "$stale_limit_seconds" ] || return 1
      
        printf 'agents-brain: stale %s last validated at %s (%s); live retrieval failed\n' \
          "$artifact" "$current_validated_utc" "$current_effective_url" >&2
        printf '%s\n' "$body_file"
        return 0
      }
      
      conditional=false
      if [ "$refresh" = false ] && [ "$have_valid_cache" = true ]; then
        if [ -n "$current_etag" ] || [ -n "$current_last_modified" ]; then
          conditional=true
        fi
      fi
      
      if ! fetch_once "$conditional"; then
        if [ "$refresh" = true ]; then
          die "forced refresh failed for $artifact"
        fi
        if use_stale_cache; then
          exit 0
        fi
        die "could not retrieve $artifact and no cache validated within seven days is available"
      fi
      
      if ! allowed_effective_url "$effective_url"; then
        die "refused unexpected final URL for $artifact: $effective_url"
      fi
      
      if [ "$response_code" = 304 ]; then
        if [ "$have_valid_cache" != true ]; then
          if ! fetch_once false; then
            die "received 304 for unusable $artifact cache and unconditional retrieval failed"
          fi
          if ! allowed_effective_url "$effective_url"; then
            die "refused unexpected final URL for $artifact: $effective_url"
          fi
        else
          validated_epoch=$(date -u +%s)
          validated_utc=$(date -u '+%Y-%m-%dT%H:%M:%SZ')
          write_metadata "$effective_url" "$current_etag" "$current_last_modified" "$validated_epoch" "$validated_utc"
          print_success revalidated "$validated_utc" "$effective_url"
          exit 0
        fi
      fi
      
      if [ "$response_code" != 200 ]; then
        die "unexpected HTTP status for $artifact: $response_code"
      fi
      
      if ! validate_body "$body_tmp"; then
        die "retrieved invalid content for $artifact"
      fi
      
      new_etag=$(final_header_value ETag "$headers_tmp")
      new_last_modified=$(final_header_value Last-Modified "$headers_tmp")
      validated_epoch=$(date -u +%s)
      validated_utc=$(date -u '+%Y-%m-%dT%H:%M:%SZ')
      
      mv -f "$body_tmp" "$body_file"
      body_tmp=''
      write_metadata "$effective_url" "$new_etag" "$new_last_modified" "$validated_epoch" "$validated_utc"
      print_success fetched "$validated_utc" "$effective_url"
      
  • SKILL.md 13.8 KB
    ---
    argument-hint:
      <polish|create> [path] [target ...] [--root-only] [--preserve] [--minimal] [--thorough|--full] [--dry-run] [--force]
    compatibility:
      Requires curl and a writable user cache directory; network populates or refreshes the GPT-6.1 Sol and Claude Opus 5.5
      prompting guides.
    name: agents-brain
    skill-dependencies:
      - skill-writing
    description:
      "Create or polish repo agent context: README.md, AGENTS.md/CLAUDE.md, project-installed and source-catalog skills, and
      other Markdown context docs."
    ---
    
    # Agents Brain
    
    If these instructions are already present in the conversation from a slash or dollar invocation, follow them directly;
    do not invoke this skill again through a skill tool.
    
    Create or polish repo-local context as one coherent system: human-facing README.md files, agent-facing AGENTS.md files
    (with companion CLAUDE.md symlinks only for pre-native Claude Code, per Claude Code Compatibility below), existing
    project-installed skills under `.agents/skills`, eligible source-catalog skills under `skills/<name>/`, and context docs
    — any other Markdown files, under any name or directory, whose content is durable guidance for agents or humans, such as
    conventions, command catalogs, data-format rules, workflow runbooks, and reference material.
    
    Success means every selected target is grounded in repository evidence, respects its audience and scope, spends agent
    context only on guidance that changes behavior, and passes the narrowest repository-defined validation. Stop after
    reporting completed or planned changes, validation, and any blockers.
    
    ## Model and Context Optimization
    
    Optimize skills and other agent-facing context for GPT-6.1 Sol and Claude Opus 5.5 while preserving README.md as clear
    human-facing documentation. Before complex, long-running, multi-tool, or orchestration-heavy context work, resolve
    `scripts/fetch-guidance.sh` relative to this skill directory, run it once for `gpt-6.1-sol` and once for
    `claude-opus-5-5`, and read both returned files completely. The helper retrieves the official
    [GPT-6.1 Sol prompting guidance](https://developers.openai.com/api/docs/guides/latest-model#prompting-best-practices)
    and
    [Claude Opus 5.5 prompting guidance](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-opus-5-5)
    because their recommendations may evolve. OpenAI publishes Sol guidance in the shared GPT-6 guide; evaluate its
    family-wide prompting recommendations on GPT-6.1 Sol. Simple context work does not require either guide.
    
    Accept an integrity-valid `cached` guide for 24 hours. Use `--refresh` for explicitly latest or change-sensitive work,
    materially disputed guidance, or conflicts with observed model behavior. Interpret helper diagnostics precisely:
    
    - `cached` reused a guide validated no more than 24 hours ago without network access.
    - `revalidated` refreshed validation metadata after a successful conditional `304` response.
    - `fetched` atomically replaced the cache with integrity-valid content from the pinned official URL.
    - `stale` reused a guide validated no more than seven days ago after live retrieval failed. Proceed only after reading
      it and disclose the validation timestamp and retrieval failure under open issues and caveats.
    
    Forced refreshes, expired entries, integrity failures, and unexpected redirects fail closed. If either required guide
    cannot be returned, stop qualifying work before writing instead of substituting memory or another source. Never create
    the cache in a repository or skill installation.
    
    Keep only content that changes a decision, prevents an evidenced mistake, or supplies a non-discoverable constraint.
    State each meaning once at the narrowest reliable load scope, except where independently installed artifacts need to
    stay self-contained. Preserve authority, safety, material exceptions, semantic success criteria, and exact
    machine-consumed text. Documentation-only authority does not permit changing helpers or schemas; report an extraction
    opportunity instead.
    
    ## Choose a Workflow
    
    Choose exactly one workflow and read only its reference.
    
    For skill creation, first inspect applicable repository instructions. When they define a source catalog and lifecycle,
    stop and follow that repository-owned workflow. Use `skill-writing` only when no catalog-specific workflow exists.
    
    | User intent                                                     | Workflow                     | Reference                                           |
    | --------------------------------------------------------------- | ---------------------------- | --------------------------------------------------- |
    | Update, refresh, sync, prune, polish, repair, or fix context    | `polish`                     | `references/polish.md`                              |
    | Create, initialize, generate, or regenerate context files       | `create`                     | `references/create-docs.md`                         |
    | Audit, check, review, inspect, or suggest changes without edits | `polish` in `--dry-run` mode | `references/polish.md`                              |
    | Create or scaffold a skill                                      | Stop                         | Use repository catalog lifecycle or `skill-writing` |
    | Install, discover, remove, or rename a skill                    | Stop                         | Use a dedicated skill-management workflow           |
    
    If the intent is unclear, select `polish` in `--dry-run` mode and report the smallest useful planned change set.
    
    ## Authority
    
    - Apply explicit user instructions and established authorization before this skill's defaults. Do not ask again for an
      unchanged decision; preserve host restrictions and required destructive-action approval.
    - Explicit create, update, polish, repair, fix, or equivalent intent authorizes in-scope local writes. Inspection-only
      intent and `--dry-run` do not.
    - Require explicit confirmation before deleting README.md, AGENTS.md, regular CLAUDE.md files, or context-doc targets.
      `--force` authorizes documented overwrites, not deletions. The one standing exception is a CLAUDE.md symlink to a
      sibling AGENTS.md when the installed Claude Code reads AGENTS.md natively (see Claude Code Compatibility): delete it
      without asking.
    - Resolve scope from the requested outcome. Preview a large change set, then continue when it is already authorized;
      file count alone is not an approval boundary. Ask only when an unresolved choice changes scope or intended meaning.
    - Do not expand from documentation work into source changes, skill creation, or external writes.
    
    Complete authorized discovery, edits, and validation before reporting completion. When one target needs input, continue
    independent targets and identify the exact unresolved choice. If a skill rule requires a pause, cite that rule and
    explain why existing authorization does not cover the next action.
    
    ## Arguments
    
    - `path`: Optional repo-relative subtree. Restrict documentation, package-root, project-skill, source-catalog skill, and
      context-doc discovery to that subtree.
    - `target ...`: Optional filters during `polish`: skill names from existing `.agents/skills/<name>/` or eligible
      `skills/<name>/` trees, or repo-relative Markdown paths selecting specific context docs.
    - `--root-only`: Select only root README.md, AGENTS.md, and CLAUDE.md targets. Exclude project-installed skills,
      source-catalog skills, and context docs unless explicitly selected by `target`.
    - `--dry-run`: Report planned writes and concise diffs without changing files.
    - `--preserve`: During `polish`, keep accurate user-authored prose and structure; fix only drift and obvious noise.
    - `--minimal`: Produce the smallest context that still meets the completion bar.
    - `--thorough` / `--full`: Perform deeper analysis only where it adds durable, repository-specific context.
    - `--force`: During `create`, regenerate existing README.md or AGENTS.md targets without prompting. Never applies to
      skills or deletions.
    
    If `--minimal` and `--thorough` / `--full` are both present, make no writes and ask the user to choose. Report
    unrecognized flags; continue only when they cannot change scope, safety, or write behavior.
    
    ## Repository Guard Rail
    
    Run before discovery or writes:
    
    ```sh
    cwd="$(pwd -P)"
    case "$cwd" in
      /) printf 'abort: refusing to run at the filesystem root\n' >&2; exit 1 ;;
    esac
    repo_root="$(git rev-parse --show-toplevel 2>/dev/null)" || {
      printf 'abort: not inside a git repository\n' >&2; exit 1; }
    managed_skill_root=
    case "$repo_root" in
      /|"$HOME") printf 'abort: unsupported repo root: %s\n' "$repo_root" >&2; exit 1 ;;
      "$HOME/.agents"|"$HOME/.codex"|"$HOME/.claude") managed_skill_root="$repo_root/skills" ;;
      "$HOME/.agents/"*|"$HOME/.codex/"*|"$HOME/.claude/"*)
        printf 'abort: repo root is nested under an agent configuration repository: %s\n' "$repo_root" >&2; exit 1 ;;
    esac
    if [ -n "$managed_skill_root" ]; then
      case "$cwd" in
        "$managed_skill_root"|"$managed_skill_root/"*)
          printf 'abort: installed skills must be edited in their source catalog: %s\n' "$cwd" >&2; exit 1 ;;
      esac
    fi
    ```
    
    When `managed_skill_root` is set, allow README.md, AGENTS.md, and CLAUDE.md work elsewhere in that repository, but
    exclude the entire installed `skills/` tree from every workflow. Apply the exclusion before discovery, canonicalization,
    or symlink traversal. If `path`, a `target`, or an explicit request would enter that tree, make no writes there and
    report that the skill must be edited in its source catalog. `--force` does not override this boundary.
    
    Outside managed agent-config roots, eligible git-tracked `skills/<name>/` source catalogs are in scope for `polish` per
    `references/polish.md`.
    
    ## Claude Code Compatibility
    
    Claude Code v2.1.277 and later read `AGENTS.md` directly whenever no `CLAUDE.md`, `.claude/CLAUDE.md`, or
    `CLAUDE.local.md` exists in the working directory or above it, so a CLAUDE.md symlink is no longer needed. Detect the
    installed version once per run before either workflow touches CLAUDE.md:
    
    ```sh
    claude_version=$(claude --version 2>/dev/null | awk '{ print $1; exit }')
    agents_md_native=false
    if [ -n "$claude_version" ] &&
      [ "$(printf '%s\n' 2.1.277 "$claude_version" | sort -V | head -n 1)" = 2.1.277 ]; then
      agents_md_native=true
    fi
    ```
    
    When `agents_md_native=true`:
    
    - Do not create CLAUDE.md symlinks.
    - Delete every CLAUDE.md that is a symlink resolving to its sibling AGENTS.md, in the same pass and across the whole
      selected tree, using `git rm` when tracked. Leave regular CLAUDE.md and CLAUDE.local.md files untouched and report
      them: any such file at or above the repository root still suppresses direct AGENTS.md loading unless the user sets
      **Project instructions** to `claude-md-and-agents-md` in `/config`.
    
    When `claude` is missing or older, keep the pre-native behavior: create or refresh a sibling symlink only where
    CLAUDE.md is missing or already a symlink, and never delete one.
    
    Snapshot `git status --short` before broad edits. Preserve unrelated pre-existing changes and re-check expected paths
    after generators or broad commands.
    
    ## Discovery and Tool Routing
    
    Use git-aware discovery, canonicalize every candidate beneath `repo_root`, and exclude VCS, dependency, environment, and
    build outputs. Deliberately include ignored `.agents/skills/*/SKILL.md` only when project skills are selected. Discover
    git-tracked, non-ignored, non-symlinked `skills/*/SKILL.md` only outside managed agent-config roots and only when
    source-catalog skills are selected. Parse each selected skill's YAML frontmatter. Inspect only a project-installed
    skill's declared write boundary before deciding whether it qualifies for a coordination exemption. Prefer `fd`, fall
    back once on suspiciously narrow results, and synthesize independent repository evidence before writing.
    
    Discover context docs by following Markdown links from README.md, AGENTS.md, CLAUDE.md, and SKILL.md files, then by
    scanning remaining tracked Markdown whose content qualifies. Classify by content, never by file name or location.
    Exclude changelogs, licenses, legal and policy notices, generated or vendored documentation, and prose that is product
    content rather than guidance. When classification is uncertain, leave the file out of scope and report it as a
    candidate.
    
    ## Completion and Report
    
    After writes, run repository-defined Markdown formatting or checks when present. If skill frontmatter or
    `agents/openai.yaml` changed in a project-installed skill, run its invocation metadata check. Verify that no CLAUDE.md
    symlink remains when `agents_md_native=true`, and that every retained or created symlink resolves to its sibling
    AGENTS.md otherwise. In `--dry-run`, report commands that would depend on planned files instead of running them.
    
    Lead with `### ✅ Context updated` only after writes and required validation pass,
    `### ⚠️ Context updated — validation failed` when files were written but required checks fail,
    `### 🔎 Context preview — no files written` in dry-run mode, or `### ⛔ Context blocked — no files written` for a
    pre-write stop. Follow with the workflow and scope, material changes, exact validation commands and outcomes, and any
    remaining limitation. Use short prose for a small change; add headings or tables only when they organize repeated
    information, and a tree only when directory ownership matters. Follow the user's requested report format.
    
    When issues need a separate section, group verified fixes with evidence as `Resolved` and remaining problems as `Open`,
    with impact and next action. Omit empty groups and report each item once. Reserve `blocker` for something preventing
    required work and `risk` for a specific potential adverse outcome. A workaround leaves the underlying issue open.
    
    Keep paths, commands, guard-rail errors, symlink targets, and user-authored content exact and undecorated. Omit empty
    detail and stop once the selected targets meet the completion bar.
    
    ## References
    
    - `polish`: read `references/polish.md`.
    - `create`: read `references/create-docs.md`.
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related