# headless

Adopt this skill: https://proskills.md/skills/other/ralfstrobel-agentic-brownfield-coding-claude-plugins-abc-init-skills-headless

Page: https://proskills.md/skills/other/ralfstrobel-agentic-brownfield-coding-claude-plugins-abc-init-skills-headless
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: claude-plugins/abc-init/skills/headless/SKILL.md
size: 11473
sha: 6d633b4877602ad558a904206532c704f9ff5806
upstream: https://github.com/ralfstrobel/agentic-brownfield-coding/blob/main/claude-plugins/abc-init/skills/headless/SKILL.md

```text
---
description:  >
  Assists in the creation of a headless Claude Code batch script that runs an isolated micro-session per item
  (file, line, task) for ad-hoc automation such as bulk migrations, lint-fix loops, or doc generation.
disable-model-invocation: true
user-invocable: true
---

# Claude Code Headless Batch Setup

Your goal is to help the user assemble a small shell script that drives `claude -p` over many inputs,
running one ephemeral micro-session per item. The result usually lives under `.claude/headless/` and pairs
a driver script (`*.sh`) with a system prompt file (`*.md`) and potentially an input list file.

**Additional user arguments**: $ARGUMENTS

**Language hint**: Always create all generated script content and comments in English
for consistency across the codebase, while continuing to speak to the user in the language of their choice.

**Platform hint**: Instructions and templates assume a Linux host with GNU coreutils. Adapt to the detected user OS.
- macOS   — Substitute BSD equivalents for GNU-only utilities.
- Windows — Still use `.sh` files (skip irrelevant `chmod +x`), assuming Git Bash is available at runtime.

# Workflow

1. Ensure the user intent is clear. If user arguments are absent or ambiguous,
   especially regarding the [upcoming decisions](#decisions-to-make),
   elicit the necessary information via informal conversation with the user.
2. Advise the user on a sensible strategy using the [given background](#background-knowledge) as reference.
   Push back on choices that are likely to cause token usage escalation, contention, or silent failures.
3. Pick the best suited template and copy it to `.claude/headless/<descriptive-name>.sh` and `chmod +x` it.
   - [foreach-file.sh](./templates/foreach-file.sh) — one invocation per file matching a glob argument.
   - [foreach-line.sh](./templates/foreach-line.sh) — one invocation per line of stdin (PR numbers, IDs, URLs).
   - [foreach-task.sh](./templates/foreach-task.sh) — one invocation per unchecked item in a sibling checklist file.
     This is the most powerful driver script, capable of ingesting, tracking and resuming progress on arbitrary items.
     Use when the user wants to prepare and iterate on hand-curated task list (in this or a separate session).
   - [foreach-task-parallel.sh](./templates/foreach-task-parallel.sh) — same as `foreach-task.sh` but
     runs `BATCH_SIZE` tasks concurrently per batch. However, tasks with overlapping access scope will race.
     Check the assumptions block at the top of the script for compatibility before suggesting this option.
4. Copy the matching prompt template to `.claude/headless/<descriptive-name>.md`.
   - [foreach-file.md](./templates/foreach-file.md)
   - [foreach-line.md](./templates/foreach-line.md)
   - [foreach-task.md](./templates/foreach-task.md) (also used for the parallel variant)
   For task-based scripts, also create a task file based on [foreach-task.tasks.md](./templates/foreach-task.tasks.md).
   Tailor all of these files to the user's needs, falling back to interactive feedback as required.
5. Tune the parameters in the script such as `CLAUDE_ARGS` and `BATCH_SIZE` per the decisions below.
6. Review the generated content and flag relevant [pitfalls](#pitfalls) that apply to this setup.
7. Remind the user how to run the script from the current working directory,
   suggesting a test run on the first items (script can be aborted at any time using `Ctrl+C`).

## Decisions to Make

These are the variables that determine the right approach, as well as tweaks to the scripts and prompts.

- **Input shape** — File glob, lines on stdin, fixed custom checkbox-list file (resumable).
- **Per-item task** — Specific, mechanical description. What inputs, what outputs, when to exit without action.
- **Tool surface** — Smaller is cheaper, faster, safer. Whitelist (preferred) or blacklist.
  Common shapes: `Read,Grep,Glob` (analysis), `Read,Edit` (single-file rewrite), add `Write` only if needed.
- **Model** — `sonnet` for common tasks; `haiku` for simple tasks, `opus` only when reasoning genuinely demands it.
- **Turn cap** — Set `--max-turns` low (10-20 for mechanical edits, 30-50 for harder tasks).
- **Concurrency** — Sequential by default. Only `foreach-task-parallel.sh` allows parallel execution
                    when time is the larger constraint over cost control and concurrency conflicts are not an issue.
- **Run target** — Local dev workstation (OAuth works) vs. unattended/CI (needs `ANTHROPIC_API_KEY`).

---

# Background Knowledge

## Context Isolation

Each `claude -p` invocation is a fresh agent with no memory of the previous one.
The advantages: predictable cost, parallel-friendly, clean recovery from individual failures, no context contamination.
The trade-off: the agent cannot accumulate cross-item learning. Every item must be self-contained. If the task benefits
from cumulative context (exploring a codebase, building up a plan), headless batching is the wrong tool.

## Custom System Prompt

A headless run with `--system-prompt-file` is mechanically equivalent to a subagent invocation via the
`Agent` tool from the main session. Same isolated context, same custom prompt, same tool restrictions.
The difference is only the entry point: a shell driver iterating over items vs. a parent agent dispatching tasks.

The CLI docs make `--system-prompt` and `--system-prompt-file` sound drastic — as if they replace the entire
system prompt. They don't. Claude Code's system prompt is segmented and conditional.
The injected content only replaces the conversational/persona segments that govern how the agent talks to a user in
an interactive session. The structural parts — tool definitions, environment block, harness rules, hook
contracts, etc. — remain in place. This is exactly how subagents are configured.

## Permissions

Non-interactive `-p` mode cannot display permission dialogs, so the effective tool surface is determined entirely by
`permissions.allow` and `permissions.deny` settings, modified by the command arguments.
Permission directives are evaluated in the order **deny → ask → allow**, where `ask` equals `deny` when non-interactive.

The most important general command argument is `--permission-mode`:
- **`dontAsk`** (recommended for unattended runs) — Auto-denies anything not in `permissions.allow`
  or the built-in read-only whitelist for the `Bash` tool. Error messages explicitly inform agent of this mode.
- **`acceptEdits`** — Auto-allows *any* file edits and common filesystem `Bash` tool ops (`mkdir`, `mv`, `cp`).
- **`bypassPermissions`** (same as `--dangerously-skip-permissions`) — Skips checks entirely.
  Only use under strict isolation (container, worktree, throwaway environment).
- **`auto`** uses a security classifier model to decide — not recommended.
- **`plan`** exposes read-only tools but also some that control plan mode — not recommended.
- **`default`** effectively equivalent to `dontAsk` but with less explanatory error messages — not recommended.

The arguments `--allowedTools` and `--disallowedTools` act exactly as if their content was
added to `permissions.allow` / `permissions.deny` and also take the same syntax (comma separated).
Warning: Listing a bare tool name (e.g. `Bash`) as allowed will allow *every* invocation of the tool,
except for those listed explicitly as denied. Narrow with patterns like `Bash(git:*)` when possible.

Also note that `--allowedTools` must not be confused with `--tools`:
The latter controls which tools are *available* to the model but has no impact on per-invocation permission.
So `--tools` is an effective way to define a tool whitelist, but each must also be allowed to be invoked successfully.

The interaction between `--disallowedTools` and `--tools` is even more nuanced.
If a bare tool name is listed in `--disallowedTools` or the deny settings, it is removed from the *available* tools.
When only certain argument patterns of a tool are denied, the tool in general remains available.
So `--disallowedTools` is an effective way to define a tool blacklist when use of `--tools` is impractical.

## Agent Content Principles

When generating or reviewing content for `.md` prompt files, you are writing for other AI coding agents.
Follow these principles to optimally tailor your instructions and flag violations to the user:

- **Concise** — Minimize token usage. Prefer keywords and telegraphic phrasing over full prose.
- **Structured** — Use compact Markdown to delineate connected aspects.
- **Actionable** — Generate concrete operational directives, not abstract guidelines.
  A headless agent in particular has no one to ask for clarification. Be very prescriptive and leave no ambiguities.
  Clear exhaustive instructions further help reduce costs by facilitating execution by a cheaper model.
- **Referential** — Provide `@<path>` pointers to contextual code files that are relevant for all runs.
  This ensures these files are read deterministically and do not require Read tool calls by the model.
- **Scoped** — Consider which instructions are already ingested by the model via CLAUDE.md or path-based rules.
  Rules and agent instructions progressively disclose domain- and task-specific knowledge.
- **Durable** — Consider the projected lifetime of the generated content.
  For ad-hoc throw-away scripting, duplicating context and code information can save additional reads.
  For recurring batch tasks, only reference related code by path and search terms to avoid drift.

## Pitfalls

- **Cost blowup** — A large batch and many turns each item can very quickly drain rate limits or rack up API costs.
  Pilot first, monitor usage rate at the beginning; cap with `--max-turns` and optionally `--max-budget-usd`.
- **Context bloat** — A large CLAUDE.md, path rules, or many tools adds significant token cost to every micro-session.
- **MCP overhead** — Custom MCP servers start and tool schemas inject every session.
  To prevent this cost in execution time and tokens, substituting an empty `--mcp-config` is advisable if unneeded.
- **Harness applies** — Without `--bare`, project hooks, rules and CLAUDE.md still apply to each session.
  Instructions desired for interactive global scope sessions can have unexpected effects during batch processing
  (e.g. instructions to run test suites, automatically commit to git, update documentation...).
- **Concurrency** — Parallel runs share `.git/index.lock`, the working tree, and any project MCP state.
- **Idempotency** — If the driver script crashes or a second run with improved instructions becomes desirable,
  re-running will process items a second time, leading to overhead cost and potential unexpected behavior.
  Ensure the agent instructions are suitable to detect already processed items and exit or use the task driver script.
- **Authentication** — `--bare` ignores `CLAUDE_CODE_OAUTH_TOKEN` and the local developers OAuth login,
  so it requires `ANTHROPIC_API_KEY`, an equivalent cloud provider or `apiKeyHelper` in settings.

## References

- [Headless mode overview](https://docs.claude.com/en/docs/claude-code/headless)
- [CLI reference](https://docs.claude.com/en/docs/claude-code/cli-reference)
- [Permission Modes](https://code.claude.com/docs/en/permission-modes)
- [Claude Code System Prompt](https://www.dbreunig.com/2026/04/04/how-claude-code-builds-a-system-prompt.html)
```

