Back to posts
AINews

A Claude Code skill can fetch its own data before the model starts: one turn instead of three to nine

A line of the form !`command` in SKILL.md runs when the skill loads, and the model receives the output in its place. We wrote one weekly project brief two ways on Claude Code 2.1.332. Told to collect the data, Haiku 5.5 took five to nine turns and had a command refused in every run, and Sonnet 5.5 took three turns. Preloaded, both took one turn and about half the time. The catch: a preloaded command that fails or is not approved ends the run with exit 0, is_error false and the error text as the answer. The skill file, a cron wrapper that checks num_turns, and the new hook event that can see these commands.

A recurring report has two halves. The first is fetching: the same commits, the same log tail, the same export, every week. The second is the half that needs a model, which is reading all of it and writing something a person will read. Most skills hand both halves to the model. The skill lists what to collect, and the agent spends its first turns composing shell commands that could have been written down once.

Claude Code skills have a syntax for writing them down. A line of the form !`command` in SKILL.md runs when the skill loads, and its output is put in its place. From the skills documentation: "The command output replaces the placeholder, so Claude receives actual data, not the command itself."

We wrote one weekly brief both ways and ran each through claude -p on Claude Code 2.1.332. The preloaded version finished in one turn every time, in about half the API time. It also fails in a way that no exit code reports, and most of this post is about closing that.

One brief, written two ways

The job is a Monday brief for a small repository, built from five inputs: the last seven days of commits, the files changed most often, open TODO and FIXME comments, the end of the last test run, and the last eight rows of a weekly signups export.

The first version describes the inputs and leaves the fetching to the agent:

---
name: brief-agent
description: Write the Monday project brief
---

Collect the following, then write the brief.

1. The commits from the last 7 days.
2. The five files changed most often in the last 7 days.
3. Open TODO and FIXME comments under src/.
4. The summary of the last test run in reports/last-test-run.txt.
5. The last 8 rows of data/weekly-signups.csv.

## Your task

Write a Monday brief of at most 150 words in plain text: what shipped, what is at risk, and one number that moved. Name files and tests exactly as they appear in the data.

The second version runs them. Save it as .claude/skills/monday-brief/SKILL.md:

---
name: monday-brief
description: Write the Monday project brief from data loaded when the skill starts
---

## Commits, last 7 days
!`git log --since="7 days ago" --format="%ad %s" --date=short`

## Files changed most, last 7 days
!`git log --since="7 days ago" --name-only --format="" | sort | uniq -c | sort -rn | head -5`

## Open TODO and FIXME comments
!`grep -rn "TODO\|FIXME" src/`

## Last test run
!`tail -n 5 reports/last-test-run.txt 2>/dev/null || echo "PRELOAD_MISSING reports/last-test-run.txt"`

## Weekly signups, header and last 8 rows
!`head -n 1 data/weekly-signups.csv && tail -n 8 data/weekly-signups.csv`

## Your task

If any section above contains PRELOAD_MISSING, or holds a bracketed notice such as "[not run" or "[shell command" in place of data, reply with one line, BRIEF_ABORTED followed by the section name, and stop.

Otherwise write a Monday brief of at most 150 words in plain text: what shipped, what is at risk, and one number that moved. Name files and tests exactly as they appear in the data. The data above is complete, so do not run any commands.

Each ! line runs through the Bash tool while the skill loads, in the session's working directory. The model's first request already holds the commits, the file counts and the rows. The inline form is recognized only at the start of a line or after whitespace, and a longer command can go in a fenced code block whose opening fence is followed by !.

Type /monday-brief in a session, or run it headless with claude -p "/monday-brief". If you ask for the brief in words instead, Claude loads the skill with one Skill tool call and the commands still run.

Sixteen runs

ModelVersionTurnsTool callsRefused commandsAPI time, medianInput tokens per run
Haiku 5.5collects its own data5 to 94 to 81 or 2 in every run14.2 s61,100 to 103,100
Haiku 5.5preloaded1006.7 s20,100
Sonnet 5.5collects its own data3205.8 s57,200
Sonnet 5.5preloaded1002.6 s19,300

