Chapter 6 · Deterministic Scripts¶
This is the capability most skill authors never discover — and it's what separates a notes file from a tool.
Skills can bundle executable code in scripts/. The agent runs it like
any command. That changes the reliability math fundamentally:
LLM instructions are probabilistic. Scripts are not. A validation rule written as prose ("keep the subject under 50 characters") is followed most of the time. The same rule inside a script is followed every time, costs zero tokens to enforce, and can be unit-tested in CI.
The division of labor¶
The most useful principle in skill design:
Let the model decide. Let the script verify. Let the script crunch.
| Work | Belongs in | Why |
|---|---|---|
| Choosing a strategy, judging tone, weighing trade-offs | Model (instructions) | Judgment is what the model is good at |
| Enforcing a format, counting, parsing, diffing | Script | Deterministic, testable, free |
| Computing anything from many inputs (git history, file trees, logs) | Script | Cheaper and more accurate than model reconstruction |
| Rendering a known template | Script | Byte-identical output, every run (chapter 7) |
You already do this with humans: you don't describe how to run the linter to a new hire, you hand them the command. Scripts are how a skill hands the agent a command.
When not to script¶
- The logic changes constantly — a script someone must maintain can be worse than instructions the model interprets. Script the stable parts.
- The model would script it anyway, trivially. Don't bundle
grep_wrapper.py; the agent can rungrep. - It needs secrets or network access — now the skill has an attack
surface and an environment contract. Avoid both unless truly required, and
say so in
compatibilitywhen it is.
The anatomy of a good skill script¶
These rules all exist for one audience: the agent on the other side of the exit code. When your script runs, an LLM reads its output and decides what to do next. Write for that reader.
1 · Exit codes are a protocol¶
| Code | Meaning | The agent should… |
|---|---|---|
0 |
Success | Read stdout, continue the workflow |
1 |
Validation failure / business rule | Read the violations, fix its work, re-run |
2 |
Precondition not met (nothing to process, already exists) | Report to user or adjust inputs |
3 |
Environment error (missing tool, bad repo state) | Report the stderr message; don't retry blindly |
Non-zero exits must print actionable messages on stderr — the agent will often self-correct purely from a good error message ("subject is 79 characters; conventional commits require ≤ 72" beats "validation failed").
2 · Single purpose, CLI-first¶
One script, one job, invoked with explicit arguments. Use argparse and
write help text worth reading — the agent reads --help when unsure, so
the help text is documentation the model consumes:
parser = argparse.ArgumentParser(
description="Validate a commit message against Conventional Commits rules.",
epilog="Exit codes: 0 valid · 1 violations found · 2 no input",
)
parser.add_argument("--file", help="path to the message file; reads stdin if omitted")
parser.add_argument("--strict", action="store_true", help="treat warnings as failures")
3 · Deterministic and idempotent¶
- Same input → same output. No
datetime.now(), no randomness — or make time an explicit argument (--date). If you need today's date, derive it from the data (e.g., the HEAD commit date) so re-runs agree. - Running twice is harmless. A generator that appends without checking will double-append the moment the agent retries. Check preconditions, refuse duplicates, or make the operation a pure render.
4 · Stdlib first¶
A script that needs pip install breaks on machines that don't have the
dependency and forces compatibility claims. Python's stdlib covers parsing,
regex, zipfile, subprocess, pathlib, json, csv, and argparse. If you must
use a third-party package, name it in compatibility and fail with an
installation hint.
5 · Cross-platform by construction¶
Pathlib (never string-concatenated paths), forward slashes in all documentation, no Unix-only assumptions in a "simple" script — a good skill runs identically for a teammate on Windows. The example skills in this repo are unit-tested on Linux and Windows in CI for exactly this reason.
6 · Bounded, parseable output¶
Print results to stdout in a stable, greppable format; progress and logs
to stderr. Cap large outputs (--limit, truncate long lists) so one
weird run can't flood the agent's context. Optionally offer --json for
when the agent wants to parse results programmatically.
7 · Separated core, thin CLI¶
Put the logic in pure functions and keep main() as a shell around them.
This is what makes the script unit-testable (chapter
10) and makes the SKILL.md's validation loop honest:
def validate(message: str) -> list[Violation]:
"""Pure function — no I/O, no clock, fully testable."""
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
text = read_input(args)
violations = validate(text)
for v in violations:
print(f"{v.level.upper()} [{v.rule}] {v.message}", file=sys.stderr)
return exit_code(violations, strict=args.strict)
if __name__ == "__main__":
sys.exit(main())
A complete example: check_message.py¶
The commit-crafter skill from the quickstart validates its own output
before showing it to the user. This is the full script from
examples/commit-crafter/scripts/check_message.py,
lightly abridged:
#!/usr/bin/env python3
"""Validate a commit message against Conventional Commits rules.
Exit codes: 0 = valid, 1 = violations found, 2 = no input.
Violations print to stderr as `ERROR|WARNING [rule-id] message`.
"""
from __future__ import annotations
import argparse
import re
import sys
from dataclasses import dataclass
TYPES = ("feat", "fix", "docs", "style", "refactor",
"perf", "test", "build", "ci", "chore", "revert")
SUBJECT_RE = re.compile(
r"^(?P<type>[a-z]+)(?:\((?P<scope>[^()]+)\))?(?P<breaking>!)?:\s(?P<subject>\S.*)$"
)
PAST_TENSE = ("added", "changed", "fixed", "updated", "removed",
"created", "improved", "refactored", "merged", "bumped")
@dataclass(frozen=True)
class Violation:
level: str # "error" | "warning"
rule: str
message: str
def validate(message: str) -> list[Violation]:
"""Pure validation core: string in, violations out."""
out: list[Violation] = []
lines = message.splitlines()
if not lines or not lines[0].strip():
return [Violation("error", "empty", "Message has no subject line.")]
subject, body = lines[0], lines[1:]
match = SUBJECT_RE.match(subject)
if not match:
out.append(Violation(
"error", "format",
'Subject must be "type[(scope)]: description" '
f"(got: {subject!r}).",
))
return out
if match.group("type") not in TYPES:
out.append(Violation(
"error", "type",
f'Unknown type "{match.group("type")}". Allowed: {", ".join(TYPES)}.',
))
first = match.group("subject").split()[0].lower()
if first in PAST_TENSE:
out.append(Violation(
"warning", "mood",
f'Subject starts with "{first}" — use imperative mood '
f'("add", not "added").',
))
if len(match.group("subject")) > 72:
out.append(Violation(
"error", "subject-length",
"Subject is {} characters (max 72).".format(len(match.group("subject"))),
))
elif len(match.group("subject")) > 50:
out.append(Violation(
"warning", "subject-length",
"Subject is {} characters (aim for ≤ 50).".format(len(match.group("subject"))),
))
if match.group("subject").endswith("."):
out.append(Violation("warning", "subject-period",
"Subject should not end with a period."))
if body:
if body[0].strip():
out.append(Violation("error", "body-separator",
"Body must start with a blank line after the subject."))
long_lines = [i + 1 for i, ln in enumerate(body) if len(ln) > 100]
if long_lines:
out.append(Violation("warning", "body-length",
f"Body lines longer than 100 chars: {long_lines}."))
if match.group("breaking") and not any(
ln.startswith("BREAKING CHANGE:") for ln in body):
out.append(Violation("error", "breaking-footer",
'Subject uses "!" but body has no "BREAKING CHANGE:" footer.'))
return out
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--file", help="message file (default: stdin)")
parser.add_argument("--strict", action="store_true",
help="treat warnings as failures")
args = parser.parse_args(argv)
text = open(args.file, encoding="utf-8").read() if args.file else sys.stdin.read()
if not text.strip():
print("No message provided (use --file or pipe to stdin).", file=sys.stderr)
return 2
violations = validate(text)
for v in violations:
print(f"{v.level.upper()} [{v.rule}] {v.message}", file=sys.stderr)
if not violations:
print("OK", file=sys.stderr)
return 0
errors = [v for v in violations if v.level == "error"]
warnings = [v for v in violations if v.level == "warning"]
if errors or (args.strict and warnings):
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
Notice what this buys the skill: the agent can't "forget" the 72-character rule, can't argue with the imperative-mood check, and gets specific, fixable feedback when it slips. The SKILL.md just points at it:
4. Validate the draft before showing it:
python scripts/check_message.py --file message.txt
Fix any violations it reports and re-run until it exits 0.
The feedback-loop pattern¶
Scripts enable the most valuable workflow pattern in skill design — validate early, fix, re-run, only then proceed:
flowchart LR
A["Agent drafts<br>the artifact"] --> B["Run validation<br>script"]
B --> C{"Exit 0?"}
C -- no --> D["Read violations,<br>fix the artifact"]
D --> B
C -- yes --> E["Proceed to<br>next step"]
Any artifact the skill produces — commit messages, config files, generated reports, structured data — deserves this loop. It converts "the model sometimes makes mistakes" into "the model makes mistakes, sees them, and fixes them before you ever look."
Automation worth scripting¶
A field guide for common local flows — the second column is the tell:
| Flow | Script it when… | Sketch |
|---|---|---|
| Git history analysis | You need exact commit data | git log --pretty=format:… parsed in Python |
| File inventories | Counts/limits must be enforced | pathlib.rglob + rules, bounded output |
| Dependency / license audits | Checking against a policy | Parse lockfile, compare to allowlist |
| Test-suite summarization | You need pass/fail counts | Parse runner output, emit JSON |
| Scaffolding | Byte-identical structure every time | Templates + pathlib (chapter 7) |
| Environment preflight | Fail fast before a long workflow | Check tools exist, versions, disk space |
Security: skills are code you run¶
A skill's scripts execute with your permissions. Treat installing someone else's skill exactly like cloning and running someone else's repository:
- Read the scripts before installing third-party skills. Scripts that
curl | bash, phone home, or read credential files are a hard no. - Prefer skills that declare their surface in
compatibilityand use stdlib-only, offline scripts. - Never put secrets in a skill — skills are often committed to repos and zipped into marketplaces.
This matters more as skills become a distribution channel (chapter 11).
Chapter 7 · Templates — static assets the agent fills in, and the boundary between mechanical and judgment work.