Skip to content

netresearch/agent-rules-skill / skills/agent-rules

agent-rules

Flagged

Use when creating or updating AGENTS.md files, .github/copilot-instructions.md, or other AI agent rule files, onboarding AI agents to a project, standardizing agent documentation, or when anyone mentions AGENTS.md, agent rules, project onboarding, or codebase documentation for AI agents.

FileKindSize
AGENTS.mdmarkdown4.0 KB
CLAUDE.mdmarkdown9 B
SKILL.mdskill md5.2 KB
assets/.markdownlint-cli2.jsoncother624 B
assets/example-workflows/validate-agents.ymlconfig2.8 KB
assets/root-thin.mdmarkdown5.7 KB
assets/root-verbose.mdmarkdown5.5 KB
assets/scoped/backend-go.mdmarkdown3.6 KB
assets/scoped/backend-php.mdmarkdown3.0 KB
assets/scoped/backend-python.mdmarkdown2.6 KB
assets/scoped/backend-typescript.mdmarkdown2.8 KB
assets/scoped/claude-code-skill.mdmarkdown3.4 KB
assets/scoped/cli.mdmarkdown2.7 KB
assets/scoped/concourse.mdmarkdown5.2 KB
assets/scoped/ddev.mdmarkdown2.4 KB
assets/scoped/docker.mdmarkdown5.3 KB
assets/scoped/documentation.mdmarkdown3.5 KB
assets/scoped/examples.mdmarkdown3.4 KB
assets/scoped/frontend-typescript.mdmarkdown2.7 KB
assets/scoped/github-actions.mdmarkdown5.2 KB
assets/scoped/gitlab-ci.mdmarkdown4.6 KB
assets/scoped/oro-bundle.mdmarkdown6.5 KB
assets/scoped/oro-project.mdmarkdown5.5 KB
assets/scoped/python-modern.mdmarkdown6.1 KB
assets/scoped/resources.mdmarkdown3.5 KB
assets/scoped/skill-repo.mdmarkdown5.4 KB
assets/scoped/symfony.mdmarkdown5.3 KB
assets/scoped/testing.mdmarkdown3.0 KB
assets/scoped/typo3-docs.mdmarkdown3.6 KB
assets/scoped/typo3-extension.mdmarkdown5.1 KB
assets/scoped/typo3-project.mdmarkdown4.7 KB
assets/scoped/typo3-testing.mdmarkdown3.0 KB
checkpoints.yamlconfig14.4 KB
evals/evals.jsonconfig22.9 KB
references/ai-contribution-guidelines.mdmarkdown2.6 KB
references/ai-tool-compatibility.mdmarkdown8.0 KB
references/directory-coverage.mdmarkdown2.5 KB
references/examples/coding-agent-cli/AGENTS.mdmarkdown2.5 KB
references/examples/coding-agent-cli/go.modmanifest45 B
references/examples/coding-agent-cli/scripts-AGENTS.mdmarkdown10.1 KB
references/examples/express-api-ts/.env.exampleother232 B
references/examples/express-api-ts/AGENTS.mdmarkdown3.1 KB
references/examples/express-api-ts/package.jsonmanifest757 B
references/examples/express-api-ts/pnpm-lock.yamlmanifest101 B
references/examples/express-api-ts/src/AGENTS.mdmarkdown3.1 KB
references/examples/express-api-ts/src/config.tsscript917 B
references/examples/express-api-ts/src/controllers/userController.tsscript2.1 KB
references/examples/express-api-ts/src/index.tsscript671 B
references/examples/express-api-ts/src/middleware/errorHandler.tsscript1.0 KB
references/examples/express-api-ts/src/middleware/requestLogger.tsscript471 B
references/examples/express-api-ts/src/routes/health.tsscript428 B
references/examples/express-api-ts/src/routes/users.tsscript397 B
references/examples/express-api-ts/src/utils/errors.tsscript1.2 KB
references/examples/express-api-ts/src/utils/logger.tsscript441 B
references/examples/express-api-ts/tsconfig.jsonconfig630 B
references/examples/fastapi-app/.env.exampleother348 B
references/examples/fastapi-app/AGENTS.mdmarkdown3.2 KB
references/examples/fastapi-app/pyproject.tomlmanifest1.8 KB
references/examples/fastapi-app/src/AGENTS.mdmarkdown2.9 KB
references/examples/fastapi-app/src/__init__.pyscript58 B
references/examples/fastapi-app/src/config.pyscript1.1 KB
references/examples/fastapi-app/src/main.pyscript1.7 KB
references/examples/fastapi-app/src/models/__init__.pyscript278 B
references/examples/fastapi-app/src/models/item.pyscript1.0 KB
references/examples/fastapi-app/src/models/user.pyscript922 B
references/examples/fastapi-app/src/routes/__init__.pyscript110 B
references/examples/fastapi-app/src/routes/health.pyscript470 B
references/examples/fastapi-app/src/routes/items.pyscript1.9 KB
references/examples/fastapi-app/src/routes/users.pyscript1.7 KB
references/examples/fastapi-app/src/services/__init__.pyscript174 B
references/examples/fastapi-app/src/services/item_service.pyscript2.5 KB
references/examples/fastapi-app/src/services/user_service.pyscript2.1 KB
references/examples/fastapi-app/uv.lockmanifest136 B
references/examples/go-api-with-react-admin/.scopesother93 B
references/examples/go-api-with-react-admin/AGENTS.mdmarkdown3.0 KB
references/examples/go-api-with-react-admin/admin/package.jsonmanifest423 B
references/examples/go-api-with-react-admin/admin/src/App.tsxother101 B
references/examples/go-api-with-react-admin/cmd/api/main.goscript75 B
references/examples/go-api-with-react-admin/go.modmanifest31 B
references/examples/go-api-with-react-admin/main.goscript71 B
references/examples/go-with-internal-web-tsx/.scopesother102 B
references/examples/go-with-internal-web-tsx/AGENTS.mdmarkdown3.1 KB
references/examples/go-with-internal-web-tsx/go.modmanifest34 B
references/examples/go-with-internal-web-tsx/internal/web/AGENTS.mdmarkdown3.1 KB
references/examples/go-with-internal-web-tsx/internal/web/package.jsonmanifest329 B
references/examples/go-with-internal-web-tsx/internal/web/src/App.tsxother57 B
references/examples/go-with-internal-web-tsx/internal/web/src/Button.tsxother63 B
references/examples/go-with-internal-web-tsx/internal/web/src/Footer.tsxother63 B
references/examples/go-with-internal-web-tsx/internal/web/src/Header.tsxother63 B
references/examples/go-with-internal-web-tsx/internal/web/src/Sidebar.tsxother65 B
references/examples/go-with-internal-web-tsx/main.goscript85 B
references/examples/go-with-internal-web-tsx/package-lock.jsonmanifest87 B
references/examples/go-with-internal-web-tsx/package.jsonmanifest221 B
references/examples/ldap-selfservice/AGENTS.mdmarkdown2.5 KB
references/examples/ldap-selfservice/go.modmanifest45 B
references/examples/ldap-selfservice/internal-AGENTS.mdmarkdown10.0 KB
references/examples/ldap-selfservice/internal-web-AGENTS.mdmarkdown12.1 KB
references/examples/php-with-frontend/.scopesother89 B
references/examples/php-with-frontend/AGENTS.mdmarkdown3.1 KB
references/examples/php-with-frontend/composer.jsonconfig185 B
references/examples/php-with-frontend/package.jsonmanifest307 B
references/examples/php-with-frontend/pnpm-lock.yamlmanifest101 B
references/examples/php-with-frontend/src/Controller.phpscript41 B
references/examples/php-with-frontend/web/AGENTS.mdmarkdown3.1 KB
references/examples/php-with-frontend/web/package.jsonmanifest515 B
references/examples/php-with-frontend/web/src/App.tsxother63 B
references/examples/php-with-frontend/web/src/Button.tsxother215 B
references/examples/php-with-frontend/web/src/Footer.tsxother125 B
references/examples/php-with-frontend/web/src/Header.tsxother122 B
references/examples/php-with-frontend/web/src/main.tsxother41 B
references/examples/php-with-frontend/web/tsconfig.jsonconfig280 B
references/examples/pnpm-workspace/AGENTS.mdmarkdown2.6 KB
references/examples/pnpm-workspace/package.jsonmanifest105 B
references/examples/pnpm-workspace/packages/web/package.jsonmanifest187 B
references/examples/pnpm-workspace/packages/web/src/index.tsxother258 B
references/examples/pnpm-workspace/pnpm-lock.yamlmanifest920 B
references/examples/pnpm-workspace/pnpm-workspace.yamlconfig27 B
references/examples/simple-ldap-go/AGENTS.mdmarkdown2.5 KB
references/examples/simple-ldap-go/examples-AGENTS.mdmarkdown1.8 KB
references/examples/simple-ldap-go/go.modmanifest43 B
references/examples/t3x-rte-ckeditor-image/AGENTS.mdmarkdown2.5 KB
references/examples/t3x-rte-ckeditor-image/Classes-AGENTS.mdmarkdown12.0 KB
references/examples/t3x-rte-ckeditor-image/composer.jsonconfig174 B
references/feedback-memory-schema.mdmarkdown6.2 KB
references/fleet-sync-sweep.mdmarkdown4.8 KB
references/git-hooks-setup.mdmarkdown2.5 KB
references/output-structure.mdmarkdown5.4 KB
references/quality-rubric.mdmarkdown6.2 KB
references/scripts-guide.mdmarkdown7.7 KB
references/verification-guide.mdmarkdown9.4 KB
scripts/analyze-git-history.shexecutablescript10.2 KB
scripts/check-freshness.shexecutablescript8.9 KB
scripts/detect-golden-samples.shexecutablescript5.7 KB
scripts/detect-heuristics.shexecutablescript3.2 KB
scripts/detect-project.shexecutablescript19.6 KB
scripts/detect-scopes.shexecutablescript13.4 KB
scripts/detect-utilities.shexecutablescript4.6 KB
scripts/extract-adrs.shexecutablescript6.8 KB
scripts/extract-agent-configs.shexecutablescript9.3 KB
scripts/extract-architecture-rules.shexecutablescript19.9 KB
scripts/extract-ci-commands.shexecutablescript12.5 KB
scripts/extract-ci-rules.shexecutablescript16.1 KB
scripts/extract-commands.shexecutablescript11.9 KB
scripts/extract-documentation.shexecutablescript7.8 KB
scripts/extract-github-rulesets.shexecutablescript3.8 KB
scripts/extract-github-settings.shexecutablescript3.6 KB
scripts/extract-ide-settings.shexecutablescript7.0 KB
scripts/extract-platform-files.shexecutablescript8.0 KB
scripts/extract-quality-configs.shexecutablescript14.9 KB
scripts/generate-agents.shexecutablescript118.2 KB
scripts/generate-file-map.shexecutablescript4.6 KB
scripts/lib/config-root.shexecutablescript5.8 KB
scripts/lib/git.shscript1.2 KB
scripts/lib/summary.shscript11.7 KB
scripts/lib/template.shexecutablescript15.9 KB
scripts/score-agents.shexecutablescript9.8 KB
scripts/tests/test-agents-file-write-boundary.shscript5.8 KB
scripts/tests/test-agents-scan-dependency-trees.shexecutablescript4.5 KB
scripts/tests/test-changelog-rule.shexecutablescript3.4 KB
scripts/tests/test-claude-import-file.shscript3.3 KB
scripts/tests/test-command-allowlist.shexecutablescript4.7 KB
scripts/tests/test-dependency-tree-exclusion.shscript2.5 KB
scripts/tests/test-extract-commands-real-scripts.shexecutablescript4.0 KB
scripts/tests/test-git-history-counts.shexecutablescript3.6 KB
scripts/tests/test-golden-sample-file-names.shexecutablescript2.2 KB
scripts/tests/test-json-manifest.shexecutablescript5.5 KB
scripts/tests/test-last-verified-opt-in.shscript1.6 KB
scripts/tests/test-make-target-lookup.shscript2.5 KB
scripts/tests/test-merge-heuristic.shscript1.8 KB
scripts/tests/test-scope-index-heading.shexecutablescript4.4 KB
scripts/tests/test-scope-index-keeps-existing.shexecutablescript2.5 KB
scripts/tests/test-symlink-write-boundary.shexecutablescript6.3 KB
scripts/tests/test-untrusted-git-config.shscript5.0 KB
scripts/tests/test-verification-sidecar.shscript2.7 KB
scripts/validate-structure.shexecutablescript13.3 KB
scripts/verify-commands.shexecutablescript32.5 KB
scripts/verify-content.shexecutablescript13.2 KB

scripts/generate-agents.sh

View on GitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Netresearch DTT GmbH
# Main AGENTS.md generator script
# Requires: Bash 4.3+ (for nameref variables)
# shellcheck disable=SC2034  # vars/scope_vars are used via nameref in template functions
set -euo pipefail

# Check Bash version - we need 4.3+ for nameref variables (local -n)
if ((BASH_VERSINFO[0] < 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] < 3))); then
    echo "Error: Bash 4.3+ required (found ${BASH_VERSION})." >&2
    echo "On macOS: brew install bash" >&2
    echo "Then run with: /opt/homebrew/bin/bash $0 $*" >&2
    exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_DIR="$(dirname "$SCRIPT_DIR")"
TEMPLATE_DIR="$SKILL_DIR/assets"

# Source helper libraries
# shellcheck disable=SC1091 # libs are shellchecked individually by the same hook
source "$SCRIPT_DIR/lib/template.sh"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/lib/summary.sh"
# shellcheck disable=SC1091
source "$SCRIPT_DIR/lib/config-root.sh"

# Default options
PROJECT_DIR="${1:-.}"
STYLE="${STYLE:-thin}"
DRY_RUN=false
UPDATE_ONLY=false
FORCE=false
VERBOSE=false
CLAUDE_SHIM=false
CREATE_SYMLINKS=true
JSON=false

# Parse flags
while [[ $# -gt 0 ]]; do
    case $1 in
        --style=*)
            STYLE="${1#*=}"
            shift
            ;;
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        --json)
            JSON=true
            shift
            ;;
        --update)
            UPDATE_ONLY=true
            shift
            ;;
        --force)
            FORCE=true
            shift
            ;;
        --verbose|-v)
            VERBOSE=true
            shift
            ;;
        --claude-shim)
            CLAUDE_SHIM=true
            shift
            ;;
        --no-symlinks)
            CREATE_SYMLINKS=false
            shift
            ;;
        --help|-h)
            cat <<EOF
Usage: generate-agents.sh [PROJECT_DIR] [OPTIONS]

Generate AGENTS.md files for a project following the public agents.md convention.

Options:
  --style=thin|verbose    Template style (default: thin)
  --dry-run               Preview what will be created
  --json                  Emit the write manifest as JSON (human output suppressed)
  --update                Update existing files only
  --force                 Force regeneration of existing files
  --claude-shim           Generate CLAUDE.md that imports AGENTS.md (root only, legacy)
  --no-symlinks           Skip creating CLAUDE.md/GEMINI.md symlinks (default: create them)
  --verbose, -v           Verbose output
  --help, -h              Show this help message

Examples:
  generate-agents.sh .                    # Generate thin root + scoped files
  generate-agents.sh . --dry-run          # Preview changes
  generate-agents.sh . --dry-run --json   # Machine-readable plan, nothing written
  generate-agents.sh . --style=verbose    # Use verbose root template
  generate-agents.sh . --update           # Update existing files
  generate-agents.sh . --no-symlinks      # Skip CLAUDE.md/GEMINI.md symlinks
  generate-agents.sh . --claude-shim      # Generate CLAUDE.md @import shim instead of symlink
EOF
            exit 0
            ;;
        *)
            PROJECT_DIR="$1"
            shift
            ;;
    esac
done

# Validate PROJECT_DIR exists
if [[ ! -d "$PROJECT_DIR" ]]; then
    echo "Error: Project directory not found: $PROJECT_DIR" >&2
    exit 1
fi

# Convert to absolute path before cd (so subsequent script calls work)
PROJECT_DIR="$(cd "$PROJECT_DIR" && pwd)"
# Physical path of the project, for keeping scoped writes inside it.
PROJECT_REAL="$(cd "$PROJECT_DIR" && pwd -P)"
cd "$PROJECT_DIR"

# --json emits the write manifest instead of the prose, the same way the
# read-only scripts do it: stdout is parked on fd 3 and the human lines go
# nowhere, so every existing echo stays untouched.
if [ "$JSON" = true ]; then
    exec 3>&1 1>/dev/null
fi