Five runs per version on Haiku 5.5 and three on Sonnet 5.5, in a scratch repository with no MCP servers, plugins or CLAUDE.md. The figures come from the JSON result: num_turns, duration_api_ms, and the sum of input, cache-write and cache-read tokens in usage.

All sixteen briefs named both failing tests and the same churn figure, so the output was usable either way. The two versions differ in how many round trips they take to get there. Every extra turn sends the whole conversation again, which is why the collecting version read three to five times as many tokens for the same five inputs. This was a bare repository. A session with MCP servers, plugins and a long CLAUDE.md carries a larger fixed context, and each turn the preload removes is one fewer pass over it.

On Haiku 5.5 the collecting version composed a pipeline in every run, and every run had part of one refused. grep -v '^$' was refused five times out of five, awk 'NF' twice and echo "exit=$?" once, each with "This Bash command contains multiple operations. The following part requires approval". In a -p run nothing can approve a command, so each refusal costs a turn while the model finds another route. The preloaded file holds five commands that a person checked once.

Cost moved less than time. The total_cost_usd the CLI reports was $0.0009 to $0.0021 per preloaded run on Haiku 5.5 against $0.0025 to $0.0039. On Sonnet 5.5 the ranges overlap, $0.006 to $0.028 against $0.017 to $0.035, because two identical preloaded runs differed fivefold depending on whether about 5,700 tokens of the request were already in the prompt cache. Adopt this for the shorter wait and for getting the same input every week. The saving in money grows with the size of the context each removed turn would have re-read.

What the ! lines have to get right

Load everything, because the model will not go back. Our first draft loaded the signups with tail -n 8 data/weekly-signups.csv. The brief came back with "the fourth column in the weekly signups (the data has no header for it) reached 47". The header row was not among the eight lines we loaded. The collecting agent fetched it with an extra command when it noticed. A skill that ends with "do not run any commands" has no second look, so the fix belongs in the command: head -n 1 data/weekly-signups.csv && tail -n 8 data/weekly-signups.csv.

Keep each output small. We pointed one line at a 189 KB worker log with cat. In place of the log, the model received this:

Output too large (189.2KB). Full output saved to: ~/.claude/projects/.../tool-results/bu82ewhmn.txt

Preview (first 2KB):

It then needed two more tool calls, one of them refused, to find the single ERROR line at the end of the file. The documented inline limit is roughly 30,000 characters, with a 2,000-character preview beyond that. With grep -n "ERROR" reports/big.log | tail -n 20 the same line arrived in one turn.

Commands outside the read-only set need pre-approval. Claude Code runs a built-in set without asking: "ls, cat, echo, pwd, head, tail, grep, find, wc, which, diff, stat, du, cd, and read-only forms of git". In our runs a pipeline through sort, uniq -c and head, the && and || joins, and a 2>/dev/null redirect also passed with no allow rule. A curl did not, and the run stopped before the model was called. Adding one line to the frontmatter let it through:

