@zalom/plastic 1.0.0-beta.2 → 1.0.0-beta.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/PLASTIC.md +131 -7
  2. package/agents/plastic-brainstorming.md +9 -1
  3. package/agents/plastic-enforcer.md +1 -1
  4. package/agents/plastic-executor.md +11 -1
  5. package/agents/plastic-intent-curator.md +7 -5
  6. package/agents/plastic-planner.md +11 -1
  7. package/agents/plastic-spec-specialist.md +9 -1
  8. package/hooks/hooks.json +20 -0
  9. package/hooks/retrieval-gate +10 -0
  10. package/hooks/savepoint-pre +10 -0
  11. package/hooks/statusline +150 -41
  12. package/package.json +1 -1
  13. package/scripts/agent-report +163 -0
  14. package/scripts/doctor.rb +172 -0
  15. package/scripts/hook-auto-arm +1 -1
  16. package/scripts/hook-bash-gate +2 -2
  17. package/scripts/hook-code-gate +11 -6
  18. package/scripts/hook-create-gate +2 -2
  19. package/scripts/hook-gate-check +14 -23
  20. package/scripts/hook-retrieval-gate +136 -0
  21. package/scripts/hook-savepoint-pre +32 -0
  22. package/scripts/hook-session-start +1 -1
  23. package/scripts/insight-append +51 -0
  24. package/scripts/lib/bridge.rb +374 -34
  25. package/scripts/lib/frontmatter_writer.rb +130 -0
  26. package/scripts/lib/graph_rebuild.rb +328 -0
  27. package/scripts/lib/insights.rb +86 -0
  28. package/scripts/lib/installer_core.rb +23 -0
  29. package/scripts/lib/link_suggestions.rb +322 -0
  30. package/scripts/lib/links_projection.rb +160 -0
  31. package/scripts/lib/links_section.rb +207 -0
  32. package/scripts/lib/power_tools.rb +76 -0
  33. package/scripts/lib/qmd_hook.rb +38 -25
  34. package/scripts/lib/qmd_sync.rb +36 -0
  35. package/scripts/lib/retrieval_gate.rb +211 -0
  36. package/scripts/lib/worktree.rb +409 -0
  37. package/scripts/link-suggest +211 -0
  38. package/scripts/new-intent +138 -29
  39. package/scripts/project-links +287 -0
  40. package/scripts/qmd-sync +50 -3
  41. package/scripts/rebuild-graph +244 -0
  42. package/scripts/spawn-preamble +26 -1
  43. package/skills/auto/SKILL.md +58 -11
  44. package/skills/auto/evals/evals.json +48 -0
  45. package/skills/auto/references/agent-architecture.md +27 -4
  46. package/skills/auto/references/agent-report-contract.md +121 -0
  47. package/skills/brainstorming/SKILL.md +1 -0
  48. package/skills/brainstorming/evals/evals.json +22 -0
  49. package/skills/continuing/SKILL.md +30 -8
  50. package/skills/continuing/evals/evals.json +9 -0
  51. package/skills/creating-intent/SKILL.md +16 -2
  52. package/skills/creating-intent/evals/evals.json +16 -0
  53. package/skills/creating-intent/references/lifecycle.md +9 -4
  54. package/skills/creating-skills/SKILL.md +56 -0
  55. package/skills/creating-skills/evals/evals.json +75 -0
  56. package/skills/creating-skills/references/agents.md +168 -0
  57. package/skills/creating-skills/references/evals.md +41 -0
  58. package/skills/creating-skills/references/hooks.md +193 -0
  59. package/skills/creating-skills/references/progressive-disclosure.md +176 -0
  60. package/skills/creating-skills/references/scripts.md +166 -0
  61. package/skills/creating-skills/references/skills.md +165 -0
  62. package/skills/creating-skills/scripts/scaffold.rb +313 -0
  63. package/skills/dashboard/SKILL.md +5 -0
  64. package/skills/dashboard/evals/evals.json +22 -0
  65. package/skills/executing-plan/SKILL.md +2 -2
  66. package/skills/humanizer/SKILL.md +39 -0
  67. package/skills/humanizer/evals/evals.json +70 -0
  68. package/skills/humanizer/references/always-on-snippet.md +9 -0
  69. package/skills/humanizer/references/examples.md +48 -0
  70. package/skills/intent-curator/SKILL.md +6 -1
  71. package/skills/intent-curator/evals/evals.json +22 -0
  72. package/skills/linking-intents/SKILL.md +54 -12
  73. package/skills/linking-intents/evals/evals.json +22 -0
  74. package/skills/linking-intents/references/zettelkasten.md +7 -0
  75. package/skills/managing-index/SKILL.md +8 -0
  76. package/skills/managing-index/evals/evals.json +22 -0
  77. package/skills/managing-index/references/zettelkasten-linking.md +6 -1
  78. package/skills/releasing/SKILL.md +32 -0
  79. package/skills/research/SKILL.md +8 -0
  80. package/skills/research/evals/evals.json +22 -0
  81. package/skills/writing-instructions/SKILL.md +0 -159
  82. package/skills/writing-instructions/references/agentskills-spec.md +0 -135