## File: claude-plugins/abc-init/skills/headless/templates/foreach-file.md
size: 790
sha: 6bcc8923637b5a6551eed235a488fc39be7ac891
upstream: https://github.com/ralfstrobel/agentic-brownfield-coding/blob/main/claude-plugins/abc-init/skills/headless/templates/foreach-file.md

```text
# Batch Execution

You are being invoked once per file as part of an agentic batch migration.
Ask no clarifying questions. If instructions are unclear, exit without taking actions.

The user prompt contains exactly one `@<path>` reference to the target file.
The file content should be automatically pre-loaded for you.
Only **edit this single file**. If the task below does not apply to the file, exit without editing.

## Your Task

> Describe the per-file change here. Be specific and mechanical.
> State the exact transformation, the conditions under which it applies,
> and the conditions under which the agent should exit without changes.
> If results should be machine-readable, prescribe the exact output format
> (e.g. last line must be `OK`, `SKIP <reason>`, or `FAIL <reason>`).
```

## File: claude-plugins/abc-init/skills/headless/templates/foreach-file.sh
size: 2610
sha: d4f7add57f1774975e0dd3dbd3558739c4d1d449
upstream: https://github.com/ralfstrobel/agentic-brownfield-coding/blob/main/claude-plugins/abc-init/skills/headless/templates/foreach-file.sh