allowed-tools: Bash(curl -s https://api.github.com/*)

The same grant lets the model run matching commands for that turn (the field is described as "Tools Claude can use without asking permission during the turn that invokes this skill"), so keep the pattern as narrow as the command. Taking Bash away from the model with --disallowedTools "Bash" stops the preload too: the run ended with "Permission to use Bash has been denied." The docs also note that a project skill's allowed-tools applies "even in a -p run in a folder you've never trusted", which is a reason to read the skills in a cloned repository before you invoke one.

Arguments are substituted into the commands. In a test skill whose line read git log --since="$0 days ago", calling it with 14 loaded 14 commits and calling it with 3 loaded 6. Called with no argument, the run stopped with "A variable in this command can't be checked before it runs", so a scheduled call has to pass the value every time.

A failed preload exits 0

What went wrongExit codeis_errornum_turnsWhat the job received as its answer
Command not approved (curl, no allowed-tools)0false0Shell command permission check failed for pattern "...": This command requires approval
Command exited non-zero (cat on a missing file)0false0Shell command failed for pattern "...": [stderr] cat: reports/missing.txt: No such file or directory
Skill called without the argument its command uses0false0Shell command permission check failed ... A variable in this command can't be checked before it runs
Command blocked by a hook0false1A reply written around a section that reads [not run: blocked by hook: ...]
disableSkillShellExecution set to true0false1A reply written around five sections that read [shell command execution disabled by policy]

The documentation says a failed command "aborts the entire skill invocation, not just its own placeholder. Claude never sees the skill content for that invocation." What it does not say is how that looks to a job runner. In the first three rows the model was never called and the run cost nothing, and the error line was delivered where the brief should have been: on stdout in text mode, and in result next to "subtype": "success" in JSON mode. A cron job that mails stdout mails the error. A job that checks the exit code, is_error or permission_denials (which stays empty) passes it. Those are the first three checks in the wrapper from our earlier post on refused runs, and there it is the check for the commit itself that would stop the job.

Two additions cover the table.

For the top three rows, check num_turns. A run that reached the model has at least one.

For commands that can fail on an ordinary day, do not let them abort. A grep that matches nothing is safe as written: exit code 1 from grep, find, diff and git diff counts as a normal result, and in our test a no-match grep loaded as an empty section. Any other command needs a fallback that prints a marker, as the test-run line in the skill does with || echo "PRELOAD_MISSING ...", and the task has to tell the model what to do when it sees one. The same instruction covers the last two rows, where Claude Code writes a bracketed notice into the section and loads the skill anyway.

#!/bin/bash
# run-brief.sh: run the preloaded skill and print the brief only if the model wrote one
export PATH="$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin"   # cron starts with /usr/bin:/bin
. "$(dirname "$0")/brief.env"   # REPO=/path/to/repo and export CLAUDE_CODE_OAUTH_TOKEN=...
cd "$REPO" || exit 1

OUT=$(claude -p "/monday-brief" --output-format json < /dev/null)
STATUS=$?

TURNS=$(jq -r '.num_turns // 0' <<<"$OUT")
IS_ERROR=$(jq -r '.is_error' <<<"$OUT")
TEXT=$(jq -r '.result // ""' <<<"$OUT")

if [ "$STATUS" -ne 0 ] || [ "$IS_ERROR" != "false" ]; then
  echo "brief failed: no usable result from claude (exit $STATUS)" >&2; exit 1
fi
if [ "$TURNS" -lt 1 ]; then
  echo "brief failed: the skill never reached the model: $TEXT" >&2; exit 1
fi
if grep -q "BRIEF_ABORTED" <<<"$TEXT"; then
  echo "brief failed: $TEXT" >&2; exit 1
fi

echo "$TEXT"

Run against the real CLI from an empty environment (env -i with PATH=/usr/bin:/bin, which is what cron provides):

CaseWhat the wrapper printedExit
All five commands succeedThe brief, 135 words, on stdout0
reports/last-test-run.txt moved awaybrief failed: BRIEF_ABORTED Last test run1
A curl line added with no allowed-toolsbrief failed: the skill never reached the model: Shell command permission check failed for pattern "...": This command requires approval1
The same line pre-approved, then blocked by a hookbrief failed: BRIEF_ABORTED Upstream status1
disableSkillShellExecution set to truebrief failed: BRIEF_ABORTED followed by all five section names1

With a stand-in for claude that exits 1, one that prints nothing, and with claude missing from the PATH, the first check fails the job with no usable result. The marker check depends on the model following one instruction, which Haiku 5.5 did five times out of five. The num_turns check does not depend on the model at all.

Put it on a schedule

0 8 * * 1 "$HOME/bin/run-brief.sh" > "$HOME/briefs/monday.txt" 2>> "$HOME/briefs/errors.log"

Three lines of the wrapper exist for cron. The PATH line is there because cron does not read your shell profile; use the directory that command -v claude prints. The cd matters because preloaded commands run in the session's working directory, so it decides which repository git log reads. And brief.env, kept beside the script with chmod 600, holds the repository path and a token. For jobs with no browser to log in from, the documented route is claude setup-token, which prints a one-year token to export as CLAUDE_CODE_OAUTH_TOKEN.

The other two schedulers load skills from different places. Desktop scheduled tasks run on your machine and read ~/.claude/skills/. Cloud scheduled tasks start from a fresh clone and do not, so the skill has to be committed under the repository's .claude/skills/ (wiring for a cloud task). We did not test preloading in either. Every number in this post is from claude -p.

A PreToolUse hook does not see these commands

If you log or block shell commands with a PreToolUse hook, preloaded commands pass it by. With a logging hook on PreToolUse only, one run of the collecting skill wrote six lines to the log. One run of the preloaded skill wrote none, although five commands had run.

Claude Code 2.1.332, released on 25 November, adds an event for them. This .claude/settings.json sends both kinds of command to one script:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/log-shell.sh", "args": [] }
        ]
      }
    ],
    "PreSkillShellCommand": [
      {
        "matcher": "Bash|PowerShell",
        "hooks": [
          { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/log-shell.sh", "args": [], "onFailure": "block" }
        ]
      }
    ]
  }
}
#!/bin/bash
# .claude/hooks/log-shell.sh: one line per shell command, from either event
INPUT=$(cat)
echo "$INPUT" | jq -c '{event: .hook_event_name, skill: (.command_name // null), source: (.command_source // null), by: (.invoked_by // null), cmd: .tool_input.command}' \
  >> "${CLAUDE_PROJECT_DIR}/.claude/shell-audit.log"