# One entry per path the run touches. With --dry-run it is a plan, without it a
# receipt of what was written -- the dry_run field in the output says which.
MANIFEST=()
# emit_op OP KIND PATH [KEY VALUE]
#   op:   write | symlink | keep
#   kind: agents-file | compat-file | shim
# Paths are recorded relative to the project root, so a manifest can be
# reviewed and compared without carrying one machine's directory layout.
emit_op() {
    local op="$1" kind="$2" path="$3" key="${4:-}" value="${5:-}"
    local rel="${path#"$PROJECT_DIR"/}"
    MANIFEST+=("$(jq -nc \
        --arg op "$op" --arg kind "$kind" --arg path "$rel" \
        --arg key "$key" --arg value "$value" \
        '{op: $op, kind: $kind, path: $path}
         + (if $key == "" then {} else {($key): $value} end)')")
}

# Initialize summary tracking
init_summary

log() {
    if [ "$VERBOSE" = true ]; then
        echo "[INFO] $*" >&2
    fi
}

# A CLAUDE.md/GEMINI.md compatibility file we are allowed to write:
# absent, a symlink we created (pointing at AGENTS.md), or our own generated
# "@AGENTS.md" import file. Anything else — a regular file, or a symlink
# pointing at rules the user maintains elsewhere — belongs to the user and is
# kept unless --force. Without this check "is a symlink" was treated the same
# as "does not exist" and a foreign link was silently repointed (#103).
compat_file_is_ours() {
    local file="$1"
    if [ -L "$file" ]; then
        [ "$(readlink "$file")" = "AGENTS.md" ]
        return
    fi
    [ ! -e "$file" ] && return 0
    grep -qxF '@AGENTS.md' "$file" 2>/dev/null
}

# One line saying what was left alone and how to override it. Printed
# unconditionally: a skip that only shows under --verbose reads as "nothing
# happened here" to everyone else.
report_kept_file() {
    local file="$1" label="$2" what
    if [ -L "$file" ]; then
        what="symlink → $(readlink "$file")"
    else
        what="regular file"
    fi
    emit_op keep compat-file "$file" reason "$what"
    echo "⏭️  Kept: $label ($what) — use --force to replace"
}

error() {
    echo "[ERROR] $*" >&2
    exit 1
}

# Detect Node.js package manager for a scope directory
# Walks up from scope dir to find package.json with lockfile
# Workspace-aware: checks workspace root for lockfiles if in a monorepo
detect_node_package_manager() {
    local scope_dir="$1"
    local search_dir="$scope_dir"

    # First, check if we're in a workspace - lockfile will be at workspace root
    local workspace_root
    workspace_root=$(find_node_workspace_root "$scope_dir" || true)
    if [ -n "$workspace_root" ]; then
        [ -f "$workspace_root/pnpm-lock.yaml" ] && echo "pnpm" && return
        [ -f "$workspace_root/yarn.lock" ] && echo "yarn" && return
        [ -f "$workspace_root/bun.lockb" ] && echo "bun" && return
        [ -f "$workspace_root/package-lock.json" ] && echo "npm" && return
    fi

    # Walk up to find package.json with lockfile
    while [ "$search_dir" != "." ] && [ "$search_dir" != "/" ]; do
        if [ -f "$search_dir/package.json" ]; then
            # Found package.json, check for lockfiles
            [ -f "$search_dir/pnpm-lock.yaml" ] && echo "pnpm" && return
            [ -f "$search_dir/yarn.lock" ] && echo "yarn" && return
            [ -f "$search_dir/bun.lockb" ] && echo "bun" && return
            [ -f "$search_dir/package-lock.json" ] && echo "npm" && return
            # No lockfile, default to npm
            echo "npm"
            return
        fi
        search_dir=$(dirname "$search_dir")
    done

    # Check root as last resort
    if [ -f "package.json" ]; then
        [ -f "pnpm-lock.yaml" ] && echo "pnpm" && return
        [ -f "yarn.lock" ] && echo "yarn" && return
        [ -f "bun.lockb" ] && echo "bun" && return
        echo "npm"
        return
    fi

    # Fallback: use from PROJECT_INFO if available
    if [ -n "${PROJECT_INFO:-}" ]; then
        local pkg_mgr
        pkg_mgr=$(echo "$PROJECT_INFO" | jq -r '.package_manager // "unknown"')
        if [ "$pkg_mgr" != "unknown" ] && [ "$pkg_mgr" != "go" ] && [ "$pkg_mgr" != "composer" ]; then
            echo "$pkg_mgr"
            return
        fi
    fi

    echo "npm"  # Ultimate fallback
}

# Detect CSS approach/framework used in project
# Checks package.json dependencies and config files
detect_css_approach() {
    local config_root="$1"
    local pkg_json="$config_root/package.json"
    local approaches=()

    # Check package.json dependencies
    if [ -f "$pkg_json" ]; then
        local deps
        deps=$(jq -r '(.dependencies // {}) + (.devDependencies // {}) | keys[]' "$pkg_json" 2>/dev/null || echo "")

        # Tailwind CSS
        if echo "$deps" | grep -q "^tailwindcss$"; then
            approaches+=("Tailwind CSS")
        fi

        # styled-components
        if echo "$deps" | grep -q "^styled-components$"; then
            approaches+=("styled-components")
        fi

        # Emotion
        if echo "$deps" | grep -q "^@emotion/"; then
            approaches+=("Emotion")
        fi

        # CSS Modules (indicated by config or common patterns)
        if [ -f "$config_root/postcss.config.js" ] || [ -f "$config_root/postcss.config.mjs" ]; then
            if ! printf '%s\n' "${approaches[@]}" | grep -q "Tailwind"; then
                approaches+=("CSS Modules")
            fi
        fi

        # Sass/SCSS
        if echo "$deps" | grep -q "^sass$"; then
            approaches+=("Sass/SCSS")
        fi
    fi

    # Default to CSS Modules if nothing detected but tsconfig exists
    if [ ${#approaches[@]} -eq 0 ]; then
        [ -f "$config_root/tsconfig.json" ] && approaches+=("CSS Modules")
    fi

    # Join approaches with comma. `local IFS` is function-scoped and does
    # not tamper with the caller's IFS — safe under strict SC2030/SC2031
    # semantics. Suppress opengrep's false positive on the `IFS=` pattern.
    local IFS=', '  # nosemgrep: bash.lang.security.ifs-tampering.ifs-tampering
    echo "${approaches[*]}"
}

# Byte budget enforcement (OpenAI Codex default: 32 KiB for combined instructions)
BYTE_BUDGET="${BYTE_BUDGET:-32768}"

enforce_byte_budget() {
    local file="$1"
    local budget="$2"

    [ ! -f "$file" ] && return 0

    local size
    size=$(wc -c < "$file")

    if [ "$size" -le "$budget" ]; then
        log "File size: $size bytes (within $budget budget)"
        return 0
    fi

    log "File exceeds byte budget ($size > $budget), pruning..."

    local content
    content=$(cat "$file")
    local pruned=false

    # Strategy 1: Reduce golden samples to 5
    if echo "$content" | grep -q "AGENTS-GENERATED:START golden-samples"; then
        local sample_count
        sample_count=$(echo "$content" | sed -n '/AGENTS-GENERATED:START golden-samples/,/AGENTS-GENERATED:END golden-samples/p' | grep -c "^|") || sample_count=0
        if [ "$sample_count" -gt 7 ]; then  # header + separator + 5 data rows = 7
            content=$(echo "$content" | awk '
                /AGENTS-GENERATED:START golden-samples/ { in_section=1; count=0; print; next }
                /AGENTS-GENERATED:END golden-samples/ { in_section=0; print; next }
                in_section && /^\|/ { count++; if (count <= 7) print; next }
                { print }
            ')
            pruned=true
            log "  - Reduced golden samples to 5"
        fi
    fi

    # Strategy 2: Reduce heuristics to 5
    if echo "$content" | grep -q "AGENTS-GENERATED:START heuristics"; then
        local heuristic_count
        heuristic_count=$(echo "$content" | sed -n '/AGENTS-GENERATED:START heuristics/,/AGENTS-GENERATED:END heuristics/p' | grep -c "^|") || heuristic_count=0
        if [ "$heuristic_count" -gt 7 ]; then  # header + separator + 5 data rows = 7
            content=$(echo "$content" | awk '
                /AGENTS-GENERATED:START heuristics/ { in_section=1; count=0; print; next }
                /AGENTS-GENERATED:END heuristics/ { in_section=0; print; next }
                in_section && /^\|/ { count++; if (count <= 7) print; next }
                { print }
            ')
            pruned=true
            log "  - Reduced heuristics to 5"
        fi
    fi

    # Strategy 3: Reduce utilities to 5
    if echo "$content" | grep -q "AGENTS-GENERATED:START utilities"; then
        local utility_count
        utility_count=$(echo "$content" | sed -n '/AGENTS-GENERATED:START utilities/,/AGENTS-GENERATED:END utilities/p' | grep -c "^|") || utility_count=0
        if [ "$utility_count" -gt 7 ]; then  # header + separator + 5 data rows = 7
            content=$(echo "$content" | awk '
                /AGENTS-GENERATED:START utilities/ { in_section=1; count=0; print; next }
                /AGENTS-GENERATED:END utilities/ { in_section=0; print; next }
                in_section && /^\|/ { count++; if (count <= 7) print; next }
                { print }
            ')
            pruned=true
            log "  - Reduced utilities to 5"
        fi
    fi

    # Write pruned content
    if [ "$pruned" = true ]; then
        printf '%s\n' "$content" | replace_file "$file"
        local new_size
        new_size=$(wc -c < "$file")
        echo "⚠️  Pruned due to size budget ($size → $new_size bytes)"
    fi

    return 0
}

# Detect project
log "Detecting project type..."
PROJECT_INFO=$("$SCRIPT_DIR/detect-project.sh" "$PROJECT_DIR")
[ "$VERBOSE" = true ] && echo "$PROJECT_INFO" | jq . >&2

LANGUAGE=$(echo "$PROJECT_INFO" | jq -r '.language')
VERSION=$(echo "$PROJECT_INFO" | jq -r '.version')
PROJECT_TYPE=$(echo "$PROJECT_INFO" | jq -r '.type')

[ "$LANGUAGE" = "unknown" ] && error "Could not detect project language"

# Detect scopes
log "Detecting scopes..."
SCOPES_INFO=$("$SCRIPT_DIR/detect-scopes.sh" "$PROJECT_DIR")
# A scope directory that resolves outside the project (through a symlink) is
# dropped before anything uses the list: its AGENTS.md and compatibility links
# would be written there, and the root index would point at it.
outside_scopes=()
while IFS= read -r scope_path; do
    [ -n "$scope_path" ] || continue
    scope_real="$(cd "$PROJECT_DIR/$scope_path" 2>/dev/null && pwd -P)" || scope_real=""
    if [[ "$scope_real" != "$PROJECT_REAL" && "$scope_real" != "$PROJECT_REAL"/* ]]; then
        outside_scopes+=("$scope_path")
        emit_op keep agents-file "$PROJECT_DIR/$scope_path/AGENTS.md" reason "resolves outside the project"
        echo "⚠️  Skipped: $scope_path resolves outside the project"
    fi
done < <(echo "$SCOPES_INFO" | jq -r '.scopes[]?.path')
if [ "${#outside_scopes[@]}" -gt 0 ]; then
    SCOPES_INFO=$(echo "$SCOPES_INFO" | jq --args '.scopes |= map(select(.path as $p | $ARGS.positional | index($p) | not))' "${outside_scopes[@]}")
fi
[ "$VERBOSE" = true ] && echo "$SCOPES_INFO" | jq . >&2

# Map language to stack filter for extract-commands.sh
get_stack_filter() {
    local lang="$1"
    case "$lang" in
        go) echo "go" ;;
        php) echo "php" ;;
        python) echo "python" ;;
        typescript|javascript) echo "node" ;;
        *) echo "auto" ;;
    esac
}

# Extract commands
log "Extracting build commands..."
PRIMARY_STACK=$(get_stack_filter "$LANGUAGE")
COMMANDS=$("$SCRIPT_DIR/extract-commands.sh" "$PROJECT_DIR" "$PRIMARY_STACK")
[ "$VERBOSE" = true ] && echo "$COMMANDS" | jq . >&2

# Extract documentation (README, CONTRIBUTING, SECURITY, etc.)
log "Extracting documentation..."
DOCS_INFO=$("$SCRIPT_DIR/extract-documentation.sh" "$PROJECT_DIR")
[ "$VERBOSE" = true ] && echo "$DOCS_INFO" | jq . >&2

# Extract platform files (.github/, .gitlab/, etc.)
log "Extracting platform files..."
PLATFORM_INFO=$("$SCRIPT_DIR/extract-platform-files.sh" "$PROJECT_DIR")
[ "$VERBOSE" = true ] && echo "$PLATFORM_INFO" | jq . >&2

# Extract IDE settings (.editorconfig, .vscode/, etc.)
log "Extracting IDE settings..."
IDE_INFO=$("$SCRIPT_DIR/extract-ide-settings.sh" "$PROJECT_DIR")
[ "$VERBOSE" = true ] && echo "$IDE_INFO" | jq . >&2

# Extract AI agent configs (.cursor/, .claude/, etc.)
log "Extracting AI agent configs..."
AGENT_INFO=$("$SCRIPT_DIR/extract-agent-configs.sh" "$PROJECT_DIR")
[ "$VERBOSE" = true ] && echo "$AGENT_INFO" | jq . >&2

# Generate file map
log "Generating file map..."
FILE_MAP=$("$SCRIPT_DIR/generate-file-map.sh" "$PROJECT_DIR" 2>/dev/null || echo "")

# Detect golden samples
log "Detecting golden samples..."
GOLDEN_SAMPLES=$("$SCRIPT_DIR/detect-golden-samples.sh" "$PROJECT_DIR" 2>/dev/null || echo "")

# Detect utilities
log "Detecting utilities..."
UTILITIES_LIST=$("$SCRIPT_DIR/detect-utilities.sh" "$PROJECT_DIR" 2>/dev/null || echo "")

# Detect heuristics
log "Detecting heuristics..."
HEURISTICS=$("$SCRIPT_DIR/detect-heuristics.sh" "$PROJECT_DIR" 2>/dev/null || echo "")

# Extract quality configs (detailed linter/formatter settings)
log "Extracting quality configs..."
QUALITY_CONFIG=$("$SCRIPT_DIR/extract-quality-configs.sh" "$PROJECT_DIR" 2>/dev/null || echo '{}')
[ "$VERBOSE" = true ] && echo "$QUALITY_CONFIG" | jq . >&2

# Extract CI commands
log "Extracting CI commands..."
CI_INFO=$("$SCRIPT_DIR/extract-ci-commands.sh" "$PROJECT_DIR" 2>/dev/null || echo '{}')
[ "$VERBOSE" = true ] && echo "$CI_INFO" | jq . >&2

# Extract CI rules (version matrices, quality gates, coverage thresholds)
log "Extracting CI rules..."
CI_RULES=$("$SCRIPT_DIR/extract-ci-rules.sh" "$PROJECT_DIR" 2>/dev/null || echo '{}')
[ "$VERBOSE" = true ] && echo "$CI_RULES" | jq . >&2

# Extract GitHub repository settings
log "Extracting GitHub settings..."
GITHUB_SETTINGS=$("$SCRIPT_DIR/extract-github-settings.sh" "$PROJECT_DIR" 2>/dev/null || echo '{}')
[ "$VERBOSE" = true ] && echo "$GITHUB_SETTINGS" | jq . >&2

# Extract GitHub rulesets
log "Extracting GitHub rulesets..."
GITHUB_RULESETS=$("$SCRIPT_DIR/extract-github-rulesets.sh" "$PROJECT_DIR" 2>/dev/null || echo '{"rulesets":[],"merge_queue":false,"required_checks":[],"signed_commits":false}')
[ "$VERBOSE" = true ] && echo "$GITHUB_RULESETS" | jq . >&2

# Extract ADRs
log "Extracting ADRs..."
ADR_INFO=$("$SCRIPT_DIR/extract-adrs.sh" "$PROJECT_DIR" 2>/dev/null || echo '{"adr_count":0,"adr_directory":null,"adrs":[]}')
[ "$VERBOSE" = true ] && echo "$ADR_INFO" | jq . >&2

# Extract architecture / module boundary rules
log "Extracting architecture rules..."
ARCH_RULES=$("$SCRIPT_DIR/extract-architecture-rules.sh" "$PROJECT_DIR" 2>/dev/null || echo '{}')
[ "$VERBOSE" = true ] && echo "$ARCH_RULES" | jq . >&2

# Determine command source confidence
# Priority: CI > Makefile > package.json/composer.json > fallback defaults
get_command_source() {
    local ci_system
    ci_system=$(echo "$CI_INFO" | jq -r '.ci_system // "none"')

    if [ "$ci_system" != "none" ] && [ "$ci_system" != "null" ]; then
        local ci_commands
        ci_commands=$(echo "$CI_INFO" | jq -r '.github_actions.run_commands // .gitlab_ci.script_commands // [] | length')
        if [ "$ci_commands" -gt 0 ]; then
            echo "CI ($ci_system)"
            return 0
        fi
    fi

    if [ -f "Makefile" ]; then
        echo "Makefile"
        return 0
    fi

    case "$LANGUAGE" in
        "typescript"|"javascript")
            [ -f "package.json" ] && echo "package.json" && return 0
            ;;
        "php")
            [ -f "composer.json" ] && echo "composer.json" && return 0
            ;;
        "python")
            [ -f "pyproject.toml" ] && echo "pyproject.toml" && return 0
            [ -f "setup.py" ] && echo "setup.py" && return 0
            ;;
        "go")
            [ -f "go.mod" ] && echo "go.mod" && return 0
            ;;
    esac

    echo "defaults"
}

COMMAND_SOURCE=$(get_command_source)
log "Command source: $COMMAND_SOURCE"

# Analyze git history for conventions
log "Analyzing git history..."
GIT_HISTORY=$("$SCRIPT_DIR/analyze-git-history.sh" "$PROJECT_DIR" 2>/dev/null || echo '{}')
[ "$VERBOSE" = true ] && echo "$GIT_HISTORY" | jq . >&2

# Helper: Safe jq extraction that filters null values
# Usage: jq_safe "$json" '.path.to.value'
jq_safe() {
    local json="$1"
    local path="$2"
    local result
    result=$(echo "$json" | jq -r "$path // empty | select(. != null and . != \"null\" and . != \"\")")
    echo "$result"
}

# Helper: Build quality standards from quality config
build_quality_standards() {
    local quality_json="$1"
    local standards=""

    # Get detected tools
    local tools
    tools=$(echo "$quality_json" | jq -r '.detected_tools | if . and . != null then join(", ") else "" end | select(. != "")')
    [ -n "$tools" ] && standards="$standards- Quality tools: $tools\n"

    # PHPStan level
    local phpstan_level
    phpstan_level=$(jq_safe "$quality_json" '.phpstan.level')
    [ -n "$phpstan_level" ] && standards="$standards- PHPStan level: $phpstan_level (do not lower)\n"

    # TypeScript strict mode
    local ts_strict
    ts_strict=$(jq_safe "$quality_json" '.typescript.strict')
    [ "$ts_strict" = "true" ] && standards="$standards- TypeScript: strict mode enabled\n"

    # Line length settings
    local line_length
    line_length=$(jq_safe "$quality_json" '.golangci_lint.line_length // .prettier.print_width // .black.line_length // .ruff.line_length')
    [ -n "$line_length" ] && standards="$standards- Line length: $line_length\n"

    # ESLint extends
    local eslint_extends
    eslint_extends=$(jq_safe "$quality_json" '.eslint.extends')
    [ -n "$eslint_extends" ] && standards="$standards- ESLint: extends $eslint_extends\n"

    # PHP-CS-Fixer ruleset
    local php_cs_ruleset
    php_cs_ruleset=$(jq_safe "$quality_json" '.php_cs_fixer.rule_set')
    [ -n "$php_cs_ruleset" ] && standards="$standards- PHP-CS-Fixer: $php_cs_ruleset rules\n"

    # Mypy strict
    local mypy_strict
    mypy_strict=$(jq_safe "$quality_json" '.mypy.strict')
    [ "$mypy_strict" = "True" ] || [ "$mypy_strict" = "true" ] && standards="$standards- Mypy: strict mode enabled\n"

    # Ruff select rules
    local ruff_select
    ruff_select=$(jq_safe "$quality_json" '.ruff.select')
    [ -n "$ruff_select" ] && standards="$standards- Ruff: $ruff_select\n"

    # Default if nothing found
    [ -z "$standards" ] && standards="- Follow project linting and formatting rules\n- Write tests for new functionality\n- Keep functions focused and well-documented\n"

    echo -e "$standards"
}

# Helper: Build CI/Quality Gates section from CI rules
build_ci_rules_section() {
    local ci_json="$1"
    local section=""

    local platform
    platform=$(echo "$ci_json" | jq -r '.ci_platform // empty')
    [[ -z "$platform" ]] && return 0

    section="## CI/Quality Gates\n"
    section="${section}> Platform: ${platform}\n\n"

    # Version matrix
    local versions_block=""
    local php_versions
    php_versions=$(echo "$ci_json" | jq -r '.php_versions // [] | if length > 0 then "PHP " + join(", ") else "" end')
    [[ -n "$php_versions" ]] && versions_block="${versions_block}- ${php_versions}\n"

    local node_versions
    node_versions=$(echo "$ci_json" | jq -r '.node_versions // [] | if length > 0 then "Node " + join(", ") else "" end')
    [[ -n "$node_versions" ]] && versions_block="${versions_block}- ${node_versions}\n"

    local go_version
    go_version=$(echo "$ci_json" | jq -r '.go_version // empty')
    [[ -n "$go_version" ]] && versions_block="${versions_block}- Go ${go_version}\n"

    local python_versions
    python_versions=$(echo "$ci_json" | jq -r '.python_versions // [] | if length > 0 then "Python " + join(", ") else "" end')
    [[ -n "$python_versions" ]] && versions_block="${versions_block}- ${python_versions}\n"

    if [[ -n "$versions_block" ]]; then
        section="${section}### Version Matrix\n${versions_block}\n"
    fi

    # Quality gates
    local gates
    gates=$(echo "$ci_json" | jq -r '.quality_gates // [] | if length > 0 then .[] else empty end')
    if [[ -n "$gates" ]]; then
        section="${section}### Quality Gates (must pass before merge)\n"
        while IFS= read -r gate; do
            section="${section}- \`${gate}\`\n"
        done <<< "$gates"
        section="${section}\n"
    fi

    # Coverage threshold
    local coverage
    coverage=$(echo "$ci_json" | jq -r '.coverage_threshold // empty')
    [[ -n "$coverage" ]] && section="${section}### Coverage\n- Minimum threshold: ${coverage}\n\n"

    # Security workflows
    local sec_wfs
    sec_wfs=$(echo "$ci_json" | jq -r '.security_workflows // [] | if length > 0 then .[] else empty end')
    if [[ -n "$sec_wfs" ]]; then
        section="${section}### Security Workflows\n"
        while IFS= read -r wf; do
            section="${section}- \`${wf}\`\n"
        done <<< "$sec_wfs"
        section="${section}\n"
    fi

    # Pinned actions
    local pinned
    pinned=$(echo "$ci_json" | jq -r '.pinned_actions // empty')
    if [[ "$pinned" == "true" ]]; then
        section="${section}### Constraints\n- Actions are SHA-pinned — maintain pinning when updating\n"
    fi

    # Linter configs
    local linters
    linters=$(echo "$ci_json" | jq -r '.linter_configs // [] | if length > 0 then .[] else empty end')
    if [[ -n "$linters" ]]; then
        section="${section}- Linter configs: "
        local first=true
        while IFS= read -r cfg; do
            if $first; then
                section="${section}\`${cfg}\`"
                first=false
            else
                section="${section}, \`${cfg}\`"
            fi
        done <<< "$linters"
        section="${section}\n"
    fi

    echo -e "$section"
}

# Helper: Build module boundaries section from architecture rules
build_module_boundaries() {
    local arch_json="$1"
    local section=""

    # Check if we have any data
    local framework
    framework=$(echo "$arch_json" | jq -r '.framework // empty' 2>/dev/null)
    [ -z "$framework" ] && return 0

    local rule_count
    rule_count=$(echo "$arch_json" | jq -r '.rules | length // 0' 2>/dev/null)
    local internal_count
    internal_count=$(echo "$arch_json" | jq -r '.internal_packages | length // 0' 2>/dev/null)
    local has_layers
    has_layers=$(echo "$arch_json" | jq -r '.layer_definitions | length > 0' 2>/dev/null)

    [ "$rule_count" = "0" ] && [ "$internal_count" = "0" ] && [ "$has_layers" != "true" ] && return 0

    section="## Module Boundaries\n"
    section="${section}> Source: ${framework}\n\n"

    # Internal packages (Go)
    if [ "$internal_count" -gt 0 ]; then
        section="${section}### Internal Packages (compiler-enforced)\n"
        while IFS= read -r pkg; do
            section="${section}- \`${pkg}\`\n"
        done < <(echo "$arch_json" | jq -r '.internal_packages[]' 2>/dev/null)
        section="${section}\n"
    fi

    # Layer definitions
    if [ "$has_layers" = "true" ]; then
        local arch_pattern
        arch_pattern=$(echo "$arch_json" | jq -r '.layer_definitions.architecture_pattern // empty' 2>/dev/null)
        if [ -n "$arch_pattern" ]; then
            section="${section}### Architecture Pattern\n"
            section="${section}- ${arch_pattern}\n\n"
        fi

        # Non-pattern layer definitions (deptrac etc.)
        local layer_keys
        layer_keys=$(echo "$arch_json" | jq -r '.layer_definitions | keys[] | select(. != "architecture_pattern")' 2>/dev/null)
        if [ -n "$layer_keys" ]; then
            section="${section}### Layers\n"
            while IFS= read -r layer; do
                local values
                values=$(echo "$arch_json" | jq -r --arg l "$layer" '.layer_definitions[$l] | if type == "array" then join(", ") else tostring end' 2>/dev/null)
                section="${section}- **${layer}**: ${values}\n"
            done <<< "$layer_keys"
            section="${section}\n"
        fi
    fi

    # Dependency rules
    if [ "$rule_count" -gt 0 ]; then
        section="${section}### Dependency Rules\n"
        section="${section}| Source | Target | Rule | Reason |\n"
        section="${section}|--------|--------|------|--------|\n"
        while IFS= read -r rule_line; do
            section="${section}${rule_line}\n"
        done < <(echo "$arch_json" | jq -r '.rules[] |
            "| " + .source + " | `" + .target + "` | " + .type + " | " + (.reason // "-") + " |"' 2>/dev/null)
    fi

    echo -e "$section"
}

# Helper: Build workflow section from git history
# build_workflow_info <git history json> [github settings json]
build_workflow_info() {
    local git_json="$1"
    local workflow=""

    # Commit convention
    local convention
    convention=$(echo "$git_json" | jq -r '.commit_convention.convention // "unknown" | select(. != null)')
    [ -z "$convention" ] && convention="unknown"
    local confidence
    confidence=$(echo "$git_json" | jq -r '.commit_convention.confidence // 0 | select(. != null)')
    [ -z "$confidence" ] && confidence=0

    if [ "$convention" != "unknown" ] && [ "$confidence" -gt 30 ]; then
        case "$convention" in
            "conventional-commits")
                workflow="$workflow- Commits: Use Conventional Commits (feat:, fix:, docs:, etc.)\n"
                ;;
            "tag-prefix")
                workflow="$workflow- Commits: Use [TAG] prefix style\n"
                ;;
            "emoji")
                workflow="$workflow- Commits: Use emoji prefixes\n"
                ;;
            "ticket-reference")
                workflow="$workflow- Commits: Include ticket references (JIRA-123, #123)\n"
                ;;
        esac
    fi

    # Merge strategy. History says what was done; the repository settings, when
    # known, say what is allowed now. A method the settings do not allow is not
    # advice, and when they allow exactly one, that one is.
    local merge_strategy method allowed
    merge_strategy=$(echo "$git_json" | jq -r '.merge_strategy.strategy // "unknown"')
    case "$merge_strategy" in
        "squash-and-merge") method=squash ;;
        "merge-commits") method=merge ;;
        *) method="" ;;
    esac
    allowed=$(echo "${2:-{\}}" | jq -r '(.merge_strategies // []) | join(" ")' 2>/dev/null || true)
    if [ -n "$allowed" ]; then
        [[ -n "$method" && " $allowed " != *" $method "* ]] && method=""
        [[ -z "$method" && "$allowed" != *" "* ]] && method="$allowed"
    fi
    case "$method" in
        squash) workflow="$workflow- PRs: Squash and merge\n" ;;
        merge) workflow="$workflow- PRs: Create merge commits\n" ;;
        rebase) workflow="$workflow- PRs: Rebase and merge\n" ;;
    esac

    # Branch naming
    local branch_pattern
    branch_pattern=$(echo "$git_json" | jq -r '.branch_naming.pattern // "unknown"')
    local uses_feature
    uses_feature=$(echo "$git_json" | jq -r '.branch_naming.uses_feature_branches // false')

    if [ "$uses_feature" = "true" ]; then
        workflow="$workflow- Branches: feature/, fix/, hotfix/ prefixes\n"
    elif [ "$branch_pattern" = "ticket-based" ]; then
        workflow="$workflow- Branches: Include ticket reference in name\n"
    fi

    # Release pattern
    local release_pattern
    release_pattern=$(echo "$git_json" | jq -r '.releases.pattern // "unknown"')
    local uses_v
    uses_v=$(echo "$git_json" | jq -r '.releases.uses_v_prefix // false')

    if [ "$release_pattern" = "semver" ]; then
        [ "$uses_v" = "true" ] && workflow="$workflow- Releases: Semantic versioning (vX.Y.Z)\n" || workflow="$workflow- Releases: Semantic versioning (X.Y.Z)\n"
    elif [ "$release_pattern" = "calver" ]; then
        workflow="$workflow- Releases: Calendar versioning (YYYY.MM.DD)\n"
    fi

    # Default branch
    local default_branch
    default_branch=$(echo "$git_json" | jq -r '.default_branch // "main"')
    [ -n "$default_branch" ] && [ "$default_branch" != "null" ] && workflow="$workflow- Default branch: $default_branch\n"

    echo -e "$workflow"
}

# Generate root AGENTS.md
ROOT_FILE="$PROJECT_DIR/AGENTS.md"

# A symlink counts as existing, dangling or not: [ -f ] follows it, and a
# dangling one would read as absent and be written at its target.
if { [ -e "$ROOT_FILE" ] || [ -L "$ROOT_FILE" ]; } && [ "$FORCE" = false ] && [ "$UPDATE_ONLY" = false ]; then
    emit_op keep agents-file "$ROOT_FILE" reason "already exists"
    log "Root AGENTS.md already exists, skipping (use --force to regenerate)"
elif [ "$DRY_RUN" = true ]; then
    emit_op write agents-file "$ROOT_FILE"
    echo "[DRY-RUN] Would create/update: $ROOT_FILE"
else
    log "Generating root AGENTS.md..."

    # Select template
    if [ "$STYLE" = "verbose" ]; then
        TEMPLATE="$TEMPLATE_DIR/root-verbose.md"
    else
        TEMPLATE="$TEMPLATE_DIR/root-thin.md"
    fi

    # Prepare template variables
    declare -A vars
    vars[TIMESTAMP]=$(get_timestamp)
    vars[VERIFIED_TIMESTAMP]="never"
    vars[COMMAND_SOURCE]="$COMMAND_SOURCE"
    vars[LANGUAGE_CONVENTIONS]=$(get_language_conventions "$LANGUAGE" "$VERSION")

    # Command extraction - only set if non-empty (leaves placeholder for row deletion)
    set_if_present() {
        local key="$1"
        local value="$2"
        if [ -n "$value" ] && [ "$value" != "null" ]; then
            vars[$key]="$value"
        fi
        return 0
    }
    set_if_present INSTALL_CMD "$(echo "$COMMANDS" | jq -r '.install // empty')"
    set_if_present TYPECHECK_CMD "$(echo "$COMMANDS" | jq -r '.typecheck // empty')"
    set_if_present LINT_CMD "$(echo "$COMMANDS" | jq -r '.lint // empty')"
    set_if_present FORMAT_CMD "$(echo "$COMMANDS" | jq -r '.format // empty')"
    set_if_present TEST_CMD "$(echo "$COMMANDS" | jq -r '.test // empty')"
    set_if_present TEST_SINGLE_CMD "$(echo "$COMMANDS" | jq -r '.test_single // empty')"
    set_if_present BUILD_CMD "$(echo "$COMMANDS" | jq -r '.build // empty')"

    # Time estimates - check verification JSON first, then use heuristics
    VERIFICATION_JSON="$PROJECT_DIR/.agents/command-verification.json"
    get_verified_time() {
        local pattern="$1"
        local default="$2"
        if [ -f "$VERIFICATION_JSON" ]; then
            local duration_ms
            # Try to find command in verification JSON using regex pattern
            duration_ms=$(jq -r --arg pattern "$pattern" '.commands | to_entries[] | select(.key | test($pattern; "i")) | .value.duration_ms // empty' "$VERIFICATION_JSON" 2>/dev/null | head -1)
            if [ -n "$duration_ms" ] && [ "$duration_ms" != "null" ] && [ "$duration_ms" -gt 0 ] 2>/dev/null; then
                # Convert ms to human-readable
                if [ "$duration_ms" -lt 1000 ]; then
                    echo "~${duration_ms}ms"
                elif [ "$duration_ms" -lt 60000 ]; then
                    echo "~$((duration_ms / 1000))s"
                else
                    echo "~$((duration_ms / 60000))m"
                fi
                return
            fi
        fi
        echo "$default"
    }

    # Check if we have verification data
    if [ -f "$VERIFICATION_JSON" ]; then
        verified_at=$(jq -r '.verified_at // empty' "$VERIFICATION_JSON" 2>/dev/null | cut -dT -f1)
        if [ -n "$verified_at" ]; then
            vars[VERIFIED_TIMESTAMP]="$verified_at"
            vars[VERIFIED_STATUS]=" (verified ✓)"
        else
            vars[VERIFIED_TIMESTAMP]="never"
            vars[VERIFIED_STATUS]=" (unverified)"
        fi
    else
        vars[VERIFIED_TIMESTAMP]="never"
        vars[VERIFIED_STATUS]=" (unverified)"
    fi

    vars[TYPECHECK_TIME]=$(get_verified_time "typecheck" "~15s")
    vars[LINT_TIME]=$(get_verified_time "lint|cs-fixer|eslint" "~10s")
    vars[FORMAT_TIME]=$(get_verified_time "format|prettier|black|cs-fixer fix$" "~5s")
    vars[TEST_TIME]=$(get_verified_time "test|phpunit|jest|pytest" "~30s")
    vars[BUILD_TIME]=$(get_verified_time "build" "~30s")

    # File map
    vars[FILE_MAP]="$FILE_MAP"

    # Golden samples, utilities, and heuristics from detection scripts
    vars[GOLDEN_SAMPLES]="$GOLDEN_SAMPLES"
    vars[UTILITIES_LIST]="$UTILITIES_LIST"

    # Add workflow conventions from git analysis to heuristics
    workflow_info=$(build_workflow_info "$GIT_HISTORY" "$GITHUB_SETTINGS")
    workflow_heuristics=""
    # Convert workflow info to heuristic table rows
    if echo "$workflow_info" | grep -q "Commits:"; then
        commit_convention=$(echo "$workflow_info" | grep "Commits:" | sed 's/- Commits: //')
        workflow_heuristics="${workflow_heuristics}| Committing | $commit_convention |
"
    fi
    if echo "$workflow_info" | grep -q "PRs:"; then
        pr_strategy=$(echo "$workflow_info" | grep "PRs:" | sed 's/- PRs: //')
        workflow_heuristics="${workflow_heuristics}| Merging PRs | $pr_strategy |
"
    fi
    if echo "$workflow_info" | grep -q "Branches:"; then
        branch_convention=$(echo "$workflow_info" | grep "Branches:" | sed 's/- Branches: //')
        workflow_heuristics="${workflow_heuristics}| Creating branches | Use $branch_convention |
"
    fi

    # Combine detected heuristics with workflow heuristics
    # Ensure no trailing blank lines
    combined_heuristics=""
    if [ -n "$HEURISTICS" ]; then
        # Trim blank lines and trailing whitespace
        combined_heuristics=$(printf '%s' "$HEURISTICS" | sed '/^[[:space:]]*$/d')
    fi
    if [ -n "$workflow_heuristics" ]; then
        # Add newline separator only if both have content
        if [ -n "$combined_heuristics" ]; then
            combined_heuristics="${combined_heuristics}
${workflow_heuristics}"
        else
            combined_heuristics="$workflow_heuristics"
        fi
    fi
    # Remove any trailing newlines
    combined_heuristics=$(printf '%s' "$combined_heuristics" | sed '/^[[:space:]]*$/d')
    vars[HEURISTICS]="$combined_heuristics"

    # Repository settings (from GitHub API)
    build_repo_settings() {
        local settings_json="$1"
        local available
        available=$(echo "$settings_json" | jq -r '.available // false')

        [ "$available" != "true" ] && return 0

        local content=""
        local default_branch merge_strategies required_approvals required_checks require_up_to_date

        default_branch=$(echo "$settings_json" | jq -r '.default_branch')
        merge_strategies=$(echo "$settings_json" | jq -r '.merge_strategies | join(", ")')
        required_approvals=$(echo "$settings_json" | jq -r '.required_approvals')
        required_checks=$(echo "$settings_json" | jq -r 'if .required_checks | length > 0 then .required_checks | map("`" + . + "`") | join(", ") else "" end')
        require_up_to_date=$(echo "$settings_json" | jq -r '.require_up_to_date')

        content="- **Default branch:** \`$default_branch\`\n"
        [ -n "$merge_strategies" ] && content="${content}- **Merge strategy:** $merge_strategies\n"
        [ "$required_approvals" != "0" ] && [ "$required_approvals" != "null" ] && content="${content}- **Required approvals:** $required_approvals\n"
        [ -n "$required_checks" ] && content="${content}- **Required checks:** $required_checks\n"
        [ "$require_up_to_date" = "true" ] && content="${content}- **Require up-to-date:** yes — rebase before merge\n"

        printf '%b' "$content"
    }

    # Append ruleset information to repo settings
    build_ruleset_settings() {
        local rulesets_json="$1"
        local ruleset_count
        ruleset_count=$(echo "$rulesets_json" | jq '.rulesets | length')

        [ "$ruleset_count" -eq 0 ] && return 0

        local content=""
        local merge_queue signed_commits required_checks

        merge_queue=$(echo "$rulesets_json" | jq -r '.merge_queue')
        signed_commits=$(echo "$rulesets_json" | jq -r '.signed_commits')
        required_checks=$(echo "$rulesets_json" | jq -r 'if .required_checks | length > 0 then .required_checks | map("`" + . + "`") | join(", ") else "" end')

        [ "$merge_queue" = "true" ] && content="${content}- **Merge queue:** enabled — PRs merge via queue, not direct merge\n"
        [ "$signed_commits" = "true" ] && content="${content}- **Signed commits:** required\n"
        [ -n "$required_checks" ] && content="${content}- **Required checks (rulesets):** $required_checks\n"

        # List active rulesets
        local ruleset_names
        ruleset_names=$(echo "$rulesets_json" | jq -r '[.rulesets[].name] | join(", ")')
        [ -n "$ruleset_names" ] && content="${content}- **Active rulesets:** $ruleset_names\n"

        printf '%b' "$content"
    }
    vars[REPO_SETTINGS]=$(build_repo_settings "$GITHUB_SETTINGS")
    ruleset_settings=$(build_ruleset_settings "$GITHUB_RULESETS")
    if [ -n "$ruleset_settings" ]; then
        vars[REPO_SETTINGS]="${vars[REPO_SETTINGS]}${vars[REPO_SETTINGS]:+$'\n'}${ruleset_settings}"
    fi

    # Module boundaries (from architecture rules)
    vars[MODULE_BOUNDARIES]=$(build_module_boundaries "$ARCH_RULES")

    # CI/Quality Gates section (from CI rules)
    vars[CI_RULES_SECTION]=$(build_ci_rules_section "$CI_RULES")

    # Key Decisions (from ADRs)
    build_key_decisions() {
        local adr_json="$1"
        local adr_count
        adr_count=$(echo "$adr_json" | jq -r '.adr_count')

        [ "$adr_count" -eq 0 ] || [ "$adr_count" = "null" ] && return 0

        local adr_dir content=""
        adr_dir=$(echo "$adr_json" | jq -r '.adr_directory')

        for i in $(seq 0 $((adr_count - 1))); do
            local title status summary file
            file=$(echo "$adr_json" | jq -r ".adrs[$i].file")
            title=$(echo "$adr_json" | jq -r ".adrs[$i].title")
            status=$(echo "$adr_json" | jq -r ".adrs[$i].status")
            summary=$(echo "$adr_json" | jq -r ".adrs[$i].summary")

            # Show status badge only for non-Accepted (Accepted is the norm)
            local status_badge=""
            if [ "$status" != "Accepted" ] && [ "$status" != "Unknown" ]; then
                status_badge=" [$status]"
            fi

            content="${content}- **${title}**${status_badge} — ${summary} → [\`${file}\`](${adr_dir}/${file})\n"
        done

        printf '%b' "$content"
    }
    vars[KEY_DECISIONS]=$(build_key_decisions "$ADR_INFO")

    # Contribution rules — detect issue-before-PR, AI disclosure, PR templates
    build_contribution_rules() {
        local rules=""

        # Check CONTRIBUTING.md for issue-before-PR
        if [ -f "CONTRIBUTING.md" ]; then
            if grep -qi "open an issue\|issue first\|issue before\|create an issue" CONTRIBUTING.md 2>/dev/null; then
                rules="$rules\n- **Issue first**: Open an issue and get approval before submitting a PR"
            fi
            if grep -qi "AI\|artificial intelligence\|copilot\|generated\|LLM\|disclose" CONTRIBUTING.md 2>/dev/null; then
                rules="$rules\n- **AI disclosure**: This project requires disclosure of AI-assisted contributions in PR descriptions"
            fi
        fi

        # Check PR template for issue linking
        for tmpl in .github/pull_request_template.md .github/PULL_REQUEST_TEMPLATE/*.md; do
            if [ -f "$tmpl" ] && grep -qi "Fixes #\|Closes #\|Related issue\|Issue number" "$tmpl" 2>/dev/null; then
                rules="$rules\n- **Link issues**: PR template requires linking to an issue (Fixes #NNN)"
                break
            fi
        done

        # Check branch protection for linked issues requirement
        local protection
        protection=$(echo "$GITHUB_SETTINGS" | jq -r '.required_linked_issues // false' 2>/dev/null)
        if [ "$protection" = "true" ]; then
            rules="$rules\n- **Linked issues required**: Branch protection requires PRs to reference an issue"
        fi

        [ -n "$rules" ] && printf '%b' "$rules" || true
    }
    vars[CONTRIBUTION_RULES]=$(build_contribution_rules)

    # Changelog: where changes are recorded. Only facts the tree shows; who
    # writes the entry (each PR or the release PR) is not derivable from files,
    # so it is marked for the agent to fill in from the last merged PRs.
    build_changelog_rule() {
        local file format where="" docs_page="" f
        file=$(echo "$DOCS_INFO" | jq -r '.changelog.file // empty' 2>/dev/null)
        format=$(echo "$DOCS_INFO" | jq -r '.changelog.format // empty' 2>/dev/null)
        for f in Documentation/Changelog.rst Documentation/Changelog/Index.rst Documentation/ChangeLog/Index.rst; do
            if [ -f "$f" ]; then
                docs_page="$f"
                break
            fi
        done

        if [ -n "$file" ]; then
            where="changes are recorded in [\`$file\`]($file)"
            [ "$format" = "keepachangelog" ] && where="$where (Keep a Changelog)"
        elif [ -n "$docs_page" ]; then
            where="changes are recorded in [\`$docs_page\`]($docs_page)"
            docs_page=""
        fi
        if [ -d "changelog.d" ]; then
            if [ -f "changelog.d/README.md" ]; then
                where="$where; pull requests add a fragment under \`changelog.d/\` (format: [\`changelog.d/README.md\`](changelog.d/README.md))"
            else
                where="$where; fragments live under \`changelog.d/\`"
            fi
        fi
        [ -n "$docs_page" ] && where="$where; the manual's changelog page is \`$docs_page\`"

        if [ -z "$where" ]; then
            printf '%s' "TODO: no changelog file found — name where changes are recorded (for example the release notes) and which pull request writes them"
        else
            printf '%s' "${where#; }. TODO: name which pull request writes the entry (each PR or the release PR), as the last merged PRs show it"
        fi
    }
    vars[CHANGELOG_RULE]=$(build_changelog_rule)

    # Codebase state - detect migrations, deprecations
    codebase_state=""
    [ -d "migrations" ] || [ -d "db/migrate" ] && codebase_state="$codebase_state\n- Database migrations present in migrations/"
    [ -d "prisma/migrations" ] && codebase_state="$codebase_state\n- Prisma migrations present"
    grep -rq "DEPRECATED\|@deprecated" --include="*.ts" --include="*.go" --include="*.php" --include="*.py" . 2>/dev/null && \
        codebase_state="$codebase_state\n- Contains deprecated code (grep for @deprecated)"
    [ -z "$codebase_state" ] && codebase_state="- No known migrations or tech debt documented"
    vars[CODEBASE_STATE]=$(echo -e "$codebase_state")

    # Terminology - leave empty for now, needs manual curation
    vars[TERMINOLOGY]=""

    # Scope index
    vars[SCOPE_INDEX]=$(build_scope_index "$SCOPES_INFO")

    # Verbose template additional vars
    if [ "$STYLE" = "verbose" ]; then
        # Use extracted documentation data where available
        readme_desc=$(echo "$DOCS_INFO" | jq -r '.readme.description // empty')
        if [ -n "$readme_desc" ]; then
            vars[PROJECT_DESCRIPTION]="$readme_desc"
        else
            vars[PROJECT_DESCRIPTION]="TODO: Add project description"
        fi

        vars[LANGUAGE]="$LANGUAGE"
        vars[VERSION]="$VERSION"
        vars[BUILD_TOOL]=$(echo "$PROJECT_INFO" | jq -r '.build_tool')
        vars[FRAMEWORK]=$(echo "$PROJECT_INFO" | jq -r '.framework')
        vars[PROJECT_TYPE]="$PROJECT_TYPE"
        vars[BUILD_CMD]=$(echo "$COMMANDS" | jq -r '.build')

        # Extract quality standards from contributing guidelines AND quality config
        contributing_rules=$(echo "$DOCS_INFO" | jq -r '.contributing.code_style // empty')
        quality_standards=$(build_quality_standards "$QUALITY_CONFIG")
        if [ -n "$contributing_rules" ] && [ "$contributing_rules" != "null" ]; then
            # Combine contributing rules with detected quality config
            vars[QUALITY_STANDARDS]="$contributing_rules
$quality_standards"
        else
            vars[QUALITY_STANDARDS]="$quality_standards"
        fi

        # Extract security guidelines
        security_policy=$(echo "$DOCS_INFO" | jq -r '.security.policy // empty')
        if [ -n "$security_policy" ] && [ "$security_policy" != "null" ]; then
            vars[SECURITY_SPECIFIC]="$security_policy"
        else
            vars[SECURITY_SPECIFIC]="- Report vulnerabilities via security@project or SECURITY.md
- Never commit secrets or credentials"
        fi

        vars[TEST_COVERAGE]="40"

        # Try to get test commands from CI info or fall back to detected commands
        test_cmd=$(echo "$COMMANDS" | jq -r '.test')
        ci_system=$(echo "$CI_INFO" | jq -r '.ci_system // "none"')

        # Look for specific test commands in CI
        ci_test_cmd=""
        case "$ci_system" in
            "github-actions")
                ci_test_cmd=$(echo "$CI_INFO" | jq -r '.github_actions.run_commands[]? | select(. | test("test|phpunit|jest|pytest|go test"; "i"))' 2>/dev/null | head -1)
                ;;
            "gitlab-ci")
                ci_test_cmd=$(echo "$CI_INFO" | jq -r '.gitlab_ci.script_commands[]? | select(. | test("test|phpunit|jest|pytest|go test"; "i"))' 2>/dev/null | head -1)
                ;;
        esac

        vars[TEST_FAST_CMD]="${test_cmd:-make test}"
        if [ -n "$ci_test_cmd" ]; then
            vars[TEST_FULL_CMD]="$ci_test_cmd"
        else
            vars[TEST_FULL_CMD]="${test_cmd:-make test}"
        fi

        # Check if docs exist
        [ -d "./docs" ] && vars[ARCHITECTURE_DOC]="./docs/architecture.md" || vars[ARCHITECTURE_DOC]="(not available)"
        [ -d "./docs" ] && vars[API_DOC]="./docs/api.md" || vars[API_DOC]="(not available)"

        # Use extracted contributing file path or default
        contrib_file=$(echo "$DOCS_INFO" | jq -r '.contributing.file // empty')
        if [ -n "$contrib_file" ] && [ "$contrib_file" != "null" ]; then
            vars[CONTRIBUTING_DOC]="./$contrib_file"
        else
            vars[CONTRIBUTING_DOC]="./CONTRIBUTING.md"
        fi
    fi

    # Language-specific conflict resolution, never-do rules, and code examples
    case "$LANGUAGE" in
        "go")
            vars[LANGUAGE_SPECIFIC_CONFLICT_RESOLUTION]="- For Go-specific patterns, defer to language idioms and standard library conventions"
            vars[LANGUAGE_SPECIFIC_NEVER]="- Commit go.sum without go.mod changes"
            vars[CODE_EXAMPLES]="**Good:** \`if err != nil { return fmt.Errorf(\"op failed: %w\", err) }\`
**Avoid:** \`if err != nil { panic(err) }\` or ignoring errors"
            vars[GOOD_EXAMPLE]="\`\`\`go
// Wrap errors with context
if err != nil {
    return fmt.Errorf(\"failed to process %s: %w\", item, err)
}

// Use structured logging
slog.Info(\"operation completed\", \"item\", item, \"duration\", elapsed)
\`\`\`"
            vars[BAD_EXAMPLE]="\`\`\`go
// Don't panic on recoverable errors
if err != nil {
    panic(err)  // Use return instead
}

// Don't use fmt.Println for logging
fmt.Println(\"something happened\")  // Use slog/log package
\`\`\`"
            ;;
        "php")
            vars[LANGUAGE_SPECIFIC_CONFLICT_RESOLUTION]="- For PHP-specific patterns, follow PSR standards"
            vars[LANGUAGE_SPECIFIC_NEVER]="- Commit composer.lock without composer.json changes
- Modify core framework files"
            vars[CODE_EXAMPLES]="**Good:** Constructor injection, typed properties, return types
**Avoid:** Service locator, untyped parameters, \`@var\` without types"
            vars[GOOD_EXAMPLE]="\`\`\`php
// Use constructor injection with typed properties
public function __construct(
    private readonly UserRepository \$userRepository,
    private readonly LoggerInterface \$logger,
) {}

// Always use return types and parameter types
public function findById(int \$id): ?User
{
    return \$this->userRepository->find(\$id);
}
\`\`\`"
            vars[BAD_EXAMPLE]="\`\`\`php
// Don't use service locator or globals
\$user = Container::get('user.repository')->find(\$id);

// Don't omit types
public function process(\$data)  // Missing types
{
    return \$data;  // Missing return type
}
\`\`\`"
            ;;
        "typescript")
            vars[LANGUAGE_SPECIFIC_CONFLICT_RESOLUTION]="- For TypeScript/JavaScript patterns, follow project eslint/prettier config"
            vars[LANGUAGE_SPECIFIC_NEVER]="- Commit package-lock.json without package.json changes
- Use any type without justification"
            vars[CODE_EXAMPLES]="**Good:** Strict types, async/await, destructuring
**Avoid:** \`any\` type, callback hell, mutable state in components"
            vars[GOOD_EXAMPLE]="\`\`\`typescript
// Use explicit types and async/await
async function fetchUser(id: string): Promise<User | null> {
  const response = await api.get<User>(\\\`/users/\\\${id}\\\`);
  return response.data;
}

// Use destructuring and const
const { name, email } = user;
\`\`\`"
            vars[BAD_EXAMPLE]="\`\`\`typescript
// Don't use 'any' without justification
function process(data: any): any {  // Type properly
  return data;
}

// Don't use var or nested callbacks
var result;  // Use const/let
fetchData(function(data) {  // Use async/await
  processData(data, function(result) { ... });
});
\`\`\`"
            ;;
        "python")
            vars[LANGUAGE_SPECIFIC_CONFLICT_RESOLUTION]="- For Python-specific patterns, follow PEP 8 and project tooling (ruff/black)"
            vars[LANGUAGE_SPECIFIC_NEVER]="- Commit requirements.txt without pyproject.toml changes
- Use print() for logging in production code"
            vars[CODE_EXAMPLES]="**Good:** Type hints, dataclasses, context managers
**Avoid:** Bare \`except:\`, mutable default args, \`print()\` for logging"
            vars[GOOD_EXAMPLE]="\`\`\`python
# Use type hints and dataclasses
from dataclasses import dataclass

@dataclass
class User:
    name: str
    email: str

def find_user(user_id: int) -> User | None:
    \"\"\"Find user by ID.\"\"\"
    return db.query(User).filter_by(id=user_id).first()
\`\`\`"
            vars[BAD_EXAMPLE]="\`\`\`python
# Don't use bare except or mutable defaults
def process(items=[]):  # Mutable default arg!
    try:
        return do_something(items)
    except:  # Too broad, catches KeyboardInterrupt
        pass

# Don't use print() for logging
print(f\"Processing {item}\")  # Use logging module
\`\`\`"
            ;;
        *)
            vars[LANGUAGE_SPECIFIC_CONFLICT_RESOLUTION]=""
            vars[LANGUAGE_SPECIFIC_NEVER]=""
            vars[CODE_EXAMPLES]=""
            vars[GOOD_EXAMPLE]="TODO: Add language-specific good patterns"
            vars[BAD_EXAMPLE]="TODO: Add language-specific anti-patterns"
            ;;
    esac

    # Render template (smart mode respects --update flag)
    render_template_smart "$TEMPLATE" "$ROOT_FILE" vars "$UPDATE_ONLY"

    # Enforce byte budget for agent instruction limits
    enforce_byte_budget "$ROOT_FILE" "$BYTE_BUDGET"

    if [ "$UPDATE_ONLY" = true ]; then
        emit_op write agents-file "$ROOT_FILE"
        echo "✅ Updated: $ROOT_FILE"
    else
        emit_op write agents-file "$ROOT_FILE"
        echo "✅ Created: $ROOT_FILE"
    fi
fi

# Generate CLAUDE.md shim if requested
if [ "$CLAUDE_SHIM" = true ]; then
    CLAUDE_FILE="$PROJECT_DIR/CLAUDE.md"
    # -e alone follows a symlink, so a dangling one would count as absent and
    # the write below would land at its target, outside the project.
    if { [ -e "$CLAUDE_FILE" ] || [ -L "$CLAUDE_FILE" ]; } && [ "$FORCE" = false ]; then
        if [ ! -L "$CLAUDE_FILE" ] && head -n 1 "$CLAUDE_FILE" 2>/dev/null | grep -qF 'Auto-generated shim for Claude Code compatibility'; then
            emit_op keep shim "$CLAUDE_FILE" reason "already exists"
            log "CLAUDE.md already exists, skipping (use --force to regenerate)"
        else
            # Not our shim: say so, as the symlink mode does for a kept file.
            report_kept_file "$CLAUDE_FILE" CLAUDE.md
        fi
    elif [ "$DRY_RUN" = true ]; then
        emit_op write shim "$CLAUDE_FILE"
        echo "[DRY-RUN] Would create: $CLAUDE_FILE"
    else
        # replace_file replaces a symlink rather than writing through it.
        replace_file "$CLAUDE_FILE" << 'CLAUDESHIM'
<!-- Auto-generated shim for Claude Code compatibility -->
<!-- Source of truth: AGENTS.md -->
<!-- Re-generate with: generate-agents.sh --claude-shim -->

@import AGENTS.md

<!-- Add Claude-specific overrides below if needed -->
CLAUDESHIM
        emit_op write shim "$CLAUDE_FILE"
        echo "✅ Created: $CLAUDE_FILE (shim importing AGENTS.md)"
    fi
fi

# Auto-detect Claude Code environment and ensure CLAUDE.md symlinks exist

# Create compatibility symlinks if requested (root level)
# Subdirectory symlinks are created after scoped files are generated (see below).
if [ "$CREATE_SYMLINKS" = true ] && [ "$CLAUDE_SHIM" = false ]; then
    for symlink_name in CLAUDE.md GEMINI.md; do
        SYMLINK_FILE="$PROJECT_DIR/$symlink_name"
        if compat_file_is_ours "$SYMLINK_FILE"; then
            if [ "$DRY_RUN" = true ]; then
                emit_op symlink compat-file "$SYMLINK_FILE" target AGENTS.md
                echo "[DRY-RUN] Would symlink: $SYMLINK_FILE → AGENTS.md"
            else
                ln -sf AGENTS.md "$SYMLINK_FILE"
                emit_op symlink compat-file "$SYMLINK_FILE" target AGENTS.md
                echo "✅ Symlinked: $SYMLINK_FILE → AGENTS.md"
            fi
        elif [ "$FORCE" = true ]; then
            if [ "$DRY_RUN" = true ]; then
                emit_op symlink compat-file "$SYMLINK_FILE" target AGENTS.md
                echo "[DRY-RUN] Would replace: $SYMLINK_FILE → AGENTS.md (--force)"
            else
                rm -f "$SYMLINK_FILE"
                ln -s AGENTS.md "$SYMLINK_FILE"
                emit_op symlink compat-file "$SYMLINK_FILE" target AGENTS.md
                echo "✅ Replaced: $SYMLINK_FILE → AGENTS.md (--force)"
            fi
        else
            report_kept_file "$SYMLINK_FILE" "$symlink_name"
        fi
    done
fi

# Generate scoped AGENTS.md files
SCOPE_COUNT=$(echo "$SCOPES_INFO" | jq '.scopes | length')

if [ "$SCOPE_COUNT" -eq 0 ]; then
    log "No scopes detected (no directories with sufficient source files)"
else
    log "Generating $SCOPE_COUNT scoped AGENTS.md files..."

    while read -r scope; do
        SCOPE_PATH=$(echo "$scope" | jq -r '.path')
        SCOPE_TYPE=$(echo "$scope" | jq -r '.type')
        SCOPE_FILE="$PROJECT_DIR/$SCOPE_PATH/AGENTS.md"


        if { [ -e "$SCOPE_FILE" ] || [ -L "$SCOPE_FILE" ]; } && [ "$FORCE" = false ] && [ "$UPDATE_ONLY" = false ]; then
            emit_op keep agents-file "$SCOPE_FILE" reason "already exists"
            log "Scoped AGENTS.md already exists: $SCOPE_PATH, skipping"
            continue
        fi

        if [ "$DRY_RUN" = true ]; then
            emit_op write agents-file "$SCOPE_FILE"
            echo "[DRY-RUN] Would create/update: $SCOPE_FILE"
            continue
        fi

        # Select template based on scope type
        SCOPE_TEMPLATE="$TEMPLATE_DIR/scoped/$SCOPE_TYPE.md"

        if [ ! -f "$SCOPE_TEMPLATE" ]; then
            log "No template for scope type: $SCOPE_TYPE, skipping $SCOPE_PATH"
            continue
        fi

        # Try to extract commands from scope directory (for monorepos)
        SCOPE_COMMANDS=""
        if [ -f "$SCOPE_PATH/package.json" ] || [ -f "$SCOPE_PATH/composer.json" ] || [ -f "$SCOPE_PATH/pyproject.toml" ] || [ -f "$SCOPE_PATH/go.mod" ]; then
            SCOPE_COMMANDS=$("$SCRIPT_DIR/extract-commands.sh" "$SCOPE_PATH" 2>/dev/null || echo '')
            log "Found scope-local config in $SCOPE_PATH"
        fi
        # Fall back to root commands if scope has no local config
        [ -z "$SCOPE_COMMANDS" ] && SCOPE_COMMANDS="$COMMANDS"

        # Prepare scoped template variables
        declare -A scope_vars
        scope_vars[TIMESTAMP]=$(get_timestamp)
        scope_vars[SCOPE_NAME]=$(basename "$SCOPE_PATH")
        scope_vars[SCOPE_DESCRIPTION]=$(get_scope_description "$SCOPE_TYPE")
        scope_vars[FILE_PATH]="<file>"
        scope_vars[HOUSE_RULES]=""

        # Helper to only set var if value is non-empty (leaves placeholder for row deletion)
        set_scope_if_present() {
            local key="$1"
            local value="$2"
            if [ -n "$value" ] && [ "$value" != "null" ]; then
                scope_vars[$key]="$value"
            fi
            return 0
        }

        # Generate scope-specific file map
        # Usage: generate_scope_file_map <path> <ext1> [ext2] [ext3]...
        generate_scope_file_map() {
            local scope_path="$1"
            shift  # Remove first arg, leaving extensions
            local extensions=("$@")
            local result=""

            # Build find pattern for multiple extensions
            local find_args=()
            for ext in "${extensions[@]}"; do
                if [[ ${#find_args[@]} -gt 0 ]]; then
                    find_args+=("-o")
                fi
                find_args+=("-name" "*.$ext")
            done

            # Find key files (most recently modified, largest, or entry points)
            local files
            files=$(find "$scope_path" -maxdepth 2 -type f \( "${find_args[@]}" \) 2>/dev/null | head -5)

            if [ -n "$files" ]; then
                result="| File | Purpose |\n|------|---------|"
                while IFS= read -r file; do
                    local rel_path="${file#"$PROJECT_DIR"/}"
                    # Try to extract purpose from first docblock or comment
                    local purpose
                    purpose=$(head -20 "$file" 2>/dev/null | grep -E '^\s*(//|#|\*|/\*\*)' | head -1 | sed 's/^[[:space:]]*[/*#]*[[:space:]]*//' | cut -c1-50)
                    [ -z "$purpose" ] && purpose="(add description)"
                    result="$result\n| \`$rel_path\` | $purpose |"
                done <<< "$files"
            fi
            echo -e "$result"
        }

        # Generate scope-specific golden samples
        # Usage: generate_scope_golden_samples <path> <ext1> [ext2] [ext3]...
        generate_scope_golden_samples() {
            local scope_path="$1"
            shift  # Remove first arg, leaving extensions
            local extensions=("$@")
            local result=""

            # Build find pattern for multiple extensions
            local find_args=()
            for ext in "${extensions[@]}"; do
                if [[ ${#find_args[@]} -gt 0 ]]; then
                    find_args+=("-o")
                fi
                find_args+=("-name" "*.$ext")
            done

            # Look for well-documented files with tests
            local sample
            # File names come from the target project: they reach wc as
            # arguments (-exec ... \;), never inside a shell command string.
            sample=$(find "$scope_path" -maxdepth 2 -type f \( "${find_args[@]}" \) \
                         -exec wc -l {} \; 2>/dev/null | \
                     grep -v "^0" | sort -rn | head -1 | awk '{print $2}')

            if [ -n "$sample" ] && [ -f "$sample" ]; then
                local rel_path="${sample#"$PROJECT_DIR"/}"
                result="| Pattern | Reference |\n|---------|-----------|"
                result="$result\n| Standard implementation | \`$rel_path\` |"
            fi
            echo -e "$result"
        }

        # Language-specific variables
        case "$SCOPE_TYPE" in
            "backend-go")
                scope_vars[GO_VERSION]="$VERSION"
                scope_vars[GO_MINOR_VERSION]=$(echo "$VERSION" | cut -d. -f2)
                scope_vars[GO_TOOLS]="golangci-lint, gofmt"
                scope_vars[ENV_VARS]="See .env.example"
                set_scope_if_present BUILD_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.build // empty')"

                # Build whole-line placeholders for setup section
                scope_vars[INSTALL_LINE]="- Install: \`go mod download\`"
                [ -n "${scope_vars[GO_VERSION]:-}" ] && [ "${scope_vars[GO_VERSION]}" != "unknown" ] && \
                    scope_vars[GO_VERSION_LINE]="- Go version: ${scope_vars[GO_VERSION]}"
                [ -n "${scope_vars[GO_TOOLS]:-}" ] && \
                    scope_vars[GO_TOOLS_LINE]="- Required tools: ${scope_vars[GO_TOOLS]}"
                [ -n "${scope_vars[ENV_VARS]:-}" ] && \
                    scope_vars[ENV_VARS_LINE]="- Environment variables: ${scope_vars[ENV_VARS]}"

                # Build whole-line placeholders for commands section
                scope_vars[VET_LINE]="- Vet (static analysis): \`go vet ./...\`"
                scope_vars[FORMAT_LINE]="- Format: \`gofmt -w .\`"
                scope_vars[LINT_LINE]="- Lint: \`golangci-lint run ./...\`"
                scope_vars[TEST_LINE]="- Test: \`go test -v -race ./...\`"
                scope_vars[TEST_SINGLE_LINE]="- Test specific: \`go test -v -race -run TestName ./...\`"
                [ -n "${scope_vars[BUILD_CMD]:-}" ] && \
                    scope_vars[BUILD_LINE]="- Build: \`${scope_vars[BUILD_CMD]}\`"

                # Build checklist lines
                scope_vars[TEST_CHECKLIST_LINE]="- [ ] Tests pass: \`go test -v -race ./...\`"
                scope_vars[LINT_CHECKLIST_LINE]="- [ ] Lint clean: \`golangci-lint run ./...\`"
                scope_vars[FORMAT_CHECKLIST_LINE]="- [ ] Formatted: \`gofmt -w .\`"

                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "go")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "go")
                ;;

            "backend-php")
                scope_vars[PHP_VERSION]="$VERSION"
                FRAMEWORK=$(echo "$PROJECT_INFO" | jq -r '.framework')
                scope_vars[FRAMEWORK]="$FRAMEWORK"
                scope_vars[PHP_EXTENSIONS]="json, mbstring, xml"
                scope_vars[ENV_VARS]="See .env.example"
                scope_vars[PHPSTAN_LEVEL]="10"
                set_scope_if_present BUILD_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.build // empty')"

                if [ "$FRAMEWORK" = "typo3" ]; then
                    scope_vars[FRAMEWORK_CONVENTIONS]="- TYPO3-specific: Use dependency injection, follow TYPO3 CGL"
                    scope_vars[FRAMEWORK_DOCS_LINE]="- TYPO3 documentation: https://docs.typo3.org"
                else
                    scope_vars[FRAMEWORK_CONVENTIONS]=""
                    scope_vars[FRAMEWORK_DOCS_LINE]=""
                fi

                # Build whole-line placeholders for setup section
                scope_vars[INSTALL_LINE]="- Install: \`composer install\`"
                [ -n "${scope_vars[PHP_VERSION]:-}" ] && [ "${scope_vars[PHP_VERSION]}" != "unknown" ] && \
                    scope_vars[PHP_VERSION_LINE]="- PHP version: ${scope_vars[PHP_VERSION]}"
                [ -n "${scope_vars[FRAMEWORK]:-}" ] && [ "${scope_vars[FRAMEWORK]}" != "none" ] && \
                    scope_vars[FRAMEWORK_LINE]="- Framework: ${scope_vars[FRAMEWORK]}"
                [ -n "${scope_vars[PHP_EXTENSIONS]:-}" ] && \
                    scope_vars[PHP_EXTENSIONS_LINE]="- Required extensions: ${scope_vars[PHP_EXTENSIONS]}"
                [ -n "${scope_vars[ENV_VARS]:-}" ] && \
                    scope_vars[ENV_VARS_LINE]="- Environment variables: ${scope_vars[ENV_VARS]}"

                # Build whole-line placeholders for commands section
                scope_vars[TYPECHECK_LINE]="- Typecheck: \`vendor/bin/phpstan analyze --level=${scope_vars[PHPSTAN_LEVEL]}\`"
                scope_vars[FORMAT_LINE]="- Format: \`vendor/bin/php-cs-fixer fix\`"
                scope_vars[LINT_LINE]="- Lint: \`php -l\`"
                scope_vars[TEST_LINE]="- Test: \`vendor/bin/phpunit\`"
                [ -n "${scope_vars[BUILD_CMD]:-}" ] && \
                    scope_vars[BUILD_LINE]="- Build: \`${scope_vars[BUILD_CMD]}\`"

                # Build checklist lines
                scope_vars[TEST_CHECKLIST_LINE]="- [ ] Tests pass: \`vendor/bin/phpunit\`"
                scope_vars[TYPECHECK_CHECKLIST_LINE]="- [ ] PHPStan Level ${scope_vars[PHPSTAN_LEVEL]} clean: \`vendor/bin/phpstan analyze\`"
                scope_vars[FORMAT_CHECKLIST_LINE]="- [ ] PSR-12 compliant: \`vendor/bin/php-cs-fixer fix --dry-run\`"

                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "php")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "php")
                ;;

            "typo3-extension")
                scope_vars[PHP_VERSION]="$VERSION"
                TYPO3_VERSION=$(jq -r '.require."typo3/cms-core" // .["require-dev"]."typo3/cms-core" // "^12.4 || ^13.4"' composer.json 2>/dev/null || echo "^12.4 || ^13.4")
                scope_vars[TYPO3_VERSION]="$TYPO3_VERSION"
                scope_vars[PHPSTAN_LEVEL]="10"

                # Extract extension key and vendor from composer.json
                EXT_KEY=$(jq -r '.extra."typo3/cms"."extension-key" // empty' composer.json 2>/dev/null || echo "")
                if [ -z "$EXT_KEY" ]; then
                    EXT_KEY=$(basename "$PROJECT_DIR" | tr '-' '_')
                fi
                scope_vars[EXT_KEY]="$EXT_KEY"

                VENDOR=$(jq -r '.name // empty' composer.json 2>/dev/null | cut -d'/' -f1 || echo "Vendor")
                scope_vars[VENDOR]="$VENDOR"
                scope_vars[REQUIRED_EXTENSIONS]="See ext_emconf.php"
                scope_vars[HOUSE_RULES]=""

                # Build whole-line placeholders for setup section
                scope_vars[INSTALL_LINE]="- Install: \`composer install\` or via Extension Manager"
                [ -n "${scope_vars[PHP_VERSION]:-}" ] && [ "${scope_vars[PHP_VERSION]}" != "unknown" ] && \
                    scope_vars[PHP_VERSION_LINE]="- PHP version: ${scope_vars[PHP_VERSION]}"
                [ -n "${scope_vars[TYPO3_VERSION]:-}" ] && \
                    scope_vars[TYPO3_VERSION_LINE]="- TYPO3 version: ${scope_vars[TYPO3_VERSION]}"
                scope_vars[DEV_SETUP_LINE]="- Local dev: \`ddev start && ddev composer install\`"
                [ -n "${scope_vars[REQUIRED_EXTENSIONS]:-}" ] && \
                    scope_vars[REQUIRED_EXTENSIONS_LINE]="- Required extensions: ${scope_vars[REQUIRED_EXTENSIONS]}"

                # Build commands table
                scope_vars[COMMANDS_TABLE]="| Task | Command |
|------|---------|
| Lint | \`composer ci:php:lint\` |
| CS Fix | \`composer ci:php:cs-fixer\` |
| PHPStan | \`composer ci:php:stan\` |
| Unit tests | \`composer ci:tests:unit\` |
| Functional | \`composer ci:tests:functional\` |
| All CI | \`composer ci\` |"

                scope_vars[DDEV_ALTERNATIVE]="Alternative with ddev:
- \`ddev composer ci:tests:unit\`
- \`ddev exec vendor/bin/phpunit -c Tests/Build/UnitTests.xml\`"

                # Build checklist lines
                scope_vars[CI_CHECKLIST_LINE]="- [ ] \`composer ci\` passes (lint, cs-fixer, phpstan, tests)"
                scope_vars[PHPSTAN_CHECKLIST_LINE]="- [ ] PHPStan level ${scope_vars[PHPSTAN_LEVEL]} clean"
                scope_vars[TYPO3_VERSION_CHECKLIST_LINE]="- [ ] Tested on target TYPO3 versions (${scope_vars[TYPO3_VERSION]})"

                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "php")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "php")
                ;;

            "typo3-project")
                scope_vars[PHP_VERSION]="$VERSION"
                TYPO3_VERSION=$(jq -r '.require."typo3/cms-core" // "^12.4 || ^13.4"' composer.json 2>/dev/null || echo "^12.4 || ^13.4")
                scope_vars[TYPO3_VERSION]="$TYPO3_VERSION"
                scope_vars[HOUSE_RULES]=""

                # Build whole-line placeholders for setup section
                scope_vars[INSTALL_LINE]="- Install: \`composer install\`"
                [ -n "${scope_vars[PHP_VERSION]:-}" ] && [ "${scope_vars[PHP_VERSION]}" != "unknown" ] && \
                    scope_vars[PHP_VERSION_LINE]="- PHP version: ${scope_vars[PHP_VERSION]}"
                [ -n "${scope_vars[TYPO3_VERSION]:-}" ] && \
                    scope_vars[TYPO3_VERSION_LINE]="- TYPO3 version: ${scope_vars[TYPO3_VERSION]}"
                scope_vars[DEV_SETUP_LINE]="- Local dev: \`ddev start && ddev composer install\`"

                # Detect composer mode
                if [ -f "public/typo3" ] || [ -d "public/typo3" ]; then
                    scope_vars[COMPOSER_MODE_LINE]="- Composer mode: enabled (public/ web root)"
                fi

                # Build commands table
                scope_vars[COMMANDS_TABLE]="| Task | Command |
|------|---------|
| Clear cache | \`vendor/bin/typo3 cache:flush\` |
| Warmup cache | \`vendor/bin/typo3 cache:warmup\` |
| Update DB | \`vendor/bin/typo3 database:updateschema\` |
| List commands | \`vendor/bin/typo3 list\` |"

                # Build checklist lines
                scope_vars[CI_CHECKLIST_LINE]="- [ ] Site configuration valid"
                scope_vars[TYPO3_VERSION_CHECKLIST_LINE]="- [ ] Tested on TYPO3 ${scope_vars[TYPO3_VERSION]}"

                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "php")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "php")
                ;;

            "oro-bundle")
                scope_vars[PHP_VERSION]="$VERSION"
                ORO_VERSION=$(jq -r '.require."oro/platform" // .require."oro/commerce" // .require."oro/crm" // "^6.0"' composer.json 2>/dev/null || echo "^6.0")
                scope_vars[ORO_VERSION]="$ORO_VERSION"
                scope_vars[PHPSTAN_LEVEL]="8"
                scope_vars[HOUSE_RULES]=""

                # Build whole-line placeholders for setup section
                scope_vars[INSTALL_LINE]="- Install: \`composer install\`"
                [ -n "${scope_vars[PHP_VERSION]:-}" ] && [ "${scope_vars[PHP_VERSION]}" != "unknown" ] && \
                    scope_vars[PHP_VERSION_LINE]="- PHP version: ${scope_vars[PHP_VERSION]}"
                [ -n "${scope_vars[ORO_VERSION]:-}" ] && \
                    scope_vars[ORO_VERSION_LINE]="- Oro version: ${scope_vars[ORO_VERSION]}"
                scope_vars[DATABASE_LINE]="- Database: PostgreSQL (recommended) or MySQL"
                scope_vars[SETUP_COMMANDS]="- Required: \`bin/console oro:install\` for fresh setup
- Cache clear: \`bin/console cache:clear\`
- Assets: \`bin/console oro:assets:install\`"

                # Build commands table
                scope_vars[COMMANDS_TABLE]="| Task | Command |
|------|---------|
| Lint | \`bin/console lint:yaml src/\` |
| CS Fix | \`vendor/bin/php-cs-fixer fix\` |
| PHPStan | \`vendor/bin/phpstan analyse\` |
| Unit tests | \`vendor/bin/phpunit --testsuite=unit\` |
| Functional | \`vendor/bin/phpunit --testsuite=functional\` |
| Behat | \`vendor/bin/behat\` |
| Full CI | \`bin/console oro:test:all\` |"

                # Build checklist lines
                scope_vars[CACHE_CHECKLIST_LINE]="- [ ] \`bin/console cache:clear\` runs without errors"
                scope_vars[PHPSTAN_CHECKLIST_LINE]="- [ ] PHPStan passes at configured level"
                scope_vars[UNIT_TEST_CHECKLIST_LINE]="- [ ] Unit tests pass: \`vendor/bin/phpunit --testsuite=unit\`"

                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "php")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "php")
                ;;

            "oro-project")
                scope_vars[PHP_VERSION]="$VERSION"
                ORO_VERSION=$(jq -r '.require."oro/platform" // .require."oro/commerce" // .require."oro/crm" // "^6.0"' composer.json 2>/dev/null || echo "^6.0")
                scope_vars[ORO_VERSION]="$ORO_VERSION"
                scope_vars[PHPSTAN_LEVEL]="8"
                scope_vars[HOUSE_RULES]=""

                # Build whole-line placeholders for setup section
                scope_vars[INSTALL_LINE]="- Install: \`composer install\`"
                [ -n "${scope_vars[PHP_VERSION]:-}" ] && [ "${scope_vars[PHP_VERSION]}" != "unknown" ] && \
                    scope_vars[PHP_VERSION_LINE]="- PHP version: ${scope_vars[PHP_VERSION]}"
                [ -n "${scope_vars[ORO_VERSION]:-}" ] && \
                    scope_vars[ORO_VERSION_LINE]="- Oro version: ${scope_vars[ORO_VERSION]}"
                scope_vars[DATABASE_LINE]="- Database: PostgreSQL (recommended) or MySQL"
                scope_vars[MESSAGE_QUEUE_LINE]="- Message queue: Required for background jobs"

                # Build commands table
                scope_vars[COMMANDS_TABLE]="| Task | Command |
|------|---------|
| Install | \`bin/console oro:install\` |
| Update platform | \`bin/console oro:platform:update\` |
| Clear cache | \`bin/console cache:clear\` |
| Install assets | \`bin/console oro:assets:install\` |
| Message queue | \`bin/console oro:message-queue:consume\` |
| Run cron | \`bin/console oro:cron\` |
| Unit tests | \`vendor/bin/phpunit --testsuite=unit\` |"

                # Build checklist lines
                scope_vars[CACHE_CHECKLIST_LINE]="- [ ] \`bin/console cache:clear\` runs without errors"
                scope_vars[PHPSTAN_CHECKLIST_LINE]="- [ ] PHPStan passes at configured level"
                scope_vars[UNIT_TEST_CHECKLIST_LINE]="- [ ] Unit tests pass"

                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "php")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "php")
                ;;

            "symfony")
                scope_vars[PHP_VERSION]="$VERSION"
                SYMFONY_VERSION=$(jq -r '.require."symfony/framework-bundle" // .require."symfony/symfony" // "^7.0"' composer.json 2>/dev/null || echo "^7.0")
                scope_vars[SYMFONY_VERSION]="$SYMFONY_VERSION"
                scope_vars[PHPSTAN_LEVEL]="9"
                scope_vars[HOUSE_RULES]=""

                # Build whole-line placeholders for setup section
                scope_vars[INSTALL_LINE]="- Install: \`composer install\`"
                [ -n "${scope_vars[PHP_VERSION]:-}" ] && [ "${scope_vars[PHP_VERSION]}" != "unknown" ] && \
                    scope_vars[PHP_VERSION_LINE]="- PHP version: ${scope_vars[PHP_VERSION]}"
                [ -n "${scope_vars[SYMFONY_VERSION]:-}" ] && \
                    scope_vars[SYMFONY_VERSION_LINE]="- Symfony version: ${scope_vars[SYMFONY_VERSION]}"
                # Detect database from doctrine config
                if [ -f "config/packages/doctrine.yaml" ]; then
                    scope_vars[DATABASE_LINE]="- Database: See config/packages/doctrine.yaml"
                fi

                # Build commands table
                scope_vars[COMMANDS_TABLE]="| Task | Command |
|------|---------|
| Lint | \`bin/console lint:yaml config/\` |
| CS Fix | \`vendor/bin/php-cs-fixer fix\` |
| PHPStan | \`vendor/bin/phpstan analyse\` |
| Unit tests | \`vendor/bin/phpunit\` |
| Clear cache | \`bin/console cache:clear\` |
| Debug routes | \`bin/console debug:router\` |
| Debug container | \`bin/console debug:container\` |"

                # Build checklist lines
                scope_vars[PHPSTAN_CHECKLIST_LINE]="- [ ] PHPStan level ${scope_vars[PHPSTAN_LEVEL]} clean"
                scope_vars[CS_CHECKLIST_LINE]="- [ ] Code style clean: \`vendor/bin/php-cs-fixer fix --dry-run\`"
                scope_vars[TEST_CHECKLIST_LINE]="- [ ] Tests pass: \`vendor/bin/phpunit\`"

                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "php")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "php")
                ;;

            "backend-python")
                scope_vars[PYTHON_VERSION]="$VERSION"
                scope_vars[PACKAGE_MANAGER]=$(echo "$PROJECT_INFO" | jq -r '.package_manager')
                scope_vars[ENV_VARS]="See .env or .env.example"
                # Populate all command variables from scope-local extraction
                set_scope_if_present INSTALL_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.install // empty')"
                set_scope_if_present TYPECHECK_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.typecheck // empty')"
                set_scope_if_present LINT_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.lint // empty')"
                set_scope_if_present FORMAT_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.format // empty')"
                set_scope_if_present TEST_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.test // empty')"
                set_scope_if_present TEST_SINGLE_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.test_single // empty')"
                set_scope_if_present BUILD_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.build // empty')"
                set_scope_if_present DEV_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.dev // empty')"

                # Build whole-line placeholders for setup section
                [ -n "${scope_vars[INSTALL_CMD]:-}" ] && \
                    scope_vars[INSTALL_LINE]="- Install: \`${scope_vars[INSTALL_CMD]}\`"
                [ -n "${scope_vars[PYTHON_VERSION]:-}" ] && [ "${scope_vars[PYTHON_VERSION]}" != "unknown" ] && \
                    scope_vars[PYTHON_VERSION_LINE]="- Python version: ${scope_vars[PYTHON_VERSION]}"
                [ -n "${scope_vars[PACKAGE_MANAGER]:-}" ] && [ "${scope_vars[PACKAGE_MANAGER]}" != "unknown" ] && \
                    scope_vars[PACKAGE_MANAGER_LINE]="- Package manager: ${scope_vars[PACKAGE_MANAGER]}"
                [ -n "${scope_vars[ENV_VARS]:-}" ] && \
                    scope_vars[ENV_VARS_LINE]="- Environment variables: ${scope_vars[ENV_VARS]}"

                # Build whole-line placeholders for commands section
                [ -n "${scope_vars[TYPECHECK_CMD]:-}" ] && \
                    scope_vars[TYPECHECK_LINE]="- Typecheck: \`${scope_vars[TYPECHECK_CMD]}\`"
                [ -n "${scope_vars[FORMAT_CMD]:-}" ] && \
                    scope_vars[FORMAT_LINE]="- Format: \`${scope_vars[FORMAT_CMD]}\`"
                [ -n "${scope_vars[LINT_CMD]:-}" ] && \
                    scope_vars[LINT_LINE]="- Lint: \`${scope_vars[LINT_CMD]}\`"
                [ -n "${scope_vars[TEST_CMD]:-}" ] && \
                    scope_vars[TEST_LINE]="- Test: \`${scope_vars[TEST_CMD]}\`"
                [ -n "${scope_vars[BUILD_CMD]:-}" ] && \
                    scope_vars[BUILD_LINE]="- Build: \`${scope_vars[BUILD_CMD]}\`"

                # Build checklist lines
                [ -n "${scope_vars[TEST_CMD]:-}" ] && \
                    scope_vars[TEST_CHECKLIST_LINE]="- [ ] Tests pass: \`${scope_vars[TEST_CMD]}\`"
                [ -n "${scope_vars[TYPECHECK_CMD]:-}" ] && \
                    scope_vars[TYPECHECK_CHECKLIST_LINE]="- [ ] Type check clean: \`${scope_vars[TYPECHECK_CMD]}\`"
                [ -n "${scope_vars[LINT_CMD]:-}" ] && \
                    scope_vars[LINT_CHECKLIST_LINE]="- [ ] Lint clean: \`${scope_vars[LINT_CMD]}\`"
                [ -n "${scope_vars[FORMAT_CMD]:-}" ] && \
                    scope_vars[FORMAT_CHECKLIST_LINE]="- [ ] Formatted: \`${scope_vars[FORMAT_CMD]}\`"

                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "py")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "py")
                ;;

            "backend-typescript")
                # CRITICAL: Get Node version from nearest package.json,
                # NOT from root PROJECT_INFO (which may be PHP/Go/Python)
                _node_config_root=$(find_node_config_root "$SCOPE_PATH") || _node_config_root="."

                # Extract Node-specific metadata from correct config root
                _node_version=$(get_node_version "$_node_config_root") || _node_version=""
                scope_vars[NODE_VERSION]="$_node_version"

                # Package manager from scope's config root
                scope_vars[PACKAGE_MANAGER]=$(detect_node_package_manager "$SCOPE_PATH")
                scope_vars[ENV_VARS]="See .env or .env.example"

                # Extract commands using Node-specific extraction from config root
                _node_commands=$("$SCRIPT_DIR/extract-commands.sh" "$_node_config_root" node 2>/dev/null || echo '{}')

                set_scope_if_present INSTALL_CMD "$(echo "$_node_commands" | jq -r '.install // empty')"
                set_scope_if_present TYPECHECK_CMD "$(echo "$_node_commands" | jq -r '.typecheck // empty')"
                set_scope_if_present LINT_CMD "$(echo "$_node_commands" | jq -r '.lint // empty')"
                set_scope_if_present FORMAT_CMD "$(echo "$_node_commands" | jq -r '.format // empty')"
                set_scope_if_present TEST_CMD "$(echo "$_node_commands" | jq -r '.test // empty')"
                set_scope_if_present TEST_SINGLE_CMD "$(echo "$_node_commands" | jq -r '.test_single // empty')"
                set_scope_if_present BUILD_CMD "$(echo "$_node_commands" | jq -r '.build // empty')"
                set_scope_if_present DEV_CMD "$(echo "$_node_commands" | jq -r '.dev // empty')"

                # Build whole-line placeholders for setup section
                [ -n "${scope_vars[INSTALL_CMD]:-}" ] && \
                    scope_vars[INSTALL_LINE]="- Install: \`${scope_vars[INSTALL_CMD]}\`"
                [ -n "${scope_vars[NODE_VERSION]:-}" ] && [ "${scope_vars[NODE_VERSION]}" != "unknown" ] && \
                    scope_vars[NODE_VERSION_LINE]="- Node version: ${scope_vars[NODE_VERSION]}"
                [ -n "${scope_vars[PACKAGE_MANAGER]:-}" ] && [ "${scope_vars[PACKAGE_MANAGER]}" != "unknown" ] && \
                    scope_vars[PACKAGE_MANAGER_LINE]="- Package manager: ${scope_vars[PACKAGE_MANAGER]}"
                [ -n "${scope_vars[ENV_VARS]:-}" ] && \
                    scope_vars[ENV_VARS_LINE]="- Environment variables: ${scope_vars[ENV_VARS]}"

                # Build whole-line placeholders for commands section
                [ -n "${scope_vars[TYPECHECK_CMD]:-}" ] && \
                    scope_vars[TYPECHECK_LINE]="- Typecheck (project-wide): \`${scope_vars[TYPECHECK_CMD]}\`"
                [ -n "${scope_vars[FORMAT_CMD]:-}" ] && \
                    scope_vars[FORMAT_LINE]="- Format: \`${scope_vars[FORMAT_CMD]}\`"
                [ -n "${scope_vars[LINT_CMD]:-}" ] && \
                    scope_vars[LINT_LINE]="- Lint: \`${scope_vars[LINT_CMD]}\`"
                [ -n "${scope_vars[TEST_CMD]:-}" ] && \
                    scope_vars[TEST_LINE]="- Test: \`${scope_vars[TEST_CMD]}\`"
                [ -n "${scope_vars[BUILD_CMD]:-}" ] && \
                    scope_vars[BUILD_LINE]="- Build: \`${scope_vars[BUILD_CMD]}\`"
                [ -n "${scope_vars[DEV_CMD]:-}" ] && \
                    scope_vars[DEV_LINE]="- Dev server: \`${scope_vars[DEV_CMD]}\`"

                # Build checklist lines
                [ -n "${scope_vars[TEST_CMD]:-}" ] && \
                    scope_vars[TEST_CHECKLIST_LINE]="- [ ] Tests pass: \`${scope_vars[TEST_CMD]}\`"
                [ -n "${scope_vars[TYPECHECK_CMD]:-}" ] && \
                    scope_vars[TYPECHECK_CHECKLIST_LINE]="- [ ] Type check clean: \`${scope_vars[TYPECHECK_CMD]}\`"
                [ -n "${scope_vars[LINT_CMD]:-}" ] && \
                    scope_vars[LINT_CHECKLIST_LINE]="- [ ] Lint clean: \`${scope_vars[LINT_CMD]}\`"
                [ -n "${scope_vars[FORMAT_CMD]:-}" ] && \
                    scope_vars[FORMAT_CHECKLIST_LINE]="- [ ] Formatted: \`${scope_vars[FORMAT_CMD]}\`"

                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "ts" "tsx")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "ts" "tsx")
                ;;

            "frontend-typescript")
                # CRITICAL: Get Node version and framework from nearest package.json,
                # NOT from root PROJECT_INFO (which may be PHP/Go/Python)
                _node_config_root=$(find_node_config_root "$SCOPE_PATH") || _node_config_root="."

                # Extract Node-specific metadata from correct config root
                _node_version=$(get_node_version "$_node_config_root") || _node_version=""
                scope_vars[NODE_VERSION]="$_node_version"

                _js_framework=$(get_js_framework "$_node_config_root") || _js_framework=""
                FRAMEWORK="$_js_framework"
                scope_vars[FRAMEWORK]="$FRAMEWORK"

                # Package manager from scope's config root
                scope_vars[PACKAGE_MANAGER]=$(detect_node_package_manager "$SCOPE_PATH")
                scope_vars[ENV_VARS]="See .env.example"

                # Extract commands using Node-specific extraction from config root
                _node_commands=$("$SCRIPT_DIR/extract-commands.sh" "$_node_config_root" node 2>/dev/null || echo '{}')

                set_scope_if_present INSTALL_CMD "$(echo "$_node_commands" | jq -r '.install // empty')"
                set_scope_if_present TYPECHECK_CMD "$(echo "$_node_commands" | jq -r '.typecheck // empty')"
                set_scope_if_present LINT_CMD "$(echo "$_node_commands" | jq -r '.lint // empty')"
                set_scope_if_present FORMAT_CMD "$(echo "$_node_commands" | jq -r '.format // empty')"
                set_scope_if_present TEST_CMD "$(echo "$_node_commands" | jq -r '.test // empty')"
                set_scope_if_present BUILD_CMD "$(echo "$_node_commands" | jq -r '.build // empty')"
                set_scope_if_present DEV_CMD "$(echo "$_node_commands" | jq -r '.dev // empty')"

                # TypeScript strict mode - check, don't assume
                _ts_strict=$(get_ts_strict_mode "$_node_config_root") || _ts_strict=""
                scope_vars[TS_STRICT]="$_ts_strict"

                # Conditional TS_STRICT_LINE based on actual tsconfig.json
                if [[ "${scope_vars[TS_STRICT]}" == "true" ]]; then
                    scope_vars[TS_STRICT_LINE]="- TypeScript strict mode enabled (verified from tsconfig.json)"
                elif [[ "${scope_vars[TS_STRICT]}" == "false" ]]; then
                    scope_vars[TS_STRICT_LINE]="- TypeScript strict mode: disabled (consider enabling)"
                else
                    scope_vars[TS_STRICT_LINE]="- Follow tsconfig.json compiler options"
                fi

                # CSS approach detection
                _css_approach=$(detect_css_approach "$_node_config_root") || _css_approach=""
                scope_vars[CSS_APPROACH]="$_css_approach"

                # CSS approach line (only show if detected)
                [[ -n "${scope_vars[CSS_APPROACH]:-}" ]] && \
                    scope_vars[CSS_APPROACH_LINE]="- CSS: ${scope_vars[CSS_APPROACH]}"

                # Build whole-line placeholders for commands section
                [ -n "${scope_vars[INSTALL_CMD]:-}" ] && \
                    scope_vars[INSTALL_LINE]="- Install: \`${scope_vars[INSTALL_CMD]}\`"
                [ -n "${scope_vars[TYPECHECK_CMD]:-}" ] && \
                    scope_vars[TYPECHECK_LINE]="- Typecheck: \`${scope_vars[TYPECHECK_CMD]}\`"
                [ -n "${scope_vars[LINT_CMD]:-}" ] && \
                    scope_vars[LINT_LINE]="- Lint: \`${scope_vars[LINT_CMD]}\`"
                [ -n "${scope_vars[FORMAT_CMD]:-}" ] && \
                    scope_vars[FORMAT_LINE]="- Format: \`${scope_vars[FORMAT_CMD]}\`"
                [ -n "${scope_vars[TEST_CMD]:-}" ] && \
                    scope_vars[TEST_LINE]="- Test: \`${scope_vars[TEST_CMD]}\`"
                [ -n "${scope_vars[BUILD_CMD]:-}" ] && \
                    scope_vars[BUILD_LINE]="- Build: \`${scope_vars[BUILD_CMD]}\`"
                [ -n "${scope_vars[DEV_CMD]:-}" ] && \
                    scope_vars[DEV_LINE]="- Dev server: \`${scope_vars[DEV_CMD]}\`"

                # Framework-specific component style and conventions
                case "$FRAMEWORK" in
                    "react")
                        scope_vars[COMPONENT_STYLE_LINE]="- Use functional components with hooks"
                        scope_vars[FRAMEWORK_CONVENTIONS]="- Avoid class components"
                        scope_vars[FRAMEWORK_DOCS]="https://react.dev"
                        scope_vars[FRAMEWORK_DOCS_LINE]="- Check React documentation: https://react.dev"
                        ;;
                    "next.js")
                        scope_vars[COMPONENT_STYLE_LINE]="- Use functional components with hooks"
                        scope_vars[FRAMEWORK_CONVENTIONS]="- Use App Router (app/)
- Server Components by default"
                        scope_vars[FRAMEWORK_DOCS]="https://nextjs.org/docs"
                        scope_vars[FRAMEWORK_DOCS_LINE]="- Check Next.js documentation: https://nextjs.org/docs"
                        ;;
                    "vue")
                        scope_vars[COMPONENT_STYLE_LINE]="- Use Composition API with script setup"
                        scope_vars[FRAMEWORK_CONVENTIONS]="- Avoid Options API for new code"
                        scope_vars[FRAMEWORK_DOCS]="https://vuejs.org/guide"
                        scope_vars[FRAMEWORK_DOCS_LINE]="- Check Vue documentation: https://vuejs.org/guide"
                        ;;
                    "svelte")
                        scope_vars[COMPONENT_STYLE_LINE]="- Use Svelte component syntax"
                        scope_vars[FRAMEWORK_CONVENTIONS]=""
                        scope_vars[FRAMEWORK_DOCS]="https://svelte.dev/docs"
                        scope_vars[FRAMEWORK_DOCS_LINE]="- Check Svelte documentation: https://svelte.dev/docs"
                        ;;
                    "angular")
                        scope_vars[COMPONENT_STYLE_LINE]="- Use standalone components"
                        scope_vars[FRAMEWORK_CONVENTIONS]="- Follow Angular style guide"
                        scope_vars[FRAMEWORK_DOCS]="https://angular.dev"
                        scope_vars[FRAMEWORK_DOCS_LINE]="- Check Angular documentation: https://angular.dev"
                        ;;
                    *)
                        scope_vars[COMPONENT_STYLE_LINE]=""
                        scope_vars[FRAMEWORK_CONVENTIONS]=""
                        scope_vars[FRAMEWORK_DOCS]=""
                        scope_vars[FRAMEWORK_DOCS_LINE]=""
                        ;;
                esac

                # Build whole-line placeholders (disappear cleanly when empty)
                [ -n "${scope_vars[NODE_VERSION]:-}" ] && [ "${scope_vars[NODE_VERSION]}" != "unknown" ] && \
                    scope_vars[NODE_VERSION_LINE]="- Node version: ${scope_vars[NODE_VERSION]}"
                [ -n "${scope_vars[FRAMEWORK]:-}" ] && [ "${scope_vars[FRAMEWORK]}" != "none" ] && \
                    scope_vars[FRAMEWORK_LINE]="- Framework: ${scope_vars[FRAMEWORK]}"
                [ -n "${scope_vars[PACKAGE_MANAGER]:-}" ] && [ "${scope_vars[PACKAGE_MANAGER]}" != "unknown" ] && \
                    scope_vars[PACKAGE_MANAGER_LINE]="- Package manager: ${scope_vars[PACKAGE_MANAGER]}"
                [ -n "${scope_vars[ENV_VARS]:-}" ] && \
                    scope_vars[ENV_VARS_LINE]="- Environment variables: ${scope_vars[ENV_VARS]}"

                # Build checklist lines (only when command exists)
                [ -n "${scope_vars[TEST_CMD]:-}" ] && \
                    scope_vars[TEST_CHECKLIST_LINE]="- [ ] Tests pass: \`${scope_vars[TEST_CMD]}\`"
                [ -n "${scope_vars[TYPECHECK_CMD]:-}" ] && \
                    scope_vars[TYPECHECK_CHECKLIST_LINE]="- [ ] TypeScript compiles: \`${scope_vars[TYPECHECK_CMD]}\`"
                [ -n "${scope_vars[LINT_CMD]:-}" ] && \
                    scope_vars[LINT_CHECKLIST_LINE]="- [ ] Lint clean: \`${scope_vars[LINT_CMD]}\`"
                [ -n "${scope_vars[FORMAT_CMD]:-}" ] && \
                    scope_vars[FORMAT_CHECKLIST_LINE]="- [ ] Formatted: \`${scope_vars[FORMAT_CMD]}\`"

                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "ts" "tsx")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "ts" "tsx")
                ;;

            "cli")
                scope_vars[LANGUAGE]="$LANGUAGE"
                CLI_FRAMEWORK="standard"
                [ -f "go.mod" ] && grep -q "github.com/spf13/cobra" go.mod 2>/dev/null && CLI_FRAMEWORK="cobra"
                [ -f "go.mod" ] && grep -q "github.com/urfave/cli" go.mod 2>/dev/null && CLI_FRAMEWORK="urfave/cli"
                scope_vars[CLI_FRAMEWORK]="$CLI_FRAMEWORK"
                scope_vars[BUILD_OUTPUT_PATH]="./bin/"
                build_cmd="$(echo "$SCOPE_COMMANDS" | jq -r '.build // empty')"
                [ -n "$build_cmd" ] && scope_vars[SETUP_INSTRUCTIONS]="- Build: \`$build_cmd\`"
                set_scope_if_present BUILD_CMD "$build_cmd"
                scope_vars[RUN_CMD]="./bin/$(basename "$PROJECT_DIR")"
                set_scope_if_present TEST_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.test // empty')"
                set_scope_if_present LINT_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.lint // empty')"

                # Build whole-line placeholders for setup section
                [ -n "${scope_vars[CLI_FRAMEWORK]:-}" ] && [ "${scope_vars[CLI_FRAMEWORK]}" != "standard" ] && \
                    scope_vars[CLI_FRAMEWORK_LINE]="- CLI framework: ${scope_vars[CLI_FRAMEWORK]}"
                [ -n "${scope_vars[BUILD_OUTPUT_PATH]:-}" ] && \
                    scope_vars[BUILD_OUTPUT_LINE]="- Build output: ${scope_vars[BUILD_OUTPUT_PATH]}"

                # Build whole-line placeholders for commands section
                [ -n "${scope_vars[BUILD_CMD]:-}" ] && \
                    scope_vars[BUILD_LINE]="- Build CLI: \`${scope_vars[BUILD_CMD]}\`"
                [ -n "${scope_vars[RUN_CMD]:-}" ] && \
                    scope_vars[RUN_LINE]="- Run CLI: \`${scope_vars[RUN_CMD]}\`"
                [ -n "${scope_vars[TEST_CMD]:-}" ] && \
                    scope_vars[TEST_LINE]="- Test: \`${scope_vars[TEST_CMD]}\`"
                [ -n "${scope_vars[LINT_CMD]:-}" ] && \
                    scope_vars[LINT_LINE]="- Lint: \`${scope_vars[LINT_CMD]}\`"

                # Build convention and help lines
                [ -n "${scope_vars[CLI_FRAMEWORK]:-}" ] && [ "${scope_vars[CLI_FRAMEWORK]}" != "standard" ] && \
                    scope_vars[CLI_FRAMEWORK_CONVENTION_LINE]="- Use flag parsing library consistently (${scope_vars[CLI_FRAMEWORK]})"
                [ -n "${scope_vars[CLI_FRAMEWORK]:-}" ] && [ "${scope_vars[CLI_FRAMEWORK]}" != "standard" ] && \
                    scope_vars[CLI_FRAMEWORK_DOCS_LINE]="- Review ${scope_vars[CLI_FRAMEWORK]} documentation"

                # Detect language for CLI scope
                cli_ext="go"
                [ -f "package.json" ] && cli_ext="ts"
                [ -f "setup.py" ] || [ -f "pyproject.toml" ] && cli_ext="py"
                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "$cli_ext")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "$cli_ext")
                ;;


            "testing")
                set_scope_if_present TEST_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.test // empty')"
                set_scope_if_present TEST_SINGLE_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.test_single // empty')"
                set_scope_if_present TEST_COVERAGE_CMD "$(echo "$SCOPE_COMMANDS" | jq -r '.test_coverage // empty')"

                # Build whole-line placeholders for commands section
                [ -n "${scope_vars[TEST_CMD]:-}" ] && \
                    scope_vars[TEST_LINE]="- Run all tests: \`${scope_vars[TEST_CMD]}\`"
                [ -n "${scope_vars[TEST_SINGLE_CMD]:-}" ] && \
                    scope_vars[TEST_SINGLE_LINE]="- Run specific test file: \`${scope_vars[TEST_SINGLE_CMD]}\`"
                [ -n "${scope_vars[TEST_COVERAGE_CMD]:-}" ] && \
                    scope_vars[TEST_COVERAGE_LINE]="- Run with coverage: \`${scope_vars[TEST_COVERAGE_CMD]}\`"

                # Detect test file extension
                test_ext="php"
                [ -f "go.mod" ] && test_ext="go"
                [ -f "package.json" ] && test_ext="ts"
                [ -f "pyproject.toml" ] && test_ext="py"
                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "$test_ext")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "$test_ext")
                ;;

            "documentation")
                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "md")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "md")
                ;;

            "examples")
                # Detect example file extension
                ex_ext="go"
                [ -f "package.json" ] && ex_ext="ts"
                [ -f "pyproject.toml" ] && ex_ext="py"
                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "$ex_ext")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "$ex_ext")
                ;;

            "resources")
                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "*")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=""
                ;;

            "claude-code-skill")
                # Extract plugin info (if plugin.json exists)
                plugin_name=$(jq -r '.name // "unknown"' .claude-plugin/plugin.json 2>/dev/null || echo "unknown")
                plugin_version=$(jq -r '.version // "unknown"' .claude-plugin/plugin.json 2>/dev/null || echo "unknown")
                skill_count=$(find skills -maxdepth 2 -name "SKILL.md" -type f 2>/dev/null | wc -l)

                # Build whole-line placeholders
                if [ -f ".claude-plugin/plugin.json" ]; then
                    scope_vars[PLUGIN_JSON_LINE]="- Plugin: $plugin_name v$plugin_version"
                fi
                scope_vars[SKILLS_LINE]="- Skills: $skill_count skill(s) in \`skills/\`"
                if [ -f "composer.json" ]; then
                    scope_vars[INSTALL_LINE]="- Install: \`composer require $(jq -r '.name // "vendor/package"' composer.json 2>/dev/null)\`"
                fi

                # Build command lines if shell scripts exist
                sh_count=$(find . -maxdepth 5 -name "*.sh" -type f 2>/dev/null | wc -l)
                if [ "$sh_count" -gt 0 ]; then
                    scope_vars[LINT_LINE]="- Lint scripts: \`shellcheck skills/*/scripts/*.sh\`"
                    scope_vars[LINT_CHECKLIST_LINE]="- [ ] ShellCheck passes: \`shellcheck skills/*/scripts/*.sh\`"
                fi
                scope_vars[VALIDATE_LINE]="- Validate plugin: \`jq . .claude-plugin/plugin.json\`"

                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "sh")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "md")
                scope_vars[HOUSE_RULES]=""
                ;;

            "docker")
                # Detect Docker and Compose versions from CI or system
                docker_version="latest"
                compose_version="v2"

                # Try to get from CI config
                if [ -f ".github/workflows/docker-build.yml" ]; then
                    docker_version=$(grep -E 'docker.*version' .github/workflows/*.yml 2>/dev/null | head -1 | sed 's/.*: *//' || echo "latest")
                fi

                # Build whole-line placeholders for setup section
                [ -n "$docker_version" ] && [ "$docker_version" != "latest" ] && \
                    scope_vars[DOCKER_VERSION_LINE]="- Docker version: $docker_version"
                [ -n "$compose_version" ] && \
                    scope_vars[COMPOSE_VERSION_LINE]="- Compose version: $compose_version"

                # Detect registry from CI or compose files
                registry=""
                if [ -f "docker-compose.yml" ]; then
                    registry=$(grep -E 'image:' docker-compose.yml 2>/dev/null | head -1 | sed 's/.*image: *//;s/:.*//;s|/.*||' || echo "")
                fi
                if [ -z "$registry" ] && [ -d ".github/workflows" ]; then
                    registry=$(grep -E 'registry:|ghcr.io|docker.io|quay.io' .github/workflows/*.yml 2>/dev/null | head -1 | sed 's/.*: *//' || echo "")
                fi
                [ -n "$registry" ] && scope_vars[REGISTRY_LINE]="- Registry: $registry"

                # Generate file map for Docker files
                docker_file_map=""
                while IFS= read -r df; do
                    [ -z "$df" ] && continue
                    filename=$(basename "$df")
                    [ -z "$docker_file_map" ] && docker_file_map="| File | Purpose |\n|------|---------|"
                    docker_file_map="$docker_file_map\n| \`$filename\` | (add description) |"
                done < <(find "$SCOPE_PATH" -maxdepth 1 -type f \( -name "Dockerfile*" -o -name "*.dockerfile" -o -name "docker-compose*.yml" -o -name "compose*.yml" -o -name ".dockerignore" \) 2>/dev/null | sort)
                scope_vars[SCOPE_FILE_MAP]=$(echo -e "$docker_file_map")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=""
                scope_vars[HOUSE_RULES]=""
                ;;

            "github-actions")
                # Count workflows
                workflow_count=$(find .github/workflows -type f \( -name "*.yml" -o -name "*.yaml" \) 2>/dev/null | wc -l)
                scope_vars[WORKFLOW_COUNT_LINE]="- Workflows: $workflow_count workflow file(s)"

                # Check for reusable workflows
                reusable_count=$(grep -l "workflow_call:" .github/workflows/*.yml 2>/dev/null | wc -l || true)
                [ "$reusable_count" -gt 0 ] && \
                    scope_vars[REUSABLE_WORKFLOWS_LINE]="- Reusable workflows: $reusable_count"

                # Generate file map for workflows
                workflow_file_map=""
                while IFS= read -r wf; do
                    [ -z "$wf" ] && continue
                    filename=$(basename "$wf")
                    # Try to extract workflow name from file
                    wf_name=$(grep -m1 "^name:" "$wf" 2>/dev/null | sed 's/name: *//' || echo "(add description)")
                    [ -z "$workflow_file_map" ] && workflow_file_map="| File | Purpose |\n|------|---------|"
                    workflow_file_map="$workflow_file_map\n| \`$filename\` | $wf_name |"
                done < <(find .github/workflows -maxdepth 1 -type f \( -name "*.yml" -o -name "*.yaml" \) 2>/dev/null | sort)
                scope_vars[SCOPE_FILE_MAP]=$(echo -e "$workflow_file_map")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=""
                scope_vars[HOUSE_RULES]=""
                ;;

            "gitlab-ci")
                # Count pipeline stages/jobs
                job_count=$(grep -cE "^[a-zA-Z_-]+:$" .gitlab-ci.yml 2>/dev/null) || job_count=0
                scope_vars[JOB_COUNT_LINE]="- Jobs defined: ~$job_count"

                # Check for includes
                include_count=$(grep -cE "^  *- " .gitlab-ci.yml 2>/dev/null) || include_count=0
                [ "$include_count" -gt 0 ] && \
                    scope_vars[INCLUDES_LINE]="- Includes external files/templates"

                # File map - just the main file and any .gitlab/ directory contents
                gitlab_file_map="| File | Purpose |\n|------|---------|"
                gitlab_file_map="$gitlab_file_map\n| \`.gitlab-ci.yml\` | Main pipeline configuration |"
                if [ -d ".gitlab" ]; then
                    while IFS= read -r gf; do
                        [ -z "$gf" ] && continue
                        filename="${gf#.gitlab/}"
                        gitlab_file_map="$gitlab_file_map\n| \`.gitlab/$filename\` | (add description) |"
                    done < <(find .gitlab -type f -name "*.yml" 2>/dev/null | sort)
                fi
                scope_vars[SCOPE_FILE_MAP]=$(echo -e "$gitlab_file_map")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=""
                scope_vars[HOUSE_RULES]=""
                ;;

            "concourse")
                # Count pipeline files
                pipeline_count=$(find . -maxdepth 2 -name "*pipeline*.yml" -o -name "*pipeline*.yaml" 2>/dev/null | wc -l)
                scope_vars[PIPELINE_COUNT_LINE]="- Pipeline files: $pipeline_count"

                # Check for tasks directory
                [ -d "ci/tasks" ] || [ -d "tasks" ] && \
                    scope_vars[TASKS_LINE]="- Tasks directory present"

                # File map
                concourse_file_map="| File | Purpose |\n|------|---------|"
                while IFS= read -r pf; do
                    [ -z "$pf" ] && continue
                    filename=$(basename "$pf")
                    concourse_file_map="$concourse_file_map\n| \`$filename\` | (add description) |"
                done < <(find . -maxdepth 2 \( -name "*pipeline*.yml" -o -name "*pipeline*.yaml" \) 2>/dev/null | sort)
                if [ -d "ci/tasks" ]; then
                    task_count=$(find ci/tasks -name "*.yml" 2>/dev/null | wc -l)
                    [ "$task_count" -gt 0 ] && \
                        concourse_file_map="$concourse_file_map\n| \`ci/tasks/\` | $task_count task definition(s) |"
                fi
                scope_vars[SCOPE_FILE_MAP]=$(echo -e "$concourse_file_map")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=""
                scope_vars[HOUSE_RULES]=""
                ;;

            "python-modern")
                scope_vars[PYTHON_VERSION]="$VERSION"
                BUILD_TOOL=$(echo "$PROJECT_INFO" | jq -r '.build_tool')
                scope_vars[PACKAGE_MANAGER]="$BUILD_TOOL"
                scope_vars[ENV_VARS]="See .env or .env.example"

                # Extract commands from detected commands
                scope_vars[INSTALL_CMD]=$(echo "$COMMANDS" | jq -r '.install // empty')
                scope_vars[LINT_CMD]=$(echo "$COMMANDS" | jq -r '.lint // empty')
                scope_vars[FORMAT_CMD]=$(echo "$COMMANDS" | jq -r '.format // empty')
                scope_vars[TEST_CMD]=$(echo "$COMMANDS" | jq -r '.test // empty')
                scope_vars[TYPECHECK_CMD]=$(echo "$COMMANDS" | jq -r '.typecheck // empty')
                scope_vars[BUILD_CMD]=$(echo "$COMMANDS" | jq -r '.build // empty')

                # Set ruff/mypy-aware defaults
                case "$BUILD_TOOL" in
                    "poetry")
                        [ -z "${scope_vars[INSTALL_CMD]}" ] && scope_vars[INSTALL_CMD]="poetry install"
                        [ -z "${scope_vars[LINT_CMD]}" ] && scope_vars[LINT_CMD]="poetry run ruff check ."
                        [ -z "${scope_vars[FORMAT_CMD]}" ] && scope_vars[FORMAT_CMD]="poetry run ruff format ."
                        [ -z "${scope_vars[TEST_CMD]}" ] && scope_vars[TEST_CMD]="poetry run pytest"
                        [ -z "${scope_vars[TYPECHECK_CMD]}" ] && scope_vars[TYPECHECK_CMD]="poetry run mypy ."
                        scope_vars[VENV_CMD]="poetry shell"
                        ;;
                    "uv")
                        [ -z "${scope_vars[INSTALL_CMD]}" ] && scope_vars[INSTALL_CMD]="uv sync"
                        [ -z "${scope_vars[LINT_CMD]}" ] && scope_vars[LINT_CMD]="uv run ruff check ."
                        [ -z "${scope_vars[FORMAT_CMD]}" ] && scope_vars[FORMAT_CMD]="uv run ruff format ."
                        [ -z "${scope_vars[TEST_CMD]}" ] && scope_vars[TEST_CMD]="uv run pytest"
                        [ -z "${scope_vars[TYPECHECK_CMD]}" ] && scope_vars[TYPECHECK_CMD]="uv run mypy ."
                        scope_vars[VENV_CMD]="Managed by uv (auto-creates .venv)"
                        ;;
                    "hatch")
                        [ -z "${scope_vars[INSTALL_CMD]}" ] && scope_vars[INSTALL_CMD]="hatch env create"
                        [ -z "${scope_vars[LINT_CMD]}" ] && scope_vars[LINT_CMD]="hatch run lint:check"
                        [ -z "${scope_vars[FORMAT_CMD]}" ] && scope_vars[FORMAT_CMD]="hatch run lint:fmt"
                        [ -z "${scope_vars[TEST_CMD]}" ] && scope_vars[TEST_CMD]="hatch run test"
                        [ -z "${scope_vars[TYPECHECK_CMD]}" ] && scope_vars[TYPECHECK_CMD]="hatch run types:check"
                        scope_vars[VENV_CMD]="Managed by hatch"
                        ;;
                    *)
                        [ -z "${scope_vars[LINT_CMD]}" ] && scope_vars[LINT_CMD]="ruff check ."
                        [ -z "${scope_vars[FORMAT_CMD]}" ] && scope_vars[FORMAT_CMD]="ruff format ."
                        [ -z "${scope_vars[TEST_CMD]}" ] && scope_vars[TEST_CMD]="pytest"
                        [ -z "${scope_vars[TYPECHECK_CMD]}" ] && scope_vars[TYPECHECK_CMD]="mypy ."
                        scope_vars[VENV_CMD]="python -m venv .venv && source .venv/bin/activate"
                        ;;
                esac

                # Build whole-line placeholders for setup
                [ -n "${scope_vars[PYTHON_VERSION]:-}" ] && [ "${scope_vars[PYTHON_VERSION]}" != "unknown" ] && \
                    scope_vars[PYTHON_VERSION_LINE]="- Python: ${scope_vars[PYTHON_VERSION]}"
                [ -n "${scope_vars[PACKAGE_MANAGER]:-}" ] && [ "${scope_vars[PACKAGE_MANAGER]}" != "unknown" ] && \
                    scope_vars[PACKAGE_MANAGER_LINE]="- Package manager: ${scope_vars[PACKAGE_MANAGER]}"
                [ -n "${scope_vars[VENV_CMD]:-}" ] && \
                    scope_vars[VENV_LINE]="- Virtual env: \`${scope_vars[VENV_CMD]}\`"
                scope_vars[ENV_VARS_LINE]="- Environment: see \`.env\` or \`.env.example\`"

                # Build command table lines
                [ -n "${scope_vars[LINT_CMD]:-}" ] && \
                    scope_vars[RUFF_CHECK_LINE]="| \`${scope_vars[LINT_CMD]}\` | Lint (ruff) | ~5s |"
                [ -n "${scope_vars[FORMAT_CMD]:-}" ] && \
                    scope_vars[RUFF_FORMAT_LINE]="| \`${scope_vars[FORMAT_CMD]} --check\` | Format check | ~3s |"
                [ -n "${scope_vars[TYPECHECK_CMD]:-}" ] && \
                    scope_vars[MYPY_LINE]="| \`${scope_vars[TYPECHECK_CMD]}\` | Type check (mypy) | ~15s |"
                [ -n "${scope_vars[TEST_CMD]:-}" ] && \
                    scope_vars[PYTEST_LINE]="| \`${scope_vars[TEST_CMD]}\` | Run tests | ~30s |"
                [ -n "${scope_vars[TEST_CMD]:-}" ] && \
                    scope_vars[PYTEST_COV_LINE]="| \`${scope_vars[TEST_CMD]} --cov=src\` | Tests + coverage | ~45s |"
                [ -n "${scope_vars[BUILD_CMD]:-}" ] && \
                    scope_vars[BUILD_LINE]="| \`${scope_vars[BUILD_CMD]}\` | Build | ~10s |"

                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "py")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "py")
                scope_vars[HOUSE_RULES]=""
                ;;

            "skill-repo")
                # Extract plugin info (if plugin.json exists)
                plugin_name=$(jq -r '.name // "unknown"' .claude-plugin/plugin.json 2>/dev/null || echo "unknown")
                plugin_version=$(jq -r '.version // "unknown"' .claude-plugin/plugin.json 2>/dev/null || echo "unknown")
                skill_count=$(find skills -maxdepth 2 -name "SKILL.md" -type f 2>/dev/null | wc -l)

                # Build whole-line placeholders
                if [ -f ".claude-plugin/plugin.json" ]; then
                    scope_vars[PLUGIN_JSON_LINE]="- Plugin: $plugin_name v$plugin_version"
                fi
                scope_vars[SKILLS_LINE]="- Skills: $skill_count skill(s) in \`skills/\`"

                # Build command lines if shell scripts exist
                sh_count=$(find . -maxdepth 5 -name "*.sh" -type f 2>/dev/null | wc -l)
                if [ "$sh_count" -gt 0 ]; then
                    scope_vars[LINT_LINE]="- Lint scripts: \`shellcheck skills/*/scripts/*.sh\`"
                    scope_vars[SHELLCHECK_LINE]="- ShellCheck: \`shellcheck skills/*/scripts/*.sh\`"
                fi
                scope_vars[VALIDATE_LINE]="- Validate plugin: \`jq . .claude-plugin/plugin.json\`"

                scope_vars[SCOPE_FILE_MAP]=$(generate_scope_file_map "$SCOPE_PATH" "sh")
                scope_vars[SCOPE_GOLDEN_SAMPLES]=$(generate_scope_golden_samples "$SCOPE_PATH" "md")
                scope_vars[HOUSE_RULES]=""
                ;;
        esac

        # Render template (smart mode respects --update flag)
        render_template_smart "$SCOPE_TEMPLATE" "$SCOPE_FILE" scope_vars "$UPDATE_ONLY"

        # Enforce byte budget for scoped files (use half of root budget)
        enforce_byte_budget "$SCOPE_FILE" "$((BYTE_BUDGET / 2))"

        if [ "$UPDATE_ONLY" = true ]; then
            emit_op write agents-file "$SCOPE_FILE"
            echo "✅ Updated: $SCOPE_FILE"
        else
            emit_op write agents-file "$SCOPE_FILE"
            echo "✅ Created: $SCOPE_FILE"
        fi

        # Create subdirectory symlinks for cross-agent compatibility.
        # Documentation/ is symlink-hostile: the TYPO3 docs renderer lists it
        # via Flysystem, which aborts on ANY symbolic link (#82). Emit a
        # regular @AGENTS.md import file there instead (both Claude Code and
        # Gemini CLI support the @file import syntax).
        if [ "$CREATE_SYMLINKS" = true ]; then
            for symlink_name in CLAUDE.md GEMINI.md; do
                SYMLINK_FILE="$PROJECT_DIR/$SCOPE_PATH/$symlink_name"
                if [ "$(basename "$SCOPE_PATH")" = "Documentation" ]; then
                    if ! compat_file_is_ours "$SYMLINK_FILE" && [ "$FORCE" = false ]; then
                        report_kept_file "$SYMLINK_FILE" "$SCOPE_PATH/$symlink_name"
                        continue
                    fi
                    if [ "$DRY_RUN" = true ]; then
                        emit_op write compat-file "$SYMLINK_FILE" note "@AGENTS.md import file"
                        echo "[DRY-RUN] Would write import file: $SYMLINK_FILE (@AGENTS.md)"
                    else
                        printf '%s\n\n%s\n' \
                            '<!-- Regular file, not a symlink: the TYPO3 docs renderer (Flysystem) rejects symbolic links inside Documentation/. -->' \
                            '@AGENTS.md' | replace_file "$SYMLINK_FILE"
                        emit_op write compat-file "$SYMLINK_FILE" note "@AGENTS.md import file"
                        echo "   ↳ Import file: $SCOPE_PATH/$symlink_name (@AGENTS.md, symlink-hostile directory)"
                    fi
                    continue
                fi
                if compat_file_is_ours "$SYMLINK_FILE"; then
                    if [ "$DRY_RUN" = true ]; then
                        emit_op symlink compat-file "$SYMLINK_FILE" target AGENTS.md
                        echo "[DRY-RUN] Would symlink: $SYMLINK_FILE → AGENTS.md"
                    else
                        ln -sf AGENTS.md "$SYMLINK_FILE"
                        emit_op symlink compat-file "$SYMLINK_FILE" target AGENTS.md
                        echo "   ↳ Symlinked: $SCOPE_PATH/$symlink_name → AGENTS.md"
                    fi
                elif [ "$FORCE" = true ]; then
                    if [ "$DRY_RUN" = true ]; then
                        emit_op symlink compat-file "$SYMLINK_FILE" target AGENTS.md
                        echo "[DRY-RUN] Would replace: $SYMLINK_FILE → AGENTS.md (--force)"
                    else
                        rm -f "$SYMLINK_FILE"
                        ln -s AGENTS.md "$SYMLINK_FILE"
                        emit_op symlink compat-file "$SYMLINK_FILE" target AGENTS.md
                        echo "   ↳ Replaced: $SCOPE_PATH/$symlink_name → AGENTS.md (--force)"
                    fi
                else
                    report_kept_file "$SYMLINK_FILE" "$SCOPE_PATH/$symlink_name"
                fi
            done
        fi

    done < <(echo "$SCOPES_INFO" | jq -c '.scopes[]')
fi

if [ "$DRY_RUN" = true ]; then
    echo ""
    echo "[DRY-RUN] No files were modified. Remove --dry-run to apply changes."
fi

# Print extraction summary
if [ "$VERBOSE" = true ]; then
    print_summary "$PROJECT_INFO" "$SCOPES_INFO" "$COMMANDS" "$DOCS_INFO" "$PLATFORM_INFO" "$IDE_INFO" "$AGENT_INFO"
else
    echo ""
    print_compact_summary "$PROJECT_INFO" "$SCOPES_INFO"
fi

echo ""
echo "✅ AGENTS.md generation complete!"
[ "$SCOPE_COUNT" -gt 0 ] && echo "   Generated: 1 root + $SCOPE_COUNT scoped files" || true

# The manifest goes to the real stdout (fd 3), which --json parked before any
# human line was written. dry_run tells a reader whether these operations are
# planned or already carried out.
if [ "$JSON" = true ]; then
    printf '%s\n' "${MANIFEST[@]:-}" \
        | jq -s --arg project "$PROJECT_DIR" --argjson dry "$([ "$DRY_RUN" = true ] && echo true || echo false)" \
            'map(select(. != null)) as $ops
             | {script: "generate-agents",
                schema: 1,
                dry_run: $dry,
                project: $project,
                summary: ($ops | group_by(.op) | map({key: .[0].op, value: length}) | from_entries),
                operations: $ops}' >&3
fi
rea-changelog-updatemorluto/reaPrepare or rewrite REA release changelogs and GitHub release notes from pinned Git history, with verified contributor thanks and Release Please synchronization.Stars: 469kUpdated Claude CodeCodexVerifiedInstall
academy-guideanthropics/skillsStop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials, and use cases from Claude Academy (academy.claude.com), Anthropic's learning hub. Trigger on: "how do I", "how can I", "getting started with", "what can Claude do", "teach me", "learn to use"; questions about artifacts, projects, skills, plugins, connectors, MCP; requests about rolling Claude out to a team, class, or organization; and any ask for training materials, onboarding content, or learning resources. Use it when the user is learning how to use a feature or product — not when they are mid-task and just want the task done. This skill composes with other skills: after consulting product documentation to answer how a Claude feature works, also check here for a matching course or tutorial — a docs-grounded answer and an Academy recommendation belong together. Only recommend on a strong match; never invent Academy content.Stars: 197kUpdated Claude CodeCodexVerifiedInstall
claude-apianthropics/skillsReference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER — read BEFORE opening the target file; don't skip because it "looks like a one-liner" — whenever: the prompt names Claude/Anthropic in any form (Claude, Anthropic, Fable, Opus, Sonnet, Haiku, `anthropic`, `@anthropic-ai`, `claude-*`, `us.anthropic.*`, `[1m]`); the user asks about an LLM (pricing/model choice/limits/caching) — never answer from memory; OR the task is LLM-shaped with provider unstated (agent/MCP/tool-definition/multi-agent/RAG/LLM-judge/computer-use; generate/summarize/extract/classify/rewrite/converse over NL; debugging refusals/cutoffs/streaming/tool-calls/tokens). SKIP only when another provider is being worked on (overrides all triggers): OpenAI/GPT/Gemini/Llama/Mistral/Cohere/Ollama named in the query; OR `grep -rE 'openai|langchain_openai|google.generativeai|genai|mistralai|cohere|ollama'` over the project hits (run this grep FIRST if no provider named — don't Read the file).Stars: 197kUpdated Claude CodeCodexUnverifiedInstall
doc-coauthoringanthropics/skillsGuide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision docs, or similar structured content. This workflow helps users efficiently transfer context, refine content through iteration, and verify the doc works for readers. Trigger when user mentions writing docs, creating proposals, drafting specs, or similar documentation tasks.Stars: 197kUpdated Claude CodeCodexVerifiedInstall