```text
#!/usr/bin/env bash
# foreach-file.sh — run a headless `claude` micro-session per file matching a glob expression.
#
# Example: .claude/headless/foreach-file.sh 'src/**/*.ts'
#
# Each matched file becomes the user prompt of one isolated invocation
# via `@<absolute-path>` so its content is pre-loaded for the agent.
# The system prompt with the instructions to perform comes from the sibling `foreach-file.md`.

set -euo pipefail
shopt -s globstar nullglob

trap 'echo "Aborted." >&2; exit 130' INT TERM

CLAUDE_ARGS=(
  --model sonnet                                       # override default model (sonnet|opus|haiku)
  --effort low                                         # reasoning budget per turn
  --tools "Read,Edit"                                  # fixed list of tools available to model
#  --restricted                                         # predefined restricted mode (no settings, no Bash/WebFetch)
#  --allowedTools "..."                                 # whitelist of tool uses that are auto-allowed
#  --disallowedTools "..."                              # blacklist of tool uses that are auto-denied
  --permission-mode dontAsk                            # auto-deny tool use not approved via settings or allowed-tools
  --permission-prompts none                            # disable all interactive prompts and tools
  --max-turns 50                                       # cap agent actions per file (safety net against logic loops)
  --no-session-persistence                             # don't pollute --resume history
  --strict-mcp-config --mcp-config '{"mcpServers":{}}' # disable all MCP servers
#  --output-format json                                 # machine-readable result
#  --bare                                               # ignore all configuration (auth/hooks/skills/MCP/CLAUDE.md)
)

if [[ $# -ne 1 ]]; then
  echo "Usage: $0 '<glob>'" >&2
  exit 64
fi

dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
prompt_file="$dir/foreach-file.md"

[[ -r "$prompt_file" ]] || { echo "Missing prompt file: $prompt_file" >&2; exit 1; }

# Internal glob expansion (so '**' works regardless of caller shell state).
# Intentional unquoted expansion of $1 with globstar+nullglob enabled above.
# shellcheck disable=SC2206
files=( $1 )

if [[ ${#files[@]} -eq 0 ]]; then
  echo "No files matched: $1" >&2
  exit 0
fi

total=${#files[@]}
i=0
for f in "${files[@]}"; do
  [[ -f "$f" ]] || continue
  i=$((i + 1))
  abs="$(realpath -- "$f")"
  printf '\n==> [%d/%d] %s <==\n' "$i" "$total" "$f"
  claude -p "@$abs" --system-prompt-file "$prompt_file" "${CLAUDE_ARGS[@]}"
done
```