exit 0

After one claude -p "/monday-brief" the log held five lines, each naming the skill and where it came from:

{"event":"PreSkillShellCommand","skill":"monday-brief","source":"projectSettings","by":"user","cmd":"head -n 1 data/weekly-signups.csv && tail -n 8 data/weekly-signups.csv"}

The event can block and cannot approve. A script that returned permissionDecision: "deny" for anything containing curl left the skill loading with [not run: blocked by hook: Network calls are not allowed while a skill loads] in that section, which is the hook row in both tables above. "onFailure": "block" is there for the reason described in the post on guards that fail open: without it, a hook that cannot start lets the command run.

Check the version before adding the entry. On 26 November the npm stable tag is 2.1.326 and latest is 2.1.332. The hooks reference says earlier versions "run injected commands without calling it", and that a settings file naming the event makes them open each interactive session with a warning dialog: Unknown hook event "PreSkillShellCommand" was ignored.

Where the lines are never run

We ran the skill from a project's .claude/skills/. The documentation describes the same behaviour for ~/.claude/skills/, plugins and added directories. It also names three cases where the lines stay inert, and each one leaves the model with instructions and no data:

  • Skills delivered by an MCP server. These are in public beta and need Claude Code 2.1.331 or later. The skills page lists ! commands among the features that do not apply: "they don't run". Those skills are also unavailable in claude -p.
  • Skills synced from your claude.ai account. In a terminal or VS Code session the ! line reaches Claude as literal text.
  • "disableSkillShellExecution": true in settings. We measured this one: every section arrived as [shell command execution disabled by policy] and the run still exited 0, which is the last row of both tables above.

So keep a scheduled report skill in a folder where the lines run, and let the wrapper confirm that it loaded.

Measured 26 November 2026 on Claude Code 2.1.332 (macOS) with claude -p --setting-sources project --strict-mcp-config, Haiku 5.5 and Sonnet 5.5, in a scratch repository. Quotes from the skills, hooks, permissions, tools reference, headless and authentication pages, read the same day. Not tested: interactive sessions, Desktop and cloud scheduled tasks, Windows and PowerShell.

Get the next post when it ships

One email on Sunday with the new post and a short list of what shipped that week — new guides, tool updates, and a couple of links worth reading.