draht-codex 2026.7.30 → 2026.10.4-2
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.
- package/.codex-plugin/plugin.json +1 -1
- package/CHANGELOG.md +81 -0
- package/README.md +57 -6
- package/agents/debugger.md +12 -1
- package/agents/git-committer.md +1 -0
- package/agents/implementer.md +11 -2
- package/agents/investigator.md +75 -0
- package/agents/reviewer.md +7 -0
- package/agents/speaker.md +44 -0
- package/agents/verifier.md +4 -3
- package/bin/draht-tools.cjs +472 -41
- package/bin/judge +613 -0
- package/cli.mjs +769 -46
- package/commands/atomic-commit.md +1 -12
- package/commands/create-verification-skill.md +105 -0
- package/commands/discuss-phase.md +3 -14
- package/commands/execute-phase.md +7 -14
- package/commands/fix.md +38 -17
- package/commands/grill.md +66 -0
- package/commands/init-project.md +5 -15
- package/commands/map-codebase.md +1 -13
- package/commands/new-project.md +5 -15
- package/commands/next-milestone.md +2 -13
- package/commands/orchestrate.md +1 -1
- package/commands/pause-work.md +1 -8
- package/commands/plan-phase.md +3 -11
- package/commands/progress.md +0 -8
- package/commands/quick.md +3 -11
- package/commands/resolve-conflicts.md +72 -0
- package/commands/resume-work.md +0 -8
- package/commands/review.md +6 -13
- package/commands/speak.md +45 -0
- package/commands/triage.md +161 -0
- package/commands/verify-work.md +6 -13
- package/commands/why.md +141 -0
- package/graph-archive.mjs +125 -0
- package/graph-manifest.mjs +97 -0
- package/hooks/hooks.json +39 -0
- package/package.json +5 -3
- package/scripts/gsd-quality-gate.cjs +3 -3
- package/scripts/judge-hook.cjs +42 -0
- package/scripts/judge-hook.py +391 -0
- package/scripts/judgegates.py +673 -0
- package/scripts/judgelib.py +382 -0
- package/scripts/speak.cjs +202 -0
- package/skills/atomic-commit/SKILL.md +1 -1
- package/skills/atomic-commit/command.md +62 -0
- package/skills/blast-radius/SKILL.md +56 -0
- package/skills/brainstorming/SKILL.md +11 -4
- package/skills/cinematic-continuation/SKILL.md +111 -0
- package/skills/cinematic-continuation/references/continuity-schema.md +75 -0
- package/skills/cinematic-continuation/references/seedance-adapter.md +44 -0
- package/skills/cinematic-continuation/references/style-bible.md +223 -0
- package/skills/cinematic-continuation/scripts/compile-continuation.mjs +173 -0
- package/skills/cinematic-continuation/templates/continuation-spec.json +50 -0
- package/skills/create-verification-skill/SKILL.md +14 -0
- package/skills/create-verification-skill/command.md +105 -0
- package/skills/debugging-workflow/SKILL.md +38 -10
- package/skills/discuss-phase/SKILL.md +1 -1
- package/skills/discuss-phase/command.md +44 -0
- package/skills/draht/SKILL.md +119 -0
- package/skills/epistemics/SKILL.md +99 -0
- package/skills/execute-phase/SKILL.md +1 -1
- package/skills/execute-phase/command.md +170 -0
- package/skills/explainers/SKILL.md +65 -0
- package/skills/fix/SKILL.md +1 -1
- package/skills/fix/command.md +154 -0
- package/skills/grill/SKILL.md +14 -0
- package/skills/grill/command.md +66 -0
- package/skills/gsd-workflow/SKILL.md +2 -0
- package/skills/init-project/SKILL.md +1 -1
- package/skills/init-project/command.md +57 -0
- package/skills/judge/SKILL.md +57 -0
- package/skills/map-codebase/SKILL.md +1 -1
- package/skills/map-codebase/command.md +61 -0
- package/skills/new-project/SKILL.md +1 -1
- package/skills/new-project/command.md +64 -0
- package/skills/next-milestone/SKILL.md +1 -1
- package/skills/next-milestone/command.md +42 -0
- package/skills/orchestrate/SKILL.md +1 -1
- package/skills/orchestrate/command.md +106 -0
- package/skills/orchestrate-loop/SKILL.md +1 -1
- package/skills/orchestrate-loop/command.md +100 -0
- package/skills/pause-work/SKILL.md +1 -1
- package/skills/pause-work/command.md +32 -0
- package/skills/plan-phase/SKILL.md +1 -1
- package/skills/plan-phase/command.md +140 -0
- package/skills/progress/SKILL.md +1 -1
- package/skills/progress/command.md +22 -0
- package/skills/quick/SKILL.md +1 -1
- package/skills/quick/command.md +91 -0
- package/skills/resolve-conflicts/SKILL.md +14 -0
- package/skills/resolve-conflicts/command.md +72 -0
- package/skills/resume-work/SKILL.md +1 -1
- package/skills/resume-work/command.md +27 -0
- package/skills/review/SKILL.md +1 -1
- package/skills/review/command.md +83 -0
- package/skills/saga-spawner/SKILL.md +131 -0
- package/skills/speak/SKILL.md +14 -0
- package/skills/speak/command.md +45 -0
- package/skills/tdd-workflow/SKILL.md +2 -0
- package/skills/triage/SKILL.md +14 -0
- package/skills/triage/command.md +161 -0
- package/skills/typescript-discipline/SKILL.md +50 -0
- package/skills/typescript-discipline/references/patterns.md +294 -0
- package/skills/unslop/SKILL.md +119 -0
- package/skills/verify-work/SKILL.md +1 -1
- package/skills/verify-work/command.md +117 -0
- package/skills/why/SKILL.md +14 -0
- package/skills/why/command.md +141 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: speak
|
|
3
|
+
description: Draht command prompt wrapper for speak. Use when the user wants text spoken aloud — voice output, text-to-speech, "say it", "read it to me", "sprich", "vorlesen" — or wants a spoken summary of a result via the ElevenLabs API.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Draht Command: speak
|
|
7
|
+
|
|
8
|
+
This skill exposes the Draht prompt command template to Codex's `$draht` and `/skills` surfaces.
|
|
9
|
+
|
|
10
|
+
When invoked:
|
|
11
|
+
1. Read `./command.md` in this skill's directory.
|
|
12
|
+
2. Treat the user's text after the skill mention as `$ARGUMENTS`. If the template uses `$1`, use the first positional argument.
|
|
13
|
+
3. Follow that command template as the active workflow.
|
|
14
|
+
4. Use Draht support skills such as `atomic-reasoning`, `tdd-workflow`, `verification-gate`, or `debugging-workflow` when the command template calls for that discipline.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Speak text aloud via ElevenLabs text-to-speech (voice output for summaries, status updates, or any message the user should hear)
|
|
3
|
+
allowed-tools: Bash, Read
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# /speak
|
|
7
|
+
|
|
8
|
+
Speak text aloud to the user through the local audio device, using the ElevenLabs text-to-speech API.
|
|
9
|
+
|
|
10
|
+
> **Tool note**: Invoke the speak helper as `node "${PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-$HOME/.draht/codex-marketplace/plugins/draht}}/scripts/speak.cjs" [options] "text"` via the Bash tool.
|
|
11
|
+
|
|
12
|
+
## What to speak
|
|
13
|
+
|
|
14
|
+
- `$ARGUMENTS` is the text to speak. If it is empty, speak a short spoken-style summary of the most recent result or answer in the conversation.
|
|
15
|
+
- Rewrite for the ear before speaking: short sentences, no markdown, no code blocks, no raw URLs or file paths (say "the gateway config" instead of reading a path aloud). Keep it under roughly 60 seconds of speech (~1000 characters) unless the user asked for the full text.
|
|
16
|
+
- Speak in the language the user is currently using.
|
|
17
|
+
|
|
18
|
+
## Helper options
|
|
19
|
+
|
|
20
|
+
```
|
|
21
|
+
node "${PLUGIN_ROOT:-${CLAUDE_PLUGIN_ROOT:-$HOME/.draht/codex-marketplace/plugins/draht}}/scripts/speak.cjs" [options] "text"
|
|
22
|
+
--voice <id> ElevenLabs voice id (default: $DRAHT_SPEAK_VOICE_ID or George)
|
|
23
|
+
--model <id> model id (default: $DRAHT_SPEAK_MODEL_ID or eleven_flash_v2_5)
|
|
24
|
+
--speed <n> speaking speed 0.25–4.0
|
|
25
|
+
--lang <code> ISO 639-1 language hint (e.g. de, en)
|
|
26
|
+
--out <file> also keep the mp3 at this path
|
|
27
|
+
--no-play synthesize only, do not play audio
|
|
28
|
+
--force bypass the 4000-character cost guard
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Long text can also be piped on stdin instead of passed as an argument.
|
|
32
|
+
|
|
33
|
+
## API key
|
|
34
|
+
|
|
35
|
+
The helper resolves the key in this order: `$ELEVENLABS_API_KEY` → an `ELEVENLABS_API_KEY=` line in a `.env` file in the working directory → `$HOME/.draht/keys/elevenlabs.key`. If it reports no key, tell the user to store their ElevenLabs API key in one of those places (the `$HOME/.draht/keys/elevenlabs.key` file is the recommended persistent location) — never ask them to paste the key into the chat.
|
|
36
|
+
|
|
37
|
+
## Delegating
|
|
38
|
+
|
|
39
|
+
To speak without blocking the main conversation — or to voice progress updates during long-running work — spawn the `speaker` subagent with the text to speak and the helper path above.
|
|
40
|
+
|
|
41
|
+
## Steps
|
|
42
|
+
|
|
43
|
+
1. Determine the text (from `$ARGUMENTS` or by summarizing), rewrite it for the ear.
|
|
44
|
+
2. Run the helper via Bash. On error, relay the helper's message (missing key, rate limit, no audio player) — do not retry more than once.
|
|
45
|
+
3. Confirm briefly what was spoken (one line, e.g. "Spoke the phase summary, 12 seconds.").
|
|
@@ -52,6 +52,8 @@ Draht enforces strict test-driven development through commit conventions, post-t
|
|
|
52
52
|
|
|
53
53
|
6. **Fix bugs with a reproducing test first.** No exceptions. The test must fail before the fix, pass after.
|
|
54
54
|
|
|
55
|
+
7. **Comments are a design signal.** Comments exist only for constraints the code cannot express. If the green or refactor step leaves code that needs comments to be understood, keep refactoring until it doesn't — never narrate steps or leave "this handles Y" breadcrumbs. Comment density above the surrounding file's norm is a defect to fix before committing; a heavily-commented solution means the design is wrong — redesign, don't annotate.
|
|
56
|
+
|
|
55
57
|
## TDD Cycle Violations
|
|
56
58
|
|
|
57
59
|
The post-task hook (`gsd-post-task.cjs`) checks commit history for cycle violations:
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: triage
|
|
3
|
+
description: Draht command prompt wrapper for triage. Use when the user pastes an external issue report — a bug report, support ticket, `gh issue view` output, or forwarded user complaint — and wants it classified and routed rather than fixed. Classifies (bug / performance / feature request / question / reroute) after a bounded cause trace, dedupes against GitHub Issues with typed outcomes, creates a tracker issue only behind a strict all-conditions gate, and ends with one typed verdict marker. Triggers on "triage this", "someone reported", "is this a bug or a feature request", "should we file this", or a pasted issue report.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Draht Command: triage
|
|
7
|
+
|
|
8
|
+
This skill exposes the Draht prompt command template to Codex's `$draht` and `/skills` surfaces.
|
|
9
|
+
|
|
10
|
+
When invoked:
|
|
11
|
+
1. Read `./command.md` in this skill's directory.
|
|
12
|
+
2. Treat the user's text after the skill mention as `$ARGUMENTS`. If the template uses `$1`, use the first positional argument.
|
|
13
|
+
3. Follow that command template as the active workflow.
|
|
14
|
+
4. Use Draht support skills such as `debugging-workflow`, `epistemics`, or `unslop` when the command template calls for that discipline.
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Triage an external issue report — classify, bounded cause trace, dedupe against GitHub Issues, fail-closed ticket creation, one typed verdict
|
|
3
|
+
argument-hint: "<pasted report, issue URL, or gh issue view output>"
|
|
4
|
+
allowed-tools: Bash, Read, Task
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# /triage
|
|
8
|
+
|
|
9
|
+
Classify one external issue report and end with one useful verdict. Create a tracker issue only for a clear, new bug. Do not reproduce or fix anything here — `/fix` owns that, and a `[triage:bug]` verdict is its entry ticket.
|
|
10
|
+
|
|
11
|
+
Report: $ARGUMENTS
|
|
12
|
+
|
|
13
|
+
> **Tool note**: For the bounded cause trace, spawn a Codex subagent using the `debugger` agent prompt — findings-only diagnosis (no fixes, no writes); classification and every tracker write stay with the orchestrator.
|
|
14
|
+
|
|
15
|
+
## Fail-Closed Rules
|
|
16
|
+
|
|
17
|
+
- One report, one run, one verdict. Do not narrate progress into the tracker.
|
|
18
|
+
- **Prefer no ticket over a guessed or duplicate ticket.**
|
|
19
|
+
- The `debugger` dispatch is findings-only: it diagnoses and reports; it fixes nothing, writes nothing, and never touches the tracker.
|
|
20
|
+
- No repository access → no cause trace: continue with a conservative classification and say in the verdict that cause tracing was unavailable.
|
|
21
|
+
- No confident dedupe → no ticket.
|
|
22
|
+
- Never create an issue that cannot link back to the source report.
|
|
23
|
+
- If a `gh` operation the creation gate requires is unavailable (not installed, unauthenticated, wrong repo), fail closed for that write and say so — the verdict still lands.
|
|
24
|
+
|
|
25
|
+
## 1 — Freeze the source coordinates
|
|
26
|
+
|
|
27
|
+
Pin what "the report" is before delegating or searching, and store it immutably for the rest of the run:
|
|
28
|
+
|
|
29
|
+
- A pasted report → quote its first line verbatim and record where it came from (chat, e-mail, support tool) as the user stated it.
|
|
30
|
+
- An issue URL or `gh issue view` output → store `owner/repo` + issue number, then read it whole: `gh issue view <n> --repo <owner/repo> --json url,title,state,body,comments`.
|
|
31
|
+
- Resolve the target repo for dedupe and creation: the current repo unless the report names another. Ambiguous target → ask; never guess where a ticket lands.
|
|
32
|
+
|
|
33
|
+
Every later read, search, and write uses these stored values. A reply, a cross-link, or a search hit never replaces them.
|
|
34
|
+
|
|
35
|
+
## 2 — Read the whole report
|
|
36
|
+
|
|
37
|
+
Capture before judging:
|
|
38
|
+
|
|
39
|
+
- Reporter wording, verbatim
|
|
40
|
+
- Product version, build, environment, platform when present
|
|
41
|
+
- Expected behavior vs observed behavior
|
|
42
|
+
- Frequency and trigger
|
|
43
|
+
- Error text or stack signature
|
|
44
|
+
- Existing issue, commit, or PR links
|
|
45
|
+
- Any explicit statement that someone is already fixing it
|
|
46
|
+
|
|
47
|
+
If the report references an attachment, screenshot, or recording you cannot read, say so in the verdict — do not invent what it shows.
|
|
48
|
+
|
|
49
|
+
## 3 — Trace cause before routing
|
|
50
|
+
|
|
51
|
+
A bounded source-and-history pass, before choosing a category or an owner. Dispatch the `debugger` agent with this prompt:
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
Investigate this external issue report using root-cause discipline. FINDINGS ONLY: do NOT fix anything, do NOT write or edit files, do NOT create or comment on tracker issues.
|
|
55
|
+
|
|
56
|
+
Report (frozen — do not reinterpret):
|
|
57
|
+
<reporter wording, expected/observed, error text or stack signature, version/environment, trigger>
|
|
58
|
+
|
|
59
|
+
Bounded pass — report on each step:
|
|
60
|
+
1. Identify the likely code path from the reported action to the observed result (file:line anchors).
|
|
61
|
+
2. Check whether the visible symptom belongs to that code path or to a dependency below it.
|
|
62
|
+
3. If the report looks like a regression: `git log --oneline -20` and recent diffs on the affected files — name candidate commits.
|
|
63
|
+
4. Check whether a merged commit or open PR already addresses the same symptom.
|
|
64
|
+
5. Separate confirmed facts from hypotheses — label every statement observed, derived, or assumed.
|
|
65
|
+
|
|
66
|
+
Stop at diagnosis strength sufficient for routing — a complete root cause is /fix's job, not yours. Do not build a reproduction unless one command is already obvious from the report itself.
|
|
67
|
+
|
|
68
|
+
End with STATUS: DONE | DONE_WITH_CONCERNS | NEEDS_CONTEXT | BLOCKED
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
The pass does not need a complete root cause — it must be strong enough to avoid routing a visible symptom to the wrong component. A keyword match between the report and a module name is not a trace; a visible symptom alone is not enough when cause tracing points to a dependency below it. When the report smells like a regression and design intent matters ("was this behaviour a decision or an accident?"), a bounded `/why` consult can supplement the trace — not a full archaeology run.
|
|
72
|
+
|
|
73
|
+
If the repository cannot be read, skip the dispatch, classify conservatively, and record "cause tracing unavailable" for the verdict.
|
|
74
|
+
|
|
75
|
+
## 4 — Classify
|
|
76
|
+
|
|
77
|
+
Choose exactly one:
|
|
78
|
+
|
|
79
|
+
- **Bug** — something violates intended behavior: wrong output, broken state, error, crash, hang, silent no-op, regression.
|
|
80
|
+
- **Performance** — measurable slowness, excess memory, jank, resource drain. Treat as a bug; preserve every measurement and profile the reporter supplied.
|
|
81
|
+
- **Feature request** — current behavior looks intentional; the reporter wants different behavior or a new affordance.
|
|
82
|
+
- **Question or feedback** — asks how something works, or expresses a preference without a concrete defect.
|
|
83
|
+
- **Reroute** — cause tracing shows another repo or team owns it. A route needs evidence from the report or the trace. Say where the report belongs in the verdict; never file it here.
|
|
84
|
+
|
|
85
|
+
When the bug-versus-feature line is unclear, do not file. Ask one focused question in the verdict and close with the `other` marker.
|
|
86
|
+
|
|
87
|
+
## 5 — Dedupe against GitHub Issues
|
|
88
|
+
|
|
89
|
+
GitHub Issues via `gh` is the one tracker this command speaks: search (`gh issue list --search`, `gh search issues`), read (`gh issue view`), update (`gh issue comment`), create (`gh issue create`), compensate (`gh issue close`). Preflight once: `gh auth status` and the resolved target repo.
|
|
90
|
+
|
|
91
|
+
For bug and performance reports, search open AND closed issues before creating anything:
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
gh issue list --repo <owner/repo> --state all --search "<exact error or crash signature>"
|
|
95
|
+
gh issue list --repo <owner/repo> --state all --search "<area> <trigger> <symptom>"
|
|
96
|
+
gh issue list --repo <owner/repo> --state all --search "<version or date window, suspected regression commit>"
|
|
97
|
+
gh search issues --repo <owner/repo> "<source URL or distinctive reporter phrase>"
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Choose one typed outcome and name it in the verdict:
|
|
101
|
+
|
|
102
|
+
- **Confident duplicate** — same signature, or same area + trigger + symptom, or a confirmed shared cause. Add the source reference and one short recurrence note to the existing issue (`gh issue comment`); do not reopen, relabel, or reassign it. Create nothing.
|
|
103
|
+
- **Possibly related** — a shared cause is plausible but not proven. Link it in the verdict as uncertain. Create nothing.
|
|
104
|
+
- **Weak resemblance** — similarity is superficial. Record it as checked; it does not block creation.
|
|
105
|
+
- **No match.**
|
|
106
|
+
|
|
107
|
+
A long-closed issue is a regression lead, not automatically a live duplicate — feed it back into the cause trace instead of linking it as the answer.
|
|
108
|
+
|
|
109
|
+
## 6 — Decide whether to create
|
|
110
|
+
|
|
111
|
+
Create only when ALL of these hold:
|
|
112
|
+
|
|
113
|
+
1. The classification is bug or performance.
|
|
114
|
+
2. The behavior is clearly broken — a violated intent, not a preference.
|
|
115
|
+
3. The issue is still live: no merged commit or open PR from step 3 already addresses it.
|
|
116
|
+
4. Dedupe ran and found no confident duplicate and no plausibly-related live match.
|
|
117
|
+
5. The frozen source coordinates are in hand, so the new issue links back to where the report came from.
|
|
118
|
+
6. `gh` is authenticated against the resolved target repo and title/body/labels resolve — never invent labels, milestones, assignees, or priority.
|
|
119
|
+
7. The run can still compensate: `gh issue close` on its own creation remains possible if the verdict fails to land.
|
|
120
|
+
|
|
121
|
+
Never create for a feature request, question, feedback item, reroute, possible duplicate, confident duplicate, or already-fixed report. If a condition fails, the verdict names which one.
|
|
122
|
+
|
|
123
|
+
The new issue must be self-contained:
|
|
124
|
+
|
|
125
|
+
- Plain title naming the area and the symptom — no guessed root cause in the title
|
|
126
|
+
- Reporter quote
|
|
127
|
+
- Expected and observed behavior
|
|
128
|
+
- Version and environment, or `unknown`
|
|
129
|
+
- Trigger and frequency
|
|
130
|
+
- Source reference (issue URL, or where the pasted report came from)
|
|
131
|
+
- Short cause-trace findings with hypotheses labeled as hypotheses
|
|
132
|
+
- Links to any artifacts (logs, screenshots, profiles)
|
|
133
|
+
|
|
134
|
+
**Compensation**: if this run created an issue and the verdict then cannot be delivered — the run aborts, or the creation turns out wrong before the verdict lands — close the created issue with `gh issue close <n> --comment "triage compensation: verdict did not land"`. An orphaned guess in the tracker is worse than no ticket.
|
|
135
|
+
|
|
136
|
+
## 7 — One verdict
|
|
137
|
+
|
|
138
|
+
Lead with the outcome. Link the existing or new issue when there is one. Name the dedupe outcome. Mention the reroute destination or the one missing fact when needed. Keep it short — the `unslop` bar applies, and every claim follows the `epistemics` labeling the trace carried.
|
|
139
|
+
|
|
140
|
+
End the report with exactly one marker line, the last line of the response:
|
|
141
|
+
|
|
142
|
+
```text
|
|
143
|
+
[triage:bug]
|
|
144
|
+
[triage:bug] tracker=https://github.com/OWNER/REPO/issues/N
|
|
145
|
+
[triage:performance]
|
|
146
|
+
[triage:performance] tracker=https://github.com/OWNER/REPO/issues/N
|
|
147
|
+
[triage:other]
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
`bug` and `performance` carry `tracker=` only when this run matched or created a live issue. Everything else — feature request, question, feedback, reroute, unclear — closes with `[triage:other]`. Never emit two markers; never bury the marker mid-report. A follow-up `/fix` run takes the marker plus its tracker link as the issue input.
|
|
151
|
+
|
|
152
|
+
## Rationalization Table
|
|
153
|
+
|
|
154
|
+
| Excuse | Reality |
|
|
155
|
+
|---|---|
|
|
156
|
+
| "The report names the component, route it there" | A keyword match is not a trace. Route on a confirmed code path or signature, or say the owner is unclear. |
|
|
157
|
+
| "Probably a duplicate of #123" | Probably means possibly related: link it as uncertain and create nothing. |
|
|
158
|
+
| "Filing a ticket is harmless" | A guessed or duplicate ticket costs a maintainer two triages. Prefer no ticket. |
|
|
159
|
+
| "The old closed issue matches, done" | A long-closed issue is a regression lead — trace what re-broke it. |
|
|
160
|
+
| "No repo access, but the cause is obvious" | Reading a report yields hypotheses. Classify conservatively and say the trace was unavailable. |
|
|
161
|
+
| "I'll fix it while I'm here" | Triage ends at the verdict. Hand `[triage:bug]` to `/fix`. |
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: typescript-discipline
|
|
3
|
+
description: TypeScript type-system discipline — make illegal states unrepresentable with discriminated unions, build types constructively instead of guarding loose ones, brand semantic primitives, parse external data once at the boundary and trust types inside, keep functions total and strengthen a type only where partiality appears, make the compiler enforce exhaustiveness. Use when reading or editing any .ts or .tsx file, designing a type or function signature, reviewing a TypeScript diff, or deciding whether an `any`, an `as` cast, or a non-null `!` is acceptable.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# TypeScript Discipline
|
|
7
|
+
|
|
8
|
+
The type checker is a proof assistant. Used well, it eliminates impossible states, mismatched primitives, and unhandled variants at compile time; every case the types let you ignore is a runtime failure the compiler could have stopped. Prefer defining errors out of existence over proliferating handlers — unrepresentable states, total functions, and boundary parsing are the tools for that.
|
|
9
|
+
|
|
10
|
+
Two layers: the principles below hold in any statically-typed language; the rule table and `./references/patterns.md` ground them in TypeScript syntax.
|
|
11
|
+
|
|
12
|
+
## Principles
|
|
13
|
+
|
|
14
|
+
- **Make illegal states unrepresentable.** Model variants as a discriminated union, not as a bag of optional fields where contradictory combinations compile. The canonical anti-pattern: `{ completed: boolean; completedAt?: Date }` admits `completed: true` with `completedAt: undefined`, which means nothing. Derive the boolean from a single source (`completedAt !== null`) or model the variants explicitly: `{ kind: 'open' } | { kind: 'done'; at: Date }`. If a bug ever forces the question "wait, can this combination actually happen?", the type is too loose.
|
|
15
|
+
- **Types are constructions, not restrictions.** Build the type up from the values you want instead of carving them out of a looser type with runtime checks. A non-empty list is a head plus a rest, not a list with a length check. A valid time range is a start plus a duration, not two timestamps you must keep ordered. No representation is privileged — pick the shape that cannot build the illegal value, then expose the interface callers need on top of it.
|
|
16
|
+
- **Brand semantic primitives.** A `UserId` and an `OrderId` are both strings underneath but must not be interchangeable. Brand them, validate once at creation, trust the type downstream.
|
|
17
|
+
- **External data is untyped until parsed.** RPC payloads, JSON, CLI args, config files, environment variables, database rows: each gets a parse function at the boundary that turns unstructured input into the typed domain model. Validation lives at that boundary, once — inside the system there is typed data, no re-validation deep in call chains, and business logic in pure functions the boundary shell calls.
|
|
18
|
+
- **Don't lie to the compiler.** Casts and assertions that bypass the checker are runtime crashes waiting to happen. If the compiler can't prove a fact, prove it — validate, narrow, refine the model — or accept that the cast is a hazard you are choosing to carry. The cast buried today is the postmortem written next week.
|
|
19
|
+
- **Exhaustive matching is the compiler's job.** A match over a sum type must fail compilation when a new variant is added without a case, so the compiler tells the next author every place that needs updating.
|
|
20
|
+
- **Derive types from authoritative schemas.** When a protocol buffer, OpenAPI spec, GraphQL schema, or database migration already defines a shape, derive from it instead of hand-rolling a parallel type. Manual duplication drifts.
|
|
21
|
+
- **Strengthen a type only where partiality appears.** A runtime assertion, a null check, or a "should never happen" throw marks the spot where a type is too weak — push that check up into the type, then stop. The type system's job is to track the cases each use site must handle, not to describe the data as precisely as possible. `sum` of an empty list is 0, so it takes the plain list; `head` of an empty list has no answer, so it demands the non-empty one. Extra precision beyond totality costs reuse and ceremony and buys no safety.
|
|
22
|
+
|
|
23
|
+
## Rules (TypeScript syntax)
|
|
24
|
+
|
|
25
|
+
| Rule | Summary |
|
|
26
|
+
|------|---------|
|
|
27
|
+
| Discriminated unions | Model variants with a `kind` literal discriminant so impossible states can't be represented. No optional-field bags. |
|
|
28
|
+
| Branded types | Brand primitives with `& { readonly __brand: "X" }` so they can't be mixed up. Validate once at creation. |
|
|
29
|
+
| Constructive modeling | Build the shape so the illegal value can't be constructed: `[T, ...T[]]` for non-empty, `[T, T][]` for even length, `start` plus `duration` for a range. Not a runtime guard, not a wish for refinement types. |
|
|
30
|
+
| Simplest total type | Keep `T[]` while every operation on it stays total. Strengthen to a non-empty type only where the loose type forces a `!`, a cast, or a "should never happen" throw. |
|
|
31
|
+
| `unknown` over `any` | External data is `unknown`. `any` disables type checking everywhere it touches. |
|
|
32
|
+
| No `as` casts | Every `as` is a potential runtime crash. Cast only after validation has earned it. |
|
|
33
|
+
| Narrowing hierarchy | Discriminant switch > `in` operator > `typeof`/`instanceof` > user-defined type guard > `as`. |
|
|
34
|
+
| Type guards | Must verify the claim. A lying guard is worse than `as` — the bug hides behind a name that says it's safe. Name them `isX` or `hasX`. |
|
|
35
|
+
| Exhaustiveness | Assign to a `never`-typed local in default arms so the compiler errors when a new variant is added. |
|
|
36
|
+
| `satisfies` over `as` | Validates the value without widening literal types. |
|
|
37
|
+
| Boundary validation | Parse where data crosses in — into a named domain type, once. `Record<string, unknown>` (however spelled) stops at that parse. Inside: trust the types, no redundant re-validation, logic in pure functions the boundary shell calls. |
|
|
38
|
+
| Schema-derived types | Reach for `Pick`/`Omit`/`Parameters`/`ReturnType`/`Awaited`/`typeof` before declaring a new interface. |
|
|
39
|
+
| Object args | Pass objects, not positional arguments, so call sites are self-documenting. Skip on hot paths (per-frame render, tokenizers, parsers). |
|
|
40
|
+
|
|
41
|
+
Worked don't/do examples for every rule: `./references/patterns.md`.
|
|
42
|
+
|
|
43
|
+
## Self-Checks
|
|
44
|
+
|
|
45
|
+
- "Can I write a comment explaining when this combination of fields is valid?" If yes, the type is too loose — split it into a discriminated union.
|
|
46
|
+
- "Do two function arguments share a primitive type but mean different things?" Brand them.
|
|
47
|
+
- "Where did this `any`, this `as`, this `!` come from?" Trace it to the boundary and validate there instead.
|
|
48
|
+
- "If a new variant is added next month, will the compiler point at every place that needs a case?" If not, the match isn't exhaustive.
|
|
49
|
+
- "Is this type duplicating a shape another file or schema owns?" Derive instead.
|
|
50
|
+
- "Am I strengthening this type to keep an operation total, or just to be more precise?" If nothing would otherwise throw, keep the plain type.
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
# TypeScript patterns
|
|
2
|
+
|
|
3
|
+
Worked don't/do examples for each rule in the table in `SKILL.md`. The principles behind them are language-agnostic; the syntax here is TypeScript's.
|
|
4
|
+
|
|
5
|
+
## Branded types
|
|
6
|
+
|
|
7
|
+
Brand primitives so they can't be mixed up. Validate once at creation; downstream code trusts the type.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
type AgentId = string & { readonly __brand: "AgentId" };
|
|
11
|
+
|
|
12
|
+
function parseAgentId(input: string): AgentId {
|
|
13
|
+
if (!isUUID(input)) throw new Error(`Invalid agent id: ${input}`);
|
|
14
|
+
return input as AgentId;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function focusAgent(id: AgentId): void {
|
|
18
|
+
/* input is trusted */
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Match the `readonly __brand: 'X'` shape; don't invent a new convention.
|
|
23
|
+
|
|
24
|
+
## Discriminated unions
|
|
25
|
+
|
|
26
|
+
If a bug forces the question "wait, can this combination actually happen?", the type is too loose. Model variants with a literal discriminant: every variant shares the field name and each variant's value is unique, so impossible combos can't be represented.
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
// Don't. Boolean + optionals lets contradictory states exist.
|
|
30
|
+
type DiffState = { loading: boolean; diff?: GitDiff; error?: string };
|
|
31
|
+
|
|
32
|
+
// Do. Only valid states exist.
|
|
33
|
+
type DiffState =
|
|
34
|
+
| { kind: "loading" }
|
|
35
|
+
| { kind: "ready"; diff: GitDiff }
|
|
36
|
+
| { kind: "error"; error: string };
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Pick one discriminant name (`kind`, `type`, `tag`) per codebase and stick to it.
|
|
40
|
+
|
|
41
|
+
## Constructive modeling
|
|
42
|
+
|
|
43
|
+
Build the type from parts that are all legal instead of restricting a loose type with runtime checks. Adding is easier than subtracting.
|
|
44
|
+
|
|
45
|
+
Non-empty, via a variadic tuple:
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
type NonEmpty<T> = [T, ...T[]];
|
|
49
|
+
|
|
50
|
+
// Don't: T[] plus a length check every caller must repeat
|
|
51
|
+
function pickWinner(entries: string[]): string {
|
|
52
|
+
if (entries.length === 0) throw new Error("no entries");
|
|
53
|
+
return entries[Math.floor(Math.random() * entries.length)];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Do: an empty value of the type can't exist
|
|
57
|
+
function pickWinner(entries: NonEmpty<string>): string {
|
|
58
|
+
return entries[Math.floor(Math.random() * entries.length)];
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Where a plain `T[]` arrives, narrow once with a guard. The fact then travels in the type:
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
const isNonEmpty = <T>(arr: T[]): arr is NonEmpty<T> => arr.length > 0;
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Even length, as pairs — TypeScript has no refinement types (no `arr.length % 2 === 0` at the type level), and you don't need one:
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
type Pairs<T> = [T, T][];
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
A time range, as start plus duration:
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
// Don't: a comment holds the invariant
|
|
78
|
+
type TimeRange = { start: Date; end: Date }; // start <= end
|
|
79
|
+
|
|
80
|
+
// Do: a negative range can't be written; derive end when needed
|
|
81
|
+
type TimeRange = { start: Date; durationMs: number };
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Keep `durationMs` a plain number; brand it (per Branded types) only if a raw number could plausibly be passed where a duration is expected, not by reflex. A `Pairs<T>` is an even-length list under the interpretation you give it, the same way `{ start, durationMs }` is a range. Pick the representation that makes the bad state unconstructable, then expose the reading you need on top (`pairs.flat()`, a `rangeEnd()` helper).
|
|
85
|
+
|
|
86
|
+
## Simplest total type
|
|
87
|
+
|
|
88
|
+
Don't strengthen everything. Keep `T[]` while every operation on it is total:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
const sum = (xs: number[]) => xs.reduce((a, b) => a + b, 0); // [] is 0, fine
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Strengthen when the loose type forces a lie at a use site. The tells are `!`, `arr[0] as T`, and a "should never happen" throw:
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
// Don't: partiality smuggled past the compiler
|
|
98
|
+
function newestSession(sessions: Session[]): Session {
|
|
99
|
+
return sessions.at(0)!;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Do: strengthen the input; the assertion disappears
|
|
103
|
+
function newestSession(sessions: NonEmpty<Session>): Session {
|
|
104
|
+
return sessions[0];
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Weakening the result to `Session | undefined` is the other total signature. Either way the empty case lands at the call site — the one place that knows what empty means.
|
|
109
|
+
|
|
110
|
+
## `unknown` over `any`
|
|
111
|
+
|
|
112
|
+
`any` disables type checking for everything it touches. External data is always `unknown`; narrow before use.
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
// Don't
|
|
116
|
+
function handle(input: any) {
|
|
117
|
+
return input.foo.bar;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Do
|
|
121
|
+
function handle(input: unknown) {
|
|
122
|
+
if (typeof input === "object" && input !== null && "foo" in input) {
|
|
123
|
+
// narrowed; the compiler verifies the access
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
External sources include RPC payloads, `JSON.parse`, IPC, file contents, environment variables, and database results.
|
|
129
|
+
|
|
130
|
+
## No `as` casts
|
|
131
|
+
|
|
132
|
+
Every `as` is a potential runtime crash. Cast only after validation has verified the claim — and the validation itself narrows without casting, or it proves nothing:
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
// Don't
|
|
136
|
+
const user = data as User;
|
|
137
|
+
|
|
138
|
+
// Do. Earn the cast at the boundary; the checks narrow via typeof and `in`.
|
|
139
|
+
function parseUser(data: unknown): User {
|
|
140
|
+
if (typeof data !== "object" || data === null) {
|
|
141
|
+
throw new Error("expected object");
|
|
142
|
+
}
|
|
143
|
+
if (!("id" in data) || typeof data.id !== "string") {
|
|
144
|
+
throw new Error("expected string id");
|
|
145
|
+
}
|
|
146
|
+
// ... validate the remaining fields the same way
|
|
147
|
+
return data as User; // earned: every field was checked above
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
When refactoring an `as` out of existing code, identify why the compiler can't infer:
|
|
152
|
+
|
|
153
|
+
- Missing discriminant: add one, switch to a discriminated union.
|
|
154
|
+
- Overly wide source type (e.g. `Record<string, unknown>`): narrow it.
|
|
155
|
+
- Untyped boundary: add a parse function or schema.
|
|
156
|
+
- Genuinely inexpressible: use a branded type or `satisfies`.
|
|
157
|
+
|
|
158
|
+
## Narrowing hierarchy
|
|
159
|
+
|
|
160
|
+
From best to last-resort:
|
|
161
|
+
|
|
162
|
+
1. **Discriminated union switch / if.** The compiler narrows automatically.
|
|
163
|
+
2. **`in` operator.** `"key" in obj` narrows to the variants containing that key.
|
|
164
|
+
3. **`typeof` / `instanceof`.** For primitives and class instances.
|
|
165
|
+
4. **User-defined type guard.** When the above aren't enough.
|
|
166
|
+
5. **`as` cast.** Only after validation.
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
function area(s: Shape): number {
|
|
170
|
+
if ("radius" in s) return Math.PI * s.radius ** 2; // narrowed to circle
|
|
171
|
+
return s.width * s.height; // narrowed to rect
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
## Type guards
|
|
176
|
+
|
|
177
|
+
A guard must actually verify the claim. A lying guard is worse than `as` because the bug hides behind a name that says it's safe.
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
function isCircle(s: Shape): s is Shape & { kind: "circle" } {
|
|
181
|
+
return s.kind === "circle";
|
|
182
|
+
}
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
Prefer discriminant narrowing when possible — a guard adds a layer the reader has to follow.
|
|
186
|
+
|
|
187
|
+
## Exhaustiveness
|
|
188
|
+
|
|
189
|
+
In default arms, assign the discriminant to a `never`-typed local. The compiler errors if a new variant is added without handling.
|
|
190
|
+
|
|
191
|
+
```ts
|
|
192
|
+
// Value-returning switch
|
|
193
|
+
function area(s: Shape): number {
|
|
194
|
+
switch (s.kind) {
|
|
195
|
+
case "circle":
|
|
196
|
+
return Math.PI * s.radius ** 2;
|
|
197
|
+
case "rect":
|
|
198
|
+
return s.width * s.height;
|
|
199
|
+
default: {
|
|
200
|
+
const _exhaustive: never = s;
|
|
201
|
+
return _exhaustive;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// Void switch
|
|
207
|
+
function handle(s: Shape): void {
|
|
208
|
+
switch (s.kind) {
|
|
209
|
+
case "circle":
|
|
210
|
+
drawCircle(s);
|
|
211
|
+
break;
|
|
212
|
+
case "rect":
|
|
213
|
+
drawRect(s);
|
|
214
|
+
break;
|
|
215
|
+
default: {
|
|
216
|
+
const _exhaustive: never = s;
|
|
217
|
+
void _exhaustive;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
Return-style in value-returning switches; void-style in statement switches.
|
|
224
|
+
|
|
225
|
+
## `satisfies` over `as`
|
|
226
|
+
|
|
227
|
+
`satisfies` validates without widening literal types.
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
// Don't. Widens, loses literal types.
|
|
231
|
+
const config = { theme: "dark", cols: 3 } as Config;
|
|
232
|
+
|
|
233
|
+
// Do. Validates AND preserves literal types.
|
|
234
|
+
const config = { theme: "dark", cols: 3 } satisfies Config;
|
|
235
|
+
// config.theme is "dark" (literal), not string
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
## Boundary validation
|
|
239
|
+
|
|
240
|
+
Validate once where data crosses in; trust types inside. Scattered validation is noisy, redundant, and gives a false sense of safety.
|
|
241
|
+
|
|
242
|
+
- **At boundaries** (CLI args, config files, env vars, network payloads, database rows): parse into a named domain type, return errors, handle defensively.
|
|
243
|
+
- **Inside the system:** typed data, error propagation, no re-validation. No redundant null checks deep in call chains when the boundary already validated.
|
|
244
|
+
- **Across the boundary:** expose domain concepts, not the wire format — don't re-export transport, storage, or framework types through the public surface.
|
|
245
|
+
- **Wire formats** (proto, JSON-RPC): parse with unknown fields ignored so forward-compatible changes don't break old clients. **Persisted JSON:** versioned blob with a try/catch around the parse.
|
|
246
|
+
- Keep business logic in pure functions the boundary shell calls: parse functions as pure transforms from raw bytes to typed state, so the logic tests without the framework.
|
|
247
|
+
|
|
248
|
+
## Schema-derived types
|
|
249
|
+
|
|
250
|
+
When a `.proto`, OpenAPI spec, GraphQL schema, or database migration already defines a shape, derive from the generated types instead of duplicating them.
|
|
251
|
+
|
|
252
|
+
```ts
|
|
253
|
+
// Don't. Duplicate shape, drifts when the schema changes.
|
|
254
|
+
type CheckSummary = {
|
|
255
|
+
totalCount: number;
|
|
256
|
+
checks: { name: string; status: string }[];
|
|
257
|
+
};
|
|
258
|
+
function renderChecks(s: CheckSummary) {
|
|
259
|
+
/* ... */
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// Do. Derive from the generated schema type.
|
|
263
|
+
import type { ChecksMessage } from "<generated module>";
|
|
264
|
+
function renderChecks(s: Pick<ChecksMessage, "totalCount" | "checks">) {
|
|
265
|
+
/* ... */
|
|
266
|
+
}
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Reach for `Pick`, `Omit`, `Parameters`, `ReturnType`, `Awaited`, `typeof` before writing a new interface.
|
|
270
|
+
|
|
271
|
+
## Object args
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
// Don't. Swap two args, still compiles.
|
|
275
|
+
openFile(uri, {
|
|
276
|
+
startLineNumber: 10,
|
|
277
|
+
startColumn: 1,
|
|
278
|
+
endLineNumber: 10,
|
|
279
|
+
endColumn: 1,
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
// Do. Order-independent, self-documenting.
|
|
283
|
+
openFile({
|
|
284
|
+
uri,
|
|
285
|
+
selection: {
|
|
286
|
+
startLineNumber: 10,
|
|
287
|
+
startColumn: 1,
|
|
288
|
+
endLineNumber: 10,
|
|
289
|
+
endColumn: 1,
|
|
290
|
+
},
|
|
291
|
+
});
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
Skip on hot paths: per-frame render, tokenizers, parsers, anything in a tight loop where the allocation cost matters.
|