## File: claude-plugins/abc-init/skills/headless/templates/foreach-line.md
size: 799
sha: 7b687ad152098b02576e8fe94b64ca37a282cfef
upstream: https://github.com/ralfstrobel/agentic-brownfield-coding/blob/main/claude-plugins/abc-init/skills/headless/templates/foreach-line.md

```text
# Batch Execution

You are being invoked once per input item as part of an agentic batch run.
Ask no clarifying questions. If instructions are unclear, exit without taking actions.

The user prompt contains exactly one item specifying the scope of your work.
Resolve any external context yourself using the tools available to you.
If the task below does not apply to this item, exit without acting.

## Your Task

> Describe the per-item action here. Be specific and mechanical.
> State the exact inputs (how to interpret the item), the exact outputs (file edits, stdout, or both),
> and the conditions under which the agent should exit without changes.
> If results should be machine-readable, prescribe the exact output format
> (e.g. last line must be `OK`, `SKIP <reason>`, or `FAIL <reason>`).
```

## File: claude-plugins/abc-init/skills/headless/templates/foreach-line.sh
size: 2618
sha: 6f7e696079fd895c58217a0f5b3829a0f5339f9c
upstream: https://github.com/ralfstrobel/agentic-brownfield-coding/blob/main/claude-plugins/abc-init/skills/headless/templates/foreach-line.sh

```text
#!/usr/bin/env bash
# foreach-line.sh — run a headless `claude` micro-session per line of stdin.
#
# Examples: gh pr list --json number -q '.[].number' | .claude/headless/foreach-line.sh
#           cat ticket-ids.txt | .claude/headless/foreach-line.sh
#
# Each non-empty non-comment line of stdin becomes the user prompt of one isolated invocation.
# The system prompt with the instructions to perform comes from the sibling `foreach-line.md`.

set -euo pipefail

trap 'echo "Aborted." >&2; exit 130' INT TERM

CLAUDE_ARGS=(
  --model sonnet                                       # override default model (sonnet|opus|haiku)
  --effort low                                         # reasoning budget per turn
  --tools "Glob,Grep,Read,Write,Edit"                  # fixed list of tools available to model
#  --restricted                                         # predefined restricted mode (no settings, no Bash/WebFetch)
#  --allowedTools "..."                                 # whitelist of tool uses that are auto-allowed
#  --disallowedTools "..."                              # blacklist of tool uses that are auto-denied
  --permission-mode dontAsk                            # auto-deny tool use not approved via settings or allowed-tools
  --permission-prompts none                            # disable all interactive prompts and tools
  --max-turns 50                                       # cap agent actions per file (safety net against logic loops)
  --no-session-persistence                             # don't pollute --resume history
  --strict-mcp-config --mcp-config '{"mcpServers":{}}' # disable all MCP servers
#  --output-format json                                 # machine-readable result
#  --bare                                               # ignore all configuration (auth/hooks/skills/MCP/CLAUDE.md)
)

dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
prompt_file="$dir/foreach-line.md"

[[ -r "$prompt_file" ]] || { echo "Missing prompt file: $prompt_file" >&2; exit 1; }

# Drain stdin upfront so the loop body doesn't compete with `claude` for it,
# then reattach stdin to the TTY so Ctrl+C reaches both `claude` and this script.
mapfile -t lines
exec < /dev/tty 2>/dev/null || true

if [[ ${#lines[@]} -eq 0 ]]; then
  echo "No input lines received on stdin." >&2
  exit 1
fi

i=0
for line in "${lines[@]}"; do
  # Skip blanks and comments.
  [[ -z "${line//[[:space:]]/}" ]] && continue
  [[ "${line#\#}" != "$line" ]] && continue

  i=$((i + 1))
  printf '\n==> [%d] %s <==\n' "$i" "$line"
  claude -p "$line" --system-prompt-file "$prompt_file" "${CLAUDE_ARGS[@]}"
done
```

## File: claude-plugins/abc-init/skills/headless/templates/foreach-task-parallel.sh
size: 5900
sha: 88332d1f208710155d292b9db780eaa57fc340fb
upstream: https://github.com/ralfstrobel/agentic-brownfield-coding/blob/main/claude-plugins/abc-init/skills/headless/templates/foreach-task-parallel.sh