@@ -0,0 +1,193 @@
1
+ # Authoring a Lifecycle Hook
2
+
3
+ A hook is a harness: deterministic code the Claude Code runtime fires at a lifecycle
4
+ event. Author one when a probabilistic skill keeps dropping a behavior and that behavior
5
+ must hold every time.
6
+
7
+ For body voice, budgets, and reference rules, see `progressive-disclosure.md` and `skills.md`.
8
+ For deciding script versus prose and writing the handler logic, read `scripts.md` when the
9
+ handler grows past a few lines. This file covers only hook authoring.
10
+
11
+ ## Contents
12
+
13
+ - When to reach for a hook (E1)
14
+ - The event to matcher to handler model (E2)
15
+ - Which event for which job (E2)
16
+ - Path rules and executability (E3)
17
+ - No-op by default, opt-in (E4)
18
+ - Exit codes and output channels (E5)
19
+ - Verify the harness engaged (E6)
20
+ - Authoring checklist
21
+
22
+ ## When to reach for a hook (E1)
23
+
24
+ Reach for a hook only after a skill has lost the behavior. The documented order is: first
25
+ strengthen the skill description and instructions so the model keeps preferring the skill;
26
+ if it still drops the step, enforce it deterministically with a hook. [E1]
27
+
28
+ Test: ask "does this behavior have to hold even when the model forgets the skill?" If yes
29
+ (a gate before a destructive tool, a savepoint before compaction, a format pass after every
30
+ edit), the runtime must enforce it, not the prompt. If no, leave it in the skill body and
31
+ spend no hook tokens on it. [E1]
32
+
33
+ A hook is code on the critical path of an event. It is not loaded into context, so it costs
34
+ no tokens at trigger time, but a mistuned hook blocks real work. Make it earn the
35
+ intervention. [E1]
36
+
37
+ ## The event to matcher to handler model (E2)
38
+
39
+ Hooks are configured in three nested levels: event, then matcher group, then handler list.
40
+ [E2]
41
+
42
+ - Event: the lifecycle moment (for example PreToolUse, SessionStart, PreCompact).
43
+ - Matcher: which instances of that event fire the handler. For tool events the matcher is a
44
+ tool-name pattern (`Bash`, `Edit|Write`, `mcp__memory__.*`). For SessionStart the matcher
45
+ is a source (`startup`, `resume`, `clear`, `compact`). For PreCompact it is `manual` or
46
+ `auto`.
47
+ - Handler: what runs. Handler types include `command` (a script, JSON arrives on stdin),
48
+ `http`, `mcp_tool`, `prompt` (an LLM yes/no), and `agent`. Author `command` handlers as
49
+ scripts unless a non-script handler is clearly required. [E2]
50
+
51
+ Each event exposes different inputs and a different blocking power, so the wrong event cannot
52
+ do the job no matter how the handler is written. Select the event first, then the matcher,
53
+ then the handler. [E2]
54
+
55
+ ## Which event for which job (E2)
56
+
57
+ | Job | Event | Matcher example | Can block | Key inputs |
58
+ | --- | --- | --- | --- | --- |
59
+ | Gate or validate before a tool runs | PreToolUse | `Edit\|Write`, `Bash` | yes (exit 2 or `permissionDecision: deny`) | `tool_name`, `tool_input` |
60
+ | Format, lint, or remind after a tool succeeds | PostToolUse | `Edit\|Write` | block before next model call only | `tool_name`, `tool_input`, `tool_output` |
61
+ | Boot or inject context at session start | SessionStart | `startup`, `resume`, `clear`, `compact` | no | `source` |
62
+ | Savepoint before compaction | PreCompact | `manual`, `auto` | no (savepoint; exits 0) | compaction trigger |
63
+ | Erase or augment a prompt before processing | UserPromptSubmit | (none) | yes (exit 2) | `prompt`, `permission_mode` |
64
+
65
+ Notes that change the choice of event: [E2]
66
+
67
+ - PreToolUse fires before the tool runs and can stop it. Use it for gates and pre-act
68
+ validation (block an edit to project code before the plan exists, block a destructive
69
+ Bash command).
70
+ - PostToolUse fires after the tool has already run. It cannot undo the tool. Use it to format
71
+ the result, lint it, or surface a reminder, and to block the next model call when the
72
+ output is unacceptable.
73
+ - SessionStart cannot block. Use it to inject boot context, not to enforce anything. Its
74
+ stdout on exit 0 becomes conversation context (see exit codes).
75
+ - PreCompact fires before the runtime compacts the conversation. Use it to write a savepoint
76
+ while the full context still exists.
77
+
78
+ Plastic ships working instances of each: `scripts/hook-code-gate` (PreToolUse gate),
79
+ `scripts/hook-session-start` (SessionStart boot and inject), `scripts/hook-savepoint-pre`
80
+ (PreCompact savepoint). Read one before authoring a new hook of the same shape.
81
+
82
+ ## Path rules and executability (E3)
83
+
84
+ Two failures here are silent: the hook never fires and nothing reports why. [E3]
85
+
86
+ - Reference the handler script through the exported placeholders: `${CLAUDE_PLUGIN_ROOT}` for
87
+ a script shipped inside a plugin, `${CLAUDE_PROJECT_DIR}` for a script that lives in the
88
+ project. A relative path resolves against an unpredictable working directory; a hard-coded
89
+ absolute path works in development and breaks on another machine. [E3]
90
+ - Make the script executable: `chmod +x` the handler file and commit that bit. A
91
+ non-executable `command` handler fails silently. [E3]
92
+ - Give the script a shebang (`#!/usr/bin/env ruby` for Plastic hooks; any shell must run under
93
+ macOS /bin/bash 3.2). [E3]
94
+
95
+ Other placeholders the runtime exports: `${CLAUDE_PLUGIN_DATA}`. [E3]
96
+
97
+ ## No-op by default, opt-in (E4)
98
+
99
+ Make a hook a no-op by default and enable it only through explicit config. Exit 0 (allow,
100
+ emit nothing) unless the user has opted in. A reminder or validation hook that fires for users
101
+ who never enabled it blocks or noises work that was never asked for. [E4]
102
+
103
+ Concrete shape of an opt-in, no-op-by-default handler:
104
+
105
+ ```ruby
106
+ #!/usr/bin/env ruby
107
+ # PostToolUse reminder. No-op unless explicitly enabled.
108
+ require "json"
109
+ config = ENV["CLAUDE_PROJECT_DIR"] ? File.join(ENV["CLAUDE_PROJECT_DIR"], ".myhook.yml") : nil
110
+ exit 0 unless config && File.exist?(config) # opt-in gate: silent allow when not enabled
111
+ payload = JSON.parse($stdin.read) rescue {}
112
+ # ... emit reminder only past this point ...
113
+ exit 0
114
+ ```
115
+
116
+ The early `exit 0` is the opt-in gate. Place the enable check before any side effect. [E4]
117
+ Plastic gate hooks follow the same fail-open discipline: no bridge resolved means exit 0
118
+ (allow), seen in `scripts/hook-code-gate`.
119
+
120
+ ## Exit codes and output channels (E5)
121
+
122
+ The exit code, not the script's intent, decides what the runtime does with the output. [E5]
123
+
124
+ | Exit code | Meaning | Where output goes |
125
+ | --- | --- | --- |
126
+ | 0 | success | stdout shown; for UserPromptSubmit and SessionStart, stdout becomes conversation context |
127
+ | 2 | blocking error | stdout and JSON ignored; stderr fed back to Claude; blocks the action on events that support blocking |
128
+ | other non-zero | non-blocking error | first stderr line in transcript, full text in debug log; action proceeds |
129
+
130
+ Rules that follow from the table: [E5]
131
+
132
+ - To inject context (SessionStart boot banner, UserPromptSubmit augmentation), exit 0 and
133
+ write the context to stdout. On those two events stdout is consumed as context, not just
134
+ displayed.
135
+ - To block (a gate that refuses an edit, a validator that rejects a command), exit 2 and write
136
+ the reason to stderr. The agent reads stderr and can act on it. Plastic gates do exactly
137
+ this: `$stderr.puts "PLASTIC GATE - <reason>"; exit 2`.
138
+ - For PreToolUse, prefer the structured decision over a bare exit. Emit
139
+ `hookSpecificOutput.permissionDecision` with value `allow`, `deny`, `ask`, or `defer`, plus
140
+ `permissionDecisionReason`. Do not use the deprecated top-level `decision` field. [E5]
141
+ - Blocking with exit 2 works only on events that support it. PreToolUse is the clear gate
142
+ event; UserPromptSubmit, Stop, SubagentStop, and a few task events also support exit-2
143
+ blocking. SessionStart and SessionEnd cannot block; exit 2 there does not stop anything.
144
+ PreCompact runs a savepoint, not a gate (see the job table). [E5]
145
+
146
+ PreToolUse JSON shape:
147
+
148
+ ```json
149
+ {
150
+ "hookSpecificOutput": {
151
+ "hookEventName": "PreToolUse",
152
+ "permissionDecision": "deny",
153
+ "permissionDecisionReason": "Plan not yet written; edits to project code are gated."
154
+ }
155
+ }
156
+ ```
157
+
158
+ `hookSpecificOutput` requires `hookEventName`. [E5]
159
+
160
+ ## Verify the harness engaged (E6)
161
+
162
+ A hook that is configured is not a hook that ran. Verify engagement before relying on a hook
163
+ to hold a behavior. [E6]
164
+
165
+ The known failure: in background sessions the session-id environment variable can be unset, so
166
+ hooks that resolve their state through the session (Plastic gates and savepoints resolve a
167
+ per-session bridge) silently no-op. The work proceeds ungated and nothing reports it. [E6]
168
+ This claim is grounded mainly in Plastic's own operation rather than independent reports; treat
169
+ it as Plastic-specific until confirmed elsewhere (LOW-EVIDENCE per E6).
170
+
171
+ Verify by observation, not assumption: [E6]
172
+
173
+ - Trigger the event and confirm the side effect (the gate blocked, the savepoint file appeared,
174
+ the boot context showed). Absence of an error is not proof the hook ran.
175
+ - Check the session-id environment variable is set in the context where the hook must fire;
176
+ if it is unset, session-scoped hooks no-op.
177
+ - For a gate, attempt the action the gate should block and confirm it is refused. A gate that
178
+ never refuses in testing is a gate that is not engaged.
179
+
180
+ ## Authoring checklist
181
+
182
+ - [ ] Behavior must hold deterministically; a stronger skill description was tried first (E1).
183
+ - [ ] Event chosen for its inputs and blocking power; matcher scopes it; handler is a script
184
+ unless another handler type is required (E2).
185
+ - [ ] Script referenced through `${CLAUDE_PLUGIN_ROOT}` or `${CLAUDE_PROJECT_DIR}`, has a
186
+ shebang, and is `chmod +x` (E3).
187
+ - [ ] No-op by default; the opt-in check runs before any side effect; exits 0 when not enabled
188
+ (E4).
189
+ - [ ] Exit codes deliberate: 0 to allow or inject context, 2 to block with the reason on
190
+ stderr; PreToolUse uses `hookSpecificOutput.permissionDecision`, not top-level `decision`
191
+ (E5).
192
+ - [ ] Engagement verified by triggering the event and observing the side effect, including the
193
+ unset-session-id no-op case (E6).
@@ -0,0 +1,176 @@
1
+ # Progressive Disclosure
2
+
3
+ The canonical load-level model for Plastic skills, agents, and hooks. Every other
4
+ reference and the SKILL.md body point here for this model and must not restate it (C7).
5
+ Read it before authoring any skill body, before splitting content into `references/`,
6
+ and before deciding where a file goes (scripts, references, or assets).
7
+
8
+ ## Contents
9
+
10
+ - [The three load levels](#the-three-load-levels)
11
+ - [When to split the body into references](#when-to-split-the-body-into-references)
12
+ - [Bucket selection: scripts vs references vs assets](#bucket-selection-scripts-vs-references-vs-assets)
13
+ - [Reference-link discipline (C4)](#reference-link-discipline-c4)
14
+ - [One level deep, with a table of contents (C5, C6)](#one-level-deep-with-a-table-of-contents-c5-c6)
15
+ - [Store each fact once (C7)](#store-each-fact-once-c7)
16
+ - [Cross-reference other skills by name (C8)](#cross-reference-other-skills-by-name-c8)
17
+ - [Ship only what does the job (C9)](#ship-only-what-does-the-job-c9)
18
+ - [The thin-router pattern (C10)](#the-thin-router-pattern-c10)
19
+ - [Quarantine worked examples (C11)](#quarantine-worked-examples-c11)
20
+
21
+ ## The three load levels
22
+
23
+ Treat each level as a hard design target, not a guideline. The agent platform loads
24
+ each level at a different moment, so a fact in the wrong level either burns context that
25
+ is always present or never arrives when needed. [C1]
26
+
27
+ | Level | What lives here | Budget | When it loads |
28
+ |-------|-----------------|--------|---------------|
29
+ | Metadata | `name` + `description` frontmatter | ~100 tokens | Always, for every skill in the catalog |
30
+ | Body | `SKILL.md` after the frontmatter | under 5000 tokens / under 500 lines | On trigger (description matches the request) |
31
+ | Resources | files in `references/`, `scripts/`, `assets/` | unbounded | On demand (the body points to them, or the agent runs them) |
32
+
33
+ Consequences that drive every other rule in this file:
34
+
35
+ 1. Metadata is paid for on every request, so the description earns its ~100 tokens by
36
+ triggering correctly and nothing more. Authoring rules for the description live in
37
+ `skills.md`.
38
+ 2. Body tokens are paid for only when the skill fires, but then they are paid in full.
39
+ Keep the body to the non-skippable rules plus routing. Push how-to down to resources.
40
+ 3. Resource tokens are paid for only when the agent reaches the file. This is where
41
+ depth, variants, and worked examples belong.
42
+
43
+ ## When to split the body into references
44
+
45
+ Split when the body approaches the budget or carries material the agent does not need on
46
+ every run. Move out first, in this order: advanced cases, variant paths, long worked
47
+ examples, deep domain background. Keep inline only the core workflow plus the selection
48
+ guidance that tells the agent which path or reference to take. [C2]
49
+
50
+ Move to `references/`:
51
+
52
+ - Detailed procedures the agent needs only for one task shape.
53
+ - Advanced or edge-case handling most runs never hit.
54
+ - Variant flows (one file per variant) so the common path stays short.
55
+ - Long examples and tables that document rather than instruct.
56
+
57
+ Keep in the body:
58
+
59
+ - The non-skippable rules (the ones an agent must not get wrong even if it never opens a
60
+ reference).
61
+ - The routing table that maps a request shape to the right reference.
62
+ - Selection guidance: how to choose between the references and paths on offer.
63
+
64
+ ## Bucket selection: scripts vs references vs assets
65
+
66
+ Choose the bucket by how the file touches the context window, not by file type. [C3]
67
+
68
+ | Bucket | Relationship to context | Use for |
69
+ |--------|-------------------------|---------|
70
+ | `scripts/` | Executed, not read. Output enters context, the source does not. | Deterministic logic the agent would otherwise re-derive each run: validators, generators, formatters. See `scripts.md`. |
71
+ | `references/` | Read only when the body points the agent to it. | Depth, procedures, variants, examples that instruct. |
72
+ | `assets/` | Copied into output, never read into context. | Templates, boilerplate, fixtures the agent emits or copies verbatim. |
73
+
74
+ Decision rule: if the content is logic that runs, put it in `scripts/` and document the
75
+ interface (`--help`, exit codes) rather than the implementation. If it is knowledge the
76
+ agent reads to decide or act, put it in `references/`. If it is bytes the agent copies
77
+ into its output without reading, put it in `assets/`.
78
+
79
+ ## Reference-link discipline (C4)
80
+
81
+ Bind every reference link to an observable trigger: a condition the agent can check
82
+ against the request or the run state. Never ship a bare "see references/ for more". A
83
+ bare pointer makes loading a judgment call, so the agent either loads everything (burning
84
+ the budget the split was meant to save) or loads nothing (and acts blind). [C4]
85
+
86
+ | Form | Verdict |
87
+ |------|---------|
88
+ | `Read references/hooks.md when authoring a lifecycle hook.` | Good. Trigger is the task shape. |
89
+ | `Read references/errors.md when the API returns a non-200 status.` | Good. Trigger is observable run state. |
90
+ | `See references/ for more detail.` | Bad. No trigger; loading is a guess. |
91
+ | `Refer to the references as needed.` | Bad. "As needed" is not a condition. |
92
+
93
+ Write the trigger as the request shape the agent can match ("when authoring an agent",
94
+ "when the user names a hook event") or a run-state signal it can read ("when the test
95
+ suite reports a failure", "when the frontmatter validator exits non-zero").
96
+
97
+ ## One level deep, with a table of contents (C5, C6)
98
+
99
+ Keep every reference exactly one level deep from `SKILL.md`: the body links to
100
+ `references/x.md`, and `references/x.md` does not link onward to a further file the agent
101
+ must chase. Nested references get head-previewed by the platform, so the agent acts on a
102
+ partial read and misses content below the preview window. Flatten instead: if a reference
103
+ grows a second level, split it into sibling files the body routes to directly. [C5]
104
+
105
+ Add a table of contents to the top of any reference over 100 lines so the agent can jump
106
+ to the relevant section instead of reading linearly. For very large files, put grep
107
+ patterns in the body so the agent can locate a section without loading the whole file.
108
+ [C6]
109
+
110
+ ## Store each fact once (C7)
111
+
112
+ Keep each fact in exactly one place. Do not restate a rule across the body and a
113
+ reference, across two references, or across two skills. Duplicated doctrine drifts: one
114
+ copy gets updated, the other goes stale, and the agent cannot tell which is current. When
115
+ two files need the same fact, one owns it and the other points to the owner.
116
+
117
+ This file owns the load-level model. The body and the other references point here for it
118
+ and do not repeat the table or the budgets. [C7]
119
+
120
+ ## Cross-reference other skills by name (C8)
121
+
122
+ Name a required companion skill with a requirement marker, not a path. Use a line the
123
+ agent reads as a dependency it loads on its own terms. [C8]
124
+
125
+ | Form | Effect |
126
+ |------|--------|
127
+ | `REQUIRED BACKGROUND: superpowers:test-driven-development` | Good. Names the dependency; the agent loads it when relevant. |
128
+ | `For eval depth, use plastic-evaluating-skills.` | Good. Names the skill, leaves loading to the agent. |
129
+ | `@skills/evaluating-skills/SKILL.md` | Bad. `@`-path syntax force-loads the file immediately, defeating disclosure. |
130
+
131
+ The `@`-path form pulls the target into context the moment the line is read, so it spends
132
+ the budget the level split was built to protect. Name the skill and let the trigger
133
+ decide when it loads.
134
+
135
+ ## Ship only what does the job (C9)
136
+
137
+ Ship the SKILL.md, the references the body routes to, the scripts it runs, and the assets
138
+ it copies. Nothing else. No README, CHANGELOG, or QUICK_REFERENCE inside a skill: the
139
+ description is the skill's front door, and a second front door duplicates it (C7) and adds
140
+ files the agent must skip past. No orphan files (a file no link points to and no script
141
+ runs). If nothing reaches a file, delete it. [C9]
142
+
143
+ ## The thin-router pattern (C10)
144
+
145
+ For a knowledge-heavy domain (one with many distinct request shapes, each needing
146
+ different depth), make the body a thin router: a short header of non-skippable rules plus
147
+ a table that maps a request shape to the one reference that handles it. The body inlines
148
+ no how-to. It decides which reference to load and stops. [C10]
149
+
150
+ Router body shape:
151
+
152
+ ```
153
+ # skill-name
154
+
155
+ <non-skippable rules: the few facts an agent must not get wrong>
156
+
157
+ ## Routing
158
+
159
+ | When the task is... | Read |
160
+ |---------------------|------|
161
+ | authoring an Agent Skill | references/skills.md |
162
+ | authoring a subagent | references/agents.md |
163
+ | authoring a lifecycle hook | references/hooks.md |
164
+ ```
165
+
166
+ The router keeps the always-paid body cost flat as the domain grows: adding a new request
167
+ shape adds one reference and one table row, not more body. Each reference stays focused on
168
+ its one shape.
169
+
170
+ ## Quarantine worked examples (C11)
171
+
172
+ Keep the maxim in context, keep the example out of it. State the rule in the body or the
173
+ reference; move long worked examples to a file the agent loads only when it needs to see
174
+ the rule applied. An example is illustration, not instruction: it is paid for on every run
175
+ if it sits in the body, but it is needed only when the rule alone is not enough. Put the
176
+ short rule where it triggers, and route to the example with a trigger condition (C4). [C11]
@@ -0,0 +1,166 @@
1
+ # Scripts: when deterministic code beats prose
2
+
3
+ Decide whether a skill ships a script, and write scripts that hold their determinism.
4
+ Read this when choosing script versus prose, or when writing a script that ships with a
5
+ skill.
6
+
7
+ For which bucket holds a given piece of content (scripts versus references versus
8
+ assets), read `references/progressive-disclosure.md`. This file covers only the
9
+ script-or-prose decision and script discipline.
10
+
11
+ ## Contents
12
+
13
+ - [Ship a script or write prose](#ship-a-script-or-write-prose)
14
+ - [The three-way test](#the-three-way-test)
15
+ - [Make scripts solve, not punt](#make-scripts-solve-not-punt)
16
+ - [Test by running](#test-by-running)
17
+ - [Match freedom to fragility](#match-freedom-to-fragility)
18
+ - [Wire validators into hooks](#wire-validators-into-hooks)
19
+ - [Script hard requirements](#script-hard-requirements)
20
+ - [Plastic conventions](#plastic-conventions)
21
+ - [Worked example](#worked-example)
22
+ - [Self-check](#self-check)
23
+
24
+ ## Ship a script or write prose
25
+
26
+ Ship a script when either condition holds:
27
+
28
+ 1. The same code gets rewritten on every run.
29
+ 2. Deterministic reliability matters (one wrong character breaks the result).
30
+
31
+ Otherwise write prose. A script is executed, not loaded, so its body stays out of
32
+ context and costs no tokens at trigger time. The price is an indirection: the agent must
33
+ find the script, learn its interface, and run it. Pay that price only when repetition or
34
+ determinism earns it. [G1]
35
+
36
+ ## The three-way test
37
+
38
+ When something repeats, route it by what repeats, not by gut feel. [G2]
39
+
40
+ | What repeats | Bucket | Why |
41
+ | --- | --- | --- |
42
+ | Identical code | `scripts/` | Run it; do not regenerate it each time. |
43
+ | Identical boilerplate output | `assets/` (template) | Copy the template into output; never read it into context. |
44
+ | Re-discovered facts | `references/` | Read it once, on the trigger that needs it. |
45
+
46
+ A symptom of the wrong choice: an agent pasting the same 30 lines of Ruby across three
47
+ runs belongs in `scripts/`, not in prose; a fixed file header the agent retypes belongs
48
+ in `assets/`; a constant the agent keeps looking up belongs in `references/`.
49
+
50
+ ## Make scripts solve, not punt
51
+
52
+ A script that hands its failure back to the agent loses the determinism that justified
53
+ shipping it. [G3]
54
+
55
+ - Handle errors inside the script. Catch the failure, print a clear diagnostic to stderr,
56
+ and exit non-zero. Do not raise a raw stack trace and leave the agent to interpret it.
57
+ - No voodoo constants. Every magic number, path, or threshold gets a name and a comment
58
+ stating where it came from. An unexplained `0.87` is a future break.
59
+ - State the mode. Say explicitly whether the agent executes the script or reads it. A
60
+ validator is executed; a snippet meant to be copied is read. Ambiguity makes the agent
61
+ guess.
62
+
63
+ ## Test by running
64
+
65
+ An untested script is a latent break. Run it against real input before shipping. [G4]
66
+
67
+ - Exercise the success path and at least one failure path; confirm the exit code and the
68
+ stderr message.
69
+ - Delete any example or scratch files the run generated that the skill does not ship.
70
+ Stray files are clutter and may load by accident.
71
+
72
+ ## Match freedom to fragility
73
+
74
+ Match degrees of freedom to fragility. Put guardrails on the narrow bridge, not the open
75
+ field. [G6]
76
+
77
+ | Task shape | Form | Reason |
78
+ | --- | --- | --- |
79
+ | Open, judgment-heavy | Prose | The agent needs room to adapt; code would over-constrain. |
80
+ | A preferred, repeatable pattern | Parameterized script (flags/env) | One correct shape, with controlled variation. |
81
+ | Fragile or destructive sequence | Fixed "do not modify" script | One exact path; any edit risks data loss. |
82
+
83
+ Mark a fragile script as "do not modify" in its `--help` and in the pointer that sends the
84
+ agent to it. For side-effecting workflows, gate execution behind a validator (see below)
85
+ rather than trusting the agent to check preconditions by hand.
86
+
87
+ ## Wire validators into hooks
88
+
89
+ When a rule must hold every time, wire a deterministic validator into a hook rather than
90
+ restating the rule in prose. [G5]
91
+
92
+ - A `PreToolUse` validator can refuse an action before it runs; a packaging step can
93
+ refuse to ship a skill that fails validation.
94
+ - Gate destructive steps behind validate-then-act: the validator passes, then the action
95
+ runs. A prose reminder ("remember to check X first") is probabilistic; a hook is not.
96
+
97
+ For hook event selection, exit-code semantics, and path conventions, read
98
+ `references/hooks.md`.
99
+
100
+ ## Script hard requirements
101
+
102
+ Every script that ships with a skill meets these, because an agent runs it unattended:
103
+
104
+ 1. No interactive prompts. A blocking `gets` or `read -p` hangs the agent forever. Take
105
+ all input up front.
106
+ 2. Input via flags, environment variables, or stdin. Never mid-run questions.
107
+ 3. `--help` is the primary documentation. Describe purpose, every flag, input, output, and
108
+ exit codes there, so the agent learns the interface without reading the source.
109
+ 4. Structured output. Data on stdout, diagnostics and progress on stderr, so the caller
110
+ can capture one without the other.
111
+ 5. Idempotent operations. Running twice produces the same end state; re-running after a
112
+ partial failure is safe.
113
+ 6. Meaningful, documented exit codes. 0 for success, distinct non-zero codes for distinct
114
+ failures, each named in `--help`.
115
+
116
+ ## Plastic conventions
117
+
118
+ - Scripts ship in Ruby. A worked example that shows a script shows Ruby.
119
+ - Any shell script runs under macOS `/bin/bash` 3.2. No `bash` 4.x features (no
120
+ associative arrays, no `mapfile`, no `${var^^}`), and no heredocs inside `$(...)`.
121
+
122
+ ## Worked example
123
+
124
+ A skill validates that an intent slug is well formed before any directory is created. The
125
+ check runs on every intent and must be exact, so it ships as a script, not prose. [G1][G3]
126
+
127
+ `scripts/validate_slug.rb`:
128
+
129
+ ```ruby
130
+ #!/usr/bin/env ruby
131
+ # Validate an intent slug. Execute this; do not inline its logic.
132
+ # Usage: validate_slug.rb SLUG
133
+ # Exit: 0 valid, 1 malformed, 2 wrong argument count.
134
+
135
+ # Convention source: A5 of the best-practices standard (lowercase,
136
+ # digits, single hyphens, no leading/trailing/consecutive hyphens).
137
+ SLUG_PATTERN = /\A[a-z0-9]+(-[a-z0-9]+)*\z/
138
+
139
+ if ARGV.length != 1
140
+ warn "usage: validate_slug.rb SLUG"
141
+ exit 2
142
+ end
143
+
144
+ slug = ARGV.fetch(0)
145
+ if SLUG_PATTERN.match?(slug)
146
+ puts slug # data on stdout
147
+ exit 0
148
+ else
149
+ warn "malformed slug: #{slug.inspect}" # diagnostic on stderr
150
+ exit 1
151
+ end
152
+ ```
153
+
154
+ This script earns its place: identical code on every run, one exact rule, errors handled
155
+ inside, the named constant cites its source, data on stdout and diagnostics on stderr,
156
+ documented exit codes, and the header states it is executed. An open task ("name this
157
+ intent well") would stay prose; this fixed check is a script.
158
+
159
+ ## Self-check
160
+
161
+ - Does this code repeat or demand exactness? If not, it stays prose. [G1]
162
+ - Did the right bucket win the three-way test? [G2]
163
+ - Are errors handled inside, constants named, and the execute-or-read mode stated? [G3]
164
+ - Did the script run green on a success path and a failure path, with scratch files
165
+ removed? [G4]
166
+ - Does fragility match form, with destructive steps gated by a validator? [G5][G6]