```text
#!/usr/bin/env bash
# Run a headless `claude` micro-session per unchecked task in a checklist file, using batched concurrent task execution.
#
# Example: .claude/headless/foreach-task-parallel.sh
#
# Assumptions — violating these will cause races or contention:
#   1. Per-task agents have disjoint write scopes (or are read-only).
#      Two workers editing the same file will race on filesystem state.
#   2. No PostToolUse hook contends for `.git/index.lock` (e.g. an auto `git add` post-write hook).
#   3. The API account can sustain BATCH_SIZE concurrent requests without hitting rate limits.
#   4. The tasks file uses LF line endings and no UTF-8 BOM (offset bookkeeping assumes this).

set -euo pipefail
export LC_ALL=C  # force byte semantics for ${#var} so byte-offset bookkeeping is correct

BATCH_SIZE=4

trap 'trap - INT TERM; echo "Aborted; killing workers." >&2; kill 0 2>/dev/null; exit 130' INT TERM

CLAUDE_ARGS=(
  --model sonnet                                       # override default model (sonnet|opus|haiku)
  --effort low                                         # reasoning budget per turn
  --tools "Glob,Grep,Read,Write,Edit"                  # fixed list of tools available to model
#  --restricted                                         # predefined restricted mode (no settings, no Bash/WebFetch)
#  --allowedTools "..."                                 # whitelist of tool uses that are auto-allowed
#  --disallowedTools "..."                              # blacklist of tool uses that are auto-denied
  --permission-mode dontAsk                            # auto-deny tool use not approved via settings or allowed-tools
  --permission-prompts none                            # disable all interactive prompts and tools
  --max-turns 50                                       # cap agent actions per task (safety net against logic loops)
  --no-session-persistence                             # don't pollute --resume history
  --strict-mcp-config --mcp-config '{"mcpServers":{}}' # disable all MCP servers
#  --output-format json                                 # machine-readable result
#  --bare                                               # ignore all configuration (auth/hooks/skills/MCP/CLAUDE.md)
)

dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
prompt_file="$dir/foreach-task.md"
tasks_file="$dir/foreach-task.tasks.md"

[[ -r "$prompt_file" ]] || { echo "Missing prompt file: $prompt_file" >&2; exit 1; }
[[ -r "$tasks_file" ]] || { echo "Missing tasks file: $tasks_file" >&2; exit 1; }
[[ -w "$tasks_file" ]] || { echo "Tasks file not writable: $tasks_file" >&2; exit 1; }

# Parse and map the task list once at startup. The user is expected to edit the file only while the script
# is not running, so a single snapshot is sufficient and avoids fragile search logic per iteration.
# For each checklist item we record the byte offset of the space inside `[ ]`, so we can flip the checkbox
# later by overwriting exactly one byte via dd — no rename, no inode swap.
# Single-byte writes at independent offsets don't conflict — no flock needed across workers.
regex_item='^([[:space:]]*-[[:space:]]+)\[([ x])\][[:space:]]+(.*)$'
task_offsets=() # byte offsets of the space character inside `[ ]`, used to check box
task_texts=()   # task text after the checkbox prefix
task_done=()    # "1" if already checked at startup, "0" otherwise

byte_pos=0
while IFS= read -r raw || [[ -n "$raw" ]]; do
  if [[ "$raw" =~ $regex_item ]]; then
    task_offsets+=( $(( byte_pos + ${#BASH_REMATCH[1]} + 1 )) )
    task_texts+=( "${BASH_REMATCH[3]}" )
    [[ "${BASH_REMATCH[2]}" == "x" ]] && task_done+=( 1 ) || task_done+=( 0 )
  fi
  byte_pos=$(( byte_pos + ${#raw} + 1 ))  # +1 for the LF that read consumed
done < "$tasks_file"

total=${#task_offsets[@]}
if [[ $total -eq 0 ]]; then
  echo "No checklist items in $tasks_file." >&2
  exit 1
fi

# Worker: run one task, buffer its output in memory, flip checkbox on success.
# Successful runs discard output; failed runs dump it to stderr so the user has a diagnostic.
run_task() {
  local pos="$1" offset="$2" task="$3"
  local out
  if out="$(claude -p "$task" --system-prompt-file "$prompt_file" "${CLAUDE_ARGS[@]}" 2>&1)"; then
    # Note: Exit code 0 only confirms the CLI ran cleanly, not that the agent semantically succeeded.
    echo -n x | dd of="$tasks_file" bs=1 seek="$offset" count=1 conv=notrunc 2>/dev/null
    printf '[OK]   %d/%d %s\n' "$pos" "$total" "$task"
    return 0
  else
    # Build the whole failure block, then write it in one printf — minimises interleaving
    # with concurrent workers writing to stderr at the same time.
    printf '[FAIL] %d/%d %s\n----- output -----\n%s\n----- end -----\n' \
      "$pos" "$total" "$task" "$out" >&2
    return 1
  fi
}

# Build the work queue from the startup snapshot (ensures continuous indices to pull from).
pending=()
for i in "${!task_offsets[@]}"; do
  [[ "${task_done[$i]}" == "0" ]] && pending+=( "$i" )
done

n_pending=${#pending[@]}
failures=0
batch_no=$(( (total - n_pending + BATCH_SIZE - 1) / BATCH_SIZE ))

# Run in batches of BATCH_SIZE with a full barrier between batches.
for (( start = 0; start < n_pending; start += BATCH_SIZE )); do
  batch_no=$((batch_no + 1))
  end=$(( start + BATCH_SIZE ))
  (( end > n_pending )) && end=$n_pending
  printf '\n=== batch %d: %d task(s) ===\n' "$batch_no" "$(( end - start ))"

  pids=()
  for (( k = start; k < end; k++ )); do
    i="${pending[$k]}"
    pos=$((i + 1))
    run_task "$pos" "${task_offsets[$i]}" "${task_texts[$i]}" &
    pids+=( $! )
  done

  # Barrier: wait for every worker in this batch. `|| ...` keeps set -e from aborting on a failure.
  for pid in "${pids[@]}"; do
    wait "$pid" || failures=$((failures + 1))
  done
done

if (( failures > 0 )); then
  echo
  echo "$failures task(s) failed. Re-run to retry only the unchecked ones." >&2
  exit 1
fi
```

## File: claude-plugins/abc-init/skills/headless/templates/foreach-task.md
size: 798
sha: 01f9e068fcbb2419630363a7824e8d67ecadbf47
upstream: https://github.com/ralfstrobel/agentic-brownfield-coding/blob/main/claude-plugins/abc-init/skills/headless/templates/foreach-task.md

```text
# Batch Execution

You are being invoked once per task as part of an agentic batch run.
Ask no clarifying questions. If instructions are unclear, exit without taking actions.

The user prompt contains exactly one task description, taken from a task list file.
Resolve all context yourself using the tools available to you.
If the task in combination with the guidelines below cannot be completed, exit without acting.

## Task Execution Guidelines

> Describe the per-task action here. Be specific and mechanical.
> Define what the task text represents (e.g. "a relative file path", "a refactor instruction", "a feature ticket ID").
> Forbid open-ended interpretation; prescribe exactly what success looks like
> and the conditions under which the agent should fail rather than partially complete.
```

## File: claude-plugins/abc-init/skills/headless/templates/foreach-task.sh
size: 4375
sha: 0d28ed17c62ffed96c5a473fd11ad5ac81102296
upstream: https://github.com/ralfstrobel/agentic-brownfield-coding/blob/main/claude-plugins/abc-init/skills/headless/templates/foreach-task.sh

```text
#!/usr/bin/env bash
# Run a headless `claude` micro-session per unchecked task in a checklist file.
#
# Example: .claude/headless/foreach-task.sh
#
# Reads the sibling `foreach-task.tasks.md`, iterates over lines matching `- [ ] <task>`,
# runs one isolated invocation per unchecked task, and flips the checkbox to `- [x]` after success.
# The system prompt with the instructions to perform comes from the sibling `foreach-task.md`.

set -euo pipefail
export LC_ALL=C  # force byte semantics for ${#var} so byte-offset bookkeeping is correct

trap 'echo "Aborted." >&2; exit 130' INT TERM

CLAUDE_ARGS=(
  --model sonnet                                       # override default model (sonnet|opus|haiku)
  --effort low                                         # reasoning budget per turn
  --tools "Glob,Grep,Read,Write,Edit"                  # fixed list of tools available to model
#  --restricted                                         # predefined restricted mode (no settings, no Bash/WebFetch)
#  --allowedTools "..."                                 # whitelist of tool uses that are auto-allowed
#  --disallowedTools "..."                              # blacklist of tool uses that are auto-denied
  --permission-mode dontAsk                            # auto-deny tool use not approved via settings or allowed-tools
  --permission-prompts none                            # disable all interactive prompts and tools
  --max-turns 50                                       # cap agent actions per task (safety net against logic loops)
  --no-session-persistence                             # don't pollute --resume history
  --strict-mcp-config --mcp-config '{"mcpServers":{}}' # disable all MCP servers
#  --output-format json                                 # machine-readable result
#  --bare                                               # ignore all configuration (auth/hooks/skills/MCP/CLAUDE.md)
)

dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
prompt_file="$dir/foreach-task.md"
tasks_file="$dir/foreach-task.tasks.md"

[[ -r "$prompt_file" ]] || { echo "Missing prompt file: $prompt_file" >&2; exit 1; }
[[ -r "$tasks_file" ]] || { echo "Missing tasks file: $tasks_file" >&2; exit 1; }
[[ -w "$tasks_file" ]] || { echo "Tasks file not writable: $tasks_file" >&2; exit 1; }

# Parse and map the task list once at startup. The user is expected to edit the file only while the script
# is not running, so a single snapshot is sufficient and avoids fragile search logic per iteration.
# For each checklist item we record the byte offset of the space inside `[ ]`, so we can flip the checkbox
# later by overwriting exactly one byte via dd — no rename, no inode swap, safe under concurrent writers.
# Assumes LF line endings and no UTF-8 BOM. Multi-byte task text is fine (LC_ALL=C makes ${#var} byte-count).
regex_item='^([[:space:]]*-[[:space:]]+)\[([ x])\][[:space:]]+(.*)$'
task_offsets=() # byte offsets of the space character inside `[ ]`, used to check box
task_texts=()   # task text after the checkbox prefix
task_done=()    # "1" if already checked at startup, "0" otherwise

byte_pos=0
while IFS= read -r raw || [[ -n "$raw" ]]; do
  if [[ "$raw" =~ $regex_item ]]; then
    task_offsets+=( $(( byte_pos + ${#BASH_REMATCH[1]} + 1 )) )
    task_texts+=( "${BASH_REMATCH[3]}" )
    [[ "${BASH_REMATCH[2]}" == "x" ]] && task_done+=( 1 ) || task_done+=( 0 )
  fi
  byte_pos=$(( byte_pos + ${#raw} + 1 ))  # +1 for the LF that read consumed
done < "$tasks_file"

total=${#task_offsets[@]}
if [[ $total -eq 0 ]]; then
  echo "No checklist items in $tasks_file." >&2
  exit 1
fi

# Iterate the in-memory snapshot; flip checkboxes in the file on the fly for crash durability.
for i in "${!task_offsets[@]}"; do
  [[ "${task_done[$i]}" == "1" ]] && continue
  pos=$((i + 1))
  task="${task_texts[$i]}"
  printf '\n==> [%d/%d] %s <==\n' "$pos" "$total" "$task"

  if claude -p "$task" --system-prompt-file "$prompt_file" "${CLAUDE_ARGS[@]}"; then
    # Note: Exit code 0 only confirms the CLI ran cleanly, not that the agent semantically succeeded.
    # If stricter detection is needed, instruct the prompt to return "FAIL" on last line or use json output.
    echo -n x | dd of="$tasks_file" bs=1 seek="${task_offsets[$i]}" count=1 conv=notrunc 2>/dev/null
  else
    echo "Task failed; leaving unchecked. Re-run to retry." >&2
    exit 1
  fi
done
```

## File: claude-plugins/abc-init/skills/headless/templates/foreach-task.tasks.md
size: 312
sha: c6d7e207aa5546ef7d93a2d136cae0962aa7105d
upstream: https://github.com/ralfstrobel/agentic-brownfield-coding/blob/main/claude-plugins/abc-init/skills/headless/templates/foreach-task.tasks.md

```text
# Tasks

> One task per line, formatted as `- [ ] <task text>`.
> The driver script flips the checkbox to `[x]` after each successful invocation,
> making the batch resumable across runs. Lines that are not checkbox items are ignored.

- [ ] First example task
- [ ] Second example task
- [ ] Third example task
```

## File: README.md
upstream: https://github.com/ralfstrobel/agentic-brownfield-coding/blob/main/README.md

````text
# Agentic Brownfield Coding (ABC)

This Claude Code plugin repo assists complex software projects in their first steps towards agentic coding:
1. Scaffolding and gradually augmenting an existing codebase with an efficient harness setup.
2. Learning controlled agentic development workflows with a human-in-the-loop mindset.

## Background

The ABC project arose from a dissatisfaction with the built-in `/init` command of Claude Code,
which tries to derive agent instructions by scanning the existing repository content.
Especially for large and complex codebases, this approach generally leads to poor results,
as [summarized comprehensively](https://addyosmani.com/blog/agents-md/) by Google engineer Addy Osmani.

Another major inspiration was Dexter Horthy's work on [AI in Complex Codebases](https://github.com/humanlayer/advanced-context-engineering-for-coding-agents/blob/main/ace-fca.md)
which has become known for the RPI workflow. Together with co-founder Kyle Mistele, he promotes disciplined [harness engineering](https://www.humanlayer.dev/blog/skill-issue-harness-engineering-for-coding-agents)
and controlled interactive workflows to rein in the non-determinism of coding agents.

Details about the concrete hypotheses and design philosophy behind the ABC solutions
can be found in the full length [background essay](BACKGROUND.md).

## System Requirements

- **Linux** — natively supported, requires [jq](https://jqlang.org/download/) installed
- **macOS** — supported (agent will substitute GNU-only utilities), requires [jq](https://jqlang.org/download/) installed
- **Windows** — requires [Git Bash](https://git-scm.com/download/win) and [jq](https://www.geeksforgeeks.org/git/how-to-install-jq-in-git-bash/) on PATH

## Installation

```bash
claude plugin marketplace add ralfstrobel/agentic-brownfield-coding

claude plugin install abc-init@agentic-brownfield-coding
claude plugin install abc@agentic-brownfield-coding
```

> [!TIP]
> The separate init plugin is only required once for scaffolding and can be uninstalled after.

### Uninstallation

```bash
claude plugin uninstall abc-init@agentic-brownfield-coding
claude plugin uninstall abc@agentic-brownfield-coding

claude plugin marketplace remove agentic-brownfield-coding
```

## Usage

### Scaffolding

These commands should be run using Fable or Opus as they require complex codebase reasoning.

- [`/abc-init:standalone`](claude-plugins/abc-init/skills/standalone/SKILL.md) – Create initial Claude Code artifacts for single-application projects.
- [`/abc-init:monorepo`](claude-plugins/abc-init/skills/monorepo/SKILL.md) – Create initial Claude Code artifacts for monorepo projects (multiple sub-projects/teams).

- [`/abc-init:bashless`](claude-plugins/abc-init/skills/bashless/SKILL.md) – (Optional) Create MCP tool wrappers for relevant CLI commands
  and disable the `Bash` tool, in order to prevent inefficient tool choice and harness bypassing via shell.
  While highly beneficial to enforce strictly controlled agentic workflows, projects should be aware that this
  introduces increased harness engineering overhead to curate and debug the custom toolset.

- [`/abc-init:headless`](claude-plugins/abc-init/skills/headless/SKILL.md) – (Optional) Scaffold a driver script for batch execution
  of headless agent micro-sessions (repetitive file migrations, doc generation, component analysis...).

> [!IMPORTANT]
> Content generated by the scaffolding skills includes executable shell scripts (statusline, hooks, MCP server)
> that run automatically as part of the Claude Code harness — review and safeguard these files against manipulation!

> [!NOTE]
> The scaffolding result is **not a turnkey solution** and requires thorough testing for every new codebase.
> As even frontier models sometimes struggle to follow long workflows faithfully,
> you may want to read the skill yourself and compare it against your output.
> Content produced by LLMs is also **notoriously verbose**, despite my best efforts to prompt for terse wording.
> I recommend treating any prose output as suggestions and condensing it by hand to what you find relevant.

### Workflows

These commands provide basic examples for agentic workflows during code development.

- [`/abc:build`](claude-plugins/abc/commands/build.md) – Controlled agentic development workflow with explicit steps and human-in-the-loop checkpoints.
- [`/abc:learn`](claude-plugins/abc/commands/learn.md) – Codify implicit codebase knowledge from current conversation as agent context files.

> [!NOTE]
> While the commands can be used productively, their main purpose is to be illustrative.
> You are encouraged to use them as templates to create your own custom workflows for your needs.
> The further reading section below links to various sources for advanced workflow concepts.

### Agents

These files provide basic examples for tasks that can easily be delegated to optimized subagents.

- [`abc:web-researcher`](claude-plugins/abc/agents/web-researcher.md) – Researches a topic online and compiles a compact dossier.

## FAQ

### Why only Claude Code?

At the time of writing, Claude Code is the only major coding assistant to support all artifacts
that form the base of the ABC solutions – primarily custom subagents, commands and hooks.

As long as no suitable standard for these solutions is adopted by a majority of assistants,
the focus will likely remain on Claude Code due to time constraints.

## Further Reading

### Shoutouts and Related Projects

- [superpowers](https://github.com/obra/superpowers) is a well-known plugin for enhanced workflows.
- [GET SHIT DONE](https://github.com/gsd-build/get-shit-done) is a relatively light-weight spec-driven approach for iterative development.
- [Think Upfront](https://github.com/ThinkUpfront/Upfront) provides a robust workflow for human-first agentic development.
- [Cole Medin's AI Workshop](https://github.com/coleam00/ai-transformation-workshop) teaches his method for building an AI-first development setup.

### Directories

- [Anthropic's official Claude Code plugins](https://github.com/anthropics/claude-plugins-official) contain various harness essentials.
- [Awesome Claude Code](https://github.com/hesreallyhim/awesome-claude-code) is a curated list of high-quality Claude Code artifacts.
- [Awesome Harness Engineering](https://github.com/ai-boost/awesome-harness-engineering) is a list focused specifically on harness design.

## License

This work is licensed under [Apache-2.0](LICENSE) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

Attribution via a link to this repository is appreciated. Feedback and contributors are welcome.
````
