@wrongstack/core 0.6.3 → 0.6.5

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 (63) hide show
  1. package/dist/{agent-bridge-eb7qnNrd.d.ts → agent-bridge-BBXK_ppx.d.ts} +1 -1
  2. package/dist/agent-subagent-runner-DsSm9lKN.d.ts +174 -0
  3. package/dist/{compactor-RIPuTtWK.d.ts → compactor-C8NhpSt5.d.ts} +1 -1
  4. package/dist/{config-BGGuP_Ar.d.ts → config-DfC6g6KV.d.ts} +1 -1
  5. package/dist/{context-CDRyrkKQ.d.ts → context-DN5v-uQX.d.ts} +11 -0
  6. package/dist/coordination/index.d.ts +10 -9
  7. package/dist/coordination/index.js +113 -20
  8. package/dist/coordination/index.js.map +1 -1
  9. package/dist/defaults/index.d.ts +21 -20
  10. package/dist/defaults/index.js +1329 -925
  11. package/dist/defaults/index.js.map +1 -1
  12. package/dist/{events-BHuIHekD.d.ts → events-CJqwQl8G.d.ts} +17 -1
  13. package/dist/execution/index.d.ts +82 -13
  14. package/dist/execution/index.js +1366 -74
  15. package/dist/execution/index.js.map +1 -1
  16. package/dist/extension/index.d.ts +6 -6
  17. package/dist/{goal-store-DVCfj7Ff.d.ts → goal-store-_Er467ya.d.ts} +2 -2
  18. package/dist/{index-CPcDqvZh.d.ts → index-CXnWsGBp.d.ts} +11 -175
  19. package/dist/{index-BOn9NK7D.d.ts → index-DcnXDPdY.d.ts} +6 -6
  20. package/dist/index.d.ts +28 -27
  21. package/dist/index.js +1068 -664
  22. package/dist/index.js.map +1 -1
  23. package/dist/infrastructure/index.d.ts +6 -6
  24. package/dist/kernel/index.d.ts +9 -9
  25. package/dist/kernel/index.js.map +1 -1
  26. package/dist/{mcp-servers-DBdh3cee.d.ts → mcp-servers-CevFHHM1.d.ts} +3 -3
  27. package/dist/models/index.d.ts +2 -2
  28. package/dist/models/index.js +5 -16
  29. package/dist/models/index.js.map +1 -1
  30. package/dist/{multi-agent-CxSb-9dQ.d.ts → multi-agent-D5IbASk_.d.ts} +16 -4
  31. package/dist/observability/index.d.ts +2 -2
  32. package/dist/{path-resolver-CMGNadvq.d.ts → path-resolver-CBx_q1HA.d.ts} +2 -2
  33. package/dist/{plan-templates-BJflQY2i.d.ts → plan-templates-BEOllUJV.d.ts} +5 -4
  34. package/dist/{provider-runner-BFgNXpaP.d.ts → provider-runner-Byh5TcJs.d.ts} +3 -3
  35. package/dist/{retry-policy-LKS8MHsB.d.ts → retry-policy-BZSIMxrJ.d.ts} +1 -1
  36. package/dist/sdd/index.d.ts +3 -3
  37. package/dist/{secret-scrubber-CfMdAJ_l.d.ts → secret-scrubber-CT7wefiO.d.ts} +1 -1
  38. package/dist/{secret-scrubber-BzQR5BiL.d.ts → secret-scrubber-I0QHY_ob.d.ts} +1 -1
  39. package/dist/security/index.d.ts +3 -3
  40. package/dist/{selector-C7HqnZJU.d.ts → selector-DDb_mq9X.d.ts} +1 -1
  41. package/dist/{session-reader-CzfRA6Vk.d.ts → session-reader-B9nVkziM.d.ts} +1 -1
  42. package/dist/storage/index.d.ts +6 -6
  43. package/dist/storage/index.js +27 -2
  44. package/dist/storage/index.js.map +1 -1
  45. package/dist/{system-prompt-Dl2QY1_B.d.ts → system-prompt-gL06H9P4.d.ts} +1 -1
  46. package/dist/{tool-executor-FoxBjULX.d.ts → tool-executor-BF7QfYVE.d.ts} +4 -4
  47. package/dist/types/index.d.ts +15 -15
  48. package/dist/types/index.js +5 -16
  49. package/dist/types/index.js.map +1 -1
  50. package/dist/utils/index.d.ts +1 -1
  51. package/package.json +1 -1
  52. package/skills/audit-log/SKILL.md +57 -28
  53. package/skills/bug-hunter/SKILL.md +85 -61
  54. package/skills/git-flow/SKILL.md +73 -18
  55. package/skills/multi-agent/SKILL.md +69 -40
  56. package/skills/node-modern/SKILL.md +111 -19
  57. package/skills/prompt-engineering/SKILL.md +97 -16
  58. package/skills/react-modern/SKILL.md +104 -18
  59. package/skills/refactor-planner/SKILL.md +73 -43
  60. package/skills/sdd/SKILL.md +54 -112
  61. package/skills/security-scanner/SKILL.md +95 -93
  62. package/skills/skill-creator/SKILL.md +58 -25
  63. package/skills/typescript-strict/SKILL.md +107 -15
@@ -1,4 +1,4 @@
1
- import { a5 as TodoItem, M as Message, J as JSONSchema } from '../context-CDRyrkKQ.js';
1
+ import { a5 as TodoItem, M as Message, J as JSONSchema } from '../context-DN5v-uQX.js';
2
2
  export { a as WstackPathOptions, W as WstackPaths, p as projectHash, r as resolveWstackPaths } from '../wstack-paths-86YPFktR.js';
3
3
 
4
4
  interface AtomicWriteOptions {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wrongstack/core",
3
- "version": "0.6.3",
3
+ "version": "0.6.5",
4
4
  "license": "MIT",
5
5
  "description": "WrongStack core: kernel, types, defaults, and shared utilities for the WrongStack CLI agent.",
6
6
  "repository": {
@@ -1,31 +1,46 @@
1
1
  ---
2
2
  name: audit-log
3
3
  description: |
4
- System-wide audit log analysis. Covers log parsing, anomaly detection,
5
- pattern recognition across sessions, and structured reporting.
6
- Use for post-mortems, trend analysis, and operational insights.
7
- version: 1.0.0
4
+ Use this skill when analyzing WrongStack session logs, event streams, or
5
+ system traces to surface patterns, anomalies, or operational insights.
6
+ Triggers: user says "audit", "session analysis", "log analysis", "usage patterns".
7
+ version: 1.1.0
8
8
  ---
9
9
 
10
- # Audit Log Agent
10
+ # Audit Log Agent — WrongStack
11
11
 
12
- Analyzes session logs, event streams, and system traces to surface patterns,
13
- anomalies, and actionable insights.
12
+ Analyzes session logs, event streams, and system traces to surface patterns, anomalies, and actionable insights.
14
13
 
15
- ## Capabilities
14
+ ## Workflow
16
15
 
17
- - Parse structured JSONL session logs
18
- - Detect repeated failure patterns across runs
19
- - Identify tool usage anomalies (over-use, misuse, failures)
20
- - Track token consumption trends per agent/session
21
- - Generate markdown audit reports
16
+ ```
17
+ 1. Collect: Read session logs from path or sessionRoot
18
+ 2. Parse: Extract events: tool calls, iterations, errors, usage
19
+ 3. Analyze: Group by category, detect anomalies
20
+ 4. Report: Structured markdown summary
21
+ ```
22
22
 
23
- ## Workflow
23
+ ## What to look for
24
+
25
+ ### Tool usage patterns
26
+ - Over-used tools (100+ calls to the same tool = possibly a loop)
27
+ - Tools that consistently fail (repeated failures = bug or misconfiguration)
28
+ - Unusual tool sequences (e.g., 50 writes in a row with no reads)
24
29
 
25
- 1. **Collect** — Read session logs from `sessionRoot` or provided path
26
- 2. **Parse** Extract events: tool calls, iterations, errors, usage
27
- 3. **Analyze** Group by category, detect anomalies
28
- 4. **Report** Output structured markdown summary
30
+ ### Error patterns
31
+ - Same error repeating across iterations
32
+ - Error rate by type: what's most common?
33
+ - Errors clustered in specific packages or tools
34
+
35
+ ### Cost patterns
36
+ - Tokens per iteration: is it growing?
37
+ - Which provider/model combination is most expensive?
38
+ - Any unexpected cost spikes?
39
+
40
+ ### Context management
41
+ - Iterations with very high tool count (possible loop)
42
+ - Context compaction triggered frequently
43
+ - Session that keeps restarting
29
44
 
30
45
  ## Input
31
46
 
@@ -37,31 +52,45 @@ anomalies, and actionable insights.
37
52
  }
38
53
  ```
39
54
 
40
- ## Output Format
55
+ ## Output format
41
56
 
42
57
  ```
43
58
  ## Audit Report — <date>
44
59
 
45
60
  ### Summary
46
- - Total sessions: N
61
+ - Total iterations: N
47
62
  - Total tool calls: N
48
63
  - Error rate: X%
64
+ - Cost: $X.XX
49
65
 
50
- ### Top Errors
51
- 1. <error-type>: <count>x <context>
52
- 2. ...
66
+ ### Top Errors (by count)
67
+ 1. `ToolExecutionError`47x —集中在 `bash` tool, command timeout
68
+ 2. `PermissionDenied` — 12x — `exec` tool, no trust file entry
53
69
 
54
70
  ### Tool Usage
55
71
  | Tool | Calls | Failures | Avg Duration |
56
72
  |------|-------|----------|--------------|
57
- | read | 142 | 3 | 45ms |
73
+ | read | 142 | 3 | 45ms |
74
+ | bash | 89 | 12 | 2300ms |
58
75
 
59
76
  ### Anomalies
60
- - `<pattern-detected>`<severity: low/medium/high>
77
+ - High bash failure rate (13.5%) likely command timeout
78
+ - 3 iterations with >50 tool calls — possible loop, review iteration 14
79
+
80
+ ### Cost Trend
81
+ - Iteration 1-10: avg $0.04/iteration
82
+ - Iteration 11-20: avg $0.11/iteration (context growth)
61
83
  ```
62
84
 
63
85
  ## Anti-patterns
64
86
 
65
- - Don't summarize what you didn't parse — be precise
66
- - Don't mix session paths — analyze one at a time or aggregate clearly
67
- - Don't skip error context — the user's log is the source of truth
87
+ - **Don't summarize what you didn't parse** — be precise, cite the data
88
+ - **Don't mix sessions** — analyze one at a time or aggregate clearly
89
+ - **Don't skip error context** — the raw error message is the source of truth
90
+ - **Don't ignore cost trends** — growing costs indicate context bloat
91
+ - **Don't ignore repeated failures** — same tool failing 5x = real issue
92
+
93
+ ## Skills in scope
94
+
95
+ - `bug-hunter` — for turning audit findings into concrete bugs to fix
96
+ - `refactor-planner` — for addressing systemic issues found in logs
@@ -1,87 +1,111 @@
1
1
  ---
2
2
  name: bug-hunter
3
3
  description: |
4
- Systematic bug and code smell detection. Covers static analysis patterns,
5
- anti-pattern recognition, error-prone construct detection, and severity ranking.
6
- Use before refactoring or as a standalone health check.
7
- version: 1.0.0
4
+ Use this skill when scanning source code for bugs, anti-patterns, code smells,
5
+ or quality issues in a WrongStack project. Triggers: user says "bug", "bug hunt",
6
+ "scan for issues", "find problems", "anti-pattern", "code smell", "static analysis".
7
+ version: 1.1.0
8
8
  ---
9
9
 
10
- # Bug Hunter Agent
10
+ # Bug Hunter — WrongStack
11
11
 
12
- Scans source code for bugs, anti-patterns, and code smells using pattern matching
13
- and heuristics. Outputs a prioritized hit list with file:line references.
12
+ Scans code for bugs and code smells. Outputs a prioritized hit list with file:line references.
14
13
 
15
- ## Capabilities
14
+ ## Workflow
16
15
 
17
- - Detect common bug patterns (uncaught errors, resource leaks, race conditions)
18
- - Identify anti-patterns (callback hell, God objects, circular deps)
19
- - Find TypeScript-specific issues (unsafe any, missing null checks)
20
- - Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)
21
- - Rank findings by severity: critical > high > medium > low
16
+ ```
17
+ 1. Scope: Accept file/dir globs or explicit paths
18
+ 2. Scan: grep/read across target files
19
+ 3. Classify: Categorize by type and severity
20
+ 4. Rank: Sort: critical > high > medium > low
21
+ 5. Report: Markdown with fix suggestions
22
+ ```
22
23
 
23
- ## Workflow
24
+ ## Severity levels
25
+
26
+ | Level | Meaning | Action |
27
+ |-------|---------|--------|
28
+ | **Critical** | Security breach, data loss, crash | Fix immediately |
29
+ | **High** | Logic bug, race condition, memory leak | Fix before release |
30
+ | **Medium** | Error handling gap, type unsafety | Fix soon |
31
+ | **Low** | Style, minor code smell | Consider fixing |
32
+
33
+ ## Bug patterns to find
34
+
35
+ ```
36
+ | Pattern | Regex hint | Severity |
37
+ |---------|------------|----------|
38
+ | Uncaught promise | /\.then\([^]*\.catch/ but missing catch | high |
39
+ | Event listener leak | `on(` without `off/removeListener` | high |
40
+ | Hardcoded secret | `[A-Za-z0-9/+=]{40}` in config or code | critical |
41
+ | unsafe any | `: any\b` or `as any` | medium |
42
+ | innerHTML assignment | `innerHTML\s*=` | high |
43
+ | Missing await | `await` not used on async call | high |
44
+ | Unhandled rejection | `process.on('unhandledRejection'` | medium |
45
+ | SQL concatenation | `"SELECT * FROM " + table` | critical |
46
+ | Shell injection | `exec(\`cmd ${input}\`)` | critical |
47
+ ```
48
+
49
+ ## Real examples
50
+
51
+ ```typescript
52
+ // ❌ CRITICAL — hardcoded API key
53
+ const apiKey = "sk-abc123xyz789...";
54
+
55
+ // ❌ HIGH — innerHTML XSS
56
+ element.innerHTML = userInput;
24
57
 
25
- 1. **Scope**Accept file/dir globs or explicit paths
26
- 2. **Scan** — Run grep/read across target files
27
- 3. **Classify** — Categorize findings by type and severity
28
- 4. **Rank**Sort by severity, then frequency
29
- 5. **Report** — Markdown output with fix suggestions
30
-
31
- ## Input
32
-
33
- ```json
34
- {
35
- "task": "scan | hunt | check",
36
- "paths": ["src/**/*.ts", "lib/*.js"],
37
- "focus": "bugs | patterns | security | all",
38
- "severityThreshold": "medium"
39
- }
58
+ // HIGH unhandled promise (then without catch)
59
+ fetchData().then(processData);
60
+
61
+ // HIGH shell injection
62
+ exec(`echo ${userInput}`);
63
+
64
+ // ❌ HIGH — unsafe any
65
+ const data: any = response.json();
66
+
67
+ // ✅ FIXED — use textContent
68
+ element.textContent = userInput;
69
+
70
+ // FIXED parameterized query
71
+ db.query("SELECT * FROM users WHERE id = $1", [userId]);
40
72
  ```
41
73
 
42
- ## Output Format
74
+ ## Anti-patterns
75
+
76
+ - **Don't scan `node_modules`** — waste of time, false positives
77
+ - **Don't report without file:line** — useless for fixing
78
+ - **Don't ignore false positive rate** — if >30% of findings are noise, note it
79
+ - **Don't report style issues as bugs** — those are lint findings
80
+ - **Don't flag deprecated without severity** — some deprecations are fine
81
+
82
+ ## Output format
43
83
 
44
84
  ```
45
85
  ## Bug Hunt Report — <scope>
46
86
 
47
87
  ### Critical (must fix)
48
- 1. **[RACE]** `src/auth.ts:47` — setTimeout without clearTimeout in loop
49
- 2. **[SECRET]** `lib/config.ts:12` hardcoded API key detected
88
+ 1. [SHELL-INJ] `tools/shell.ts:42` — template literal in exec()
89
+ `exec(\`echo ${userInput}\`)` use execFile with args array
90
+ 2. [SECRET] `lib/config.ts:8` — API key hardcoded
50
91
 
51
- ### High (should fix)
52
- 3. **[MEMORY]** `tools/pool.ts:89` — event listener never removed
53
- 4. **[TYPE]** `core/agent.ts:103` — unsafe `any` cast loses type safety
92
+ ### High
93
+ 3. [MEMORY] `tools/pool.ts:89` — event listener never removed
94
+ 4. [TYPE] `core/agent.ts:103` — unsafe `any` cast
54
95
 
55
- ### Medium
56
- ...
57
-
58
- ### Low (consider)
59
- ...
60
-
61
- ## Summary
96
+ ### Summary
62
97
  | Severity | Count |
63
98
  |----------|-------|
64
- | Critical | 2 |
65
- | High | 4 |
66
- | Medium | 7 |
67
- | Low | 3 |
99
+ | Critical | 2 |
100
+ | High | 4 |
101
+ | Medium | 7 |
102
+ | Low | 3 |
68
103
 
69
104
  Total: 16 findings in 12 files
70
105
  ```
71
106
 
72
- ## Bug Pattern Reference
73
-
74
- | Pattern | Regex Hint | Severity |
75
- |---------|------------|----------|
76
- | Uncaught promise | `\.then\(` without `catch` | high |
77
- | Event leak | `on\(` without `off`/`removeListener` | high |
78
- | Hardcoded secret | `[a-zA-Z0-9/_-]{20,}` in config | critical |
79
- | unsafe any | `: any\b` or `<any>` | medium |
80
- | innerHTML | `innerHTML\s*=` | high |
81
- | TODO without FIXME | `TODO(?!.*FIXME)` | low |
82
-
83
- ## Anti-patterns
107
+ ## Skills in scope
84
108
 
85
- - Don't scan node_modules waste of time and false positives
86
- - Don't report without file:line useless for fixing
87
- - Don't ignore false positive rates if >30% of findings are noise, lower confidence
109
+ - `security-scanner`for hardcoded secrets and injection vectors
110
+ - `refactor-planner` for fixing findings across multiple files
111
+ - `typescript-strict`for type-safety related findings
@@ -1,32 +1,87 @@
1
1
  ---
2
2
  name: git-flow
3
3
  description: |
4
- Use this skill when proposing, creating, or reviewing git commits, branches,
5
- and PRs. Covers commit message style, branch hygiene, and safe history operations.
6
- version: 1.0.0
4
+ Use this skill when proposing, reviewing, or troubleshooting git commits,
5
+ branches, pull requests, or merge strategies in a WrongStack project session.
6
+ Triggers: user mentions "commit", "branch", "PR", "merge", "rebase", "stash", "diff".
7
+ version: 1.1.0
7
8
  ---
8
9
 
9
- # Git workflow
10
+ # Git Workflow — WrongStack
10
11
 
11
- ## Commits
12
+ ## Commit messages
12
13
 
13
- - Subject line: imperative mood, ≤ 72 chars, no trailing period.
14
- - Body: explain *why*, not *what* (the diff shows what).
15
- - Group by intent, not by file.
14
+ Format: `type: short description`
16
15
 
17
- ## Branches
16
+ Types: `fix`, `feat`, `docs`, `refactor`, `test`, `chore`, `perf`, `ci`
18
17
 
19
- - One topic per branch. Rebase before merging when safe.
20
- - Delete branches after merge.
18
+ Rules:
19
+ - Subject 72 chars, imperative mood, no trailing period
20
+ - Body: explain **why**, not what (the diff shows what)
21
+ - Reference issues: `Fix #123` or `Closes GH-456`
22
+
23
+ ```
24
+ # Good
25
+ fix: correct race condition in token refresh
26
+ Retry logic now respects backoff multiplier. Without this,
27
+ repeated failures would hammer the provider instead of backing off.
28
+
29
+ # Bad — what, not why
30
+ fix: fixed bug
31
+ ```
32
+
33
+ ## Branch strategy
34
+
35
+ - One topic per branch: `feat/login`, `fix/session-leak`, `refactor/auth-layer`
36
+ - Delete branches after merge (unless shared/releasing)
37
+ - Rebase onto `main` before PR when safe (cleaner history)
38
+ - Never `git push --force` to shared branches — use `--force-with-lease`
21
39
 
22
40
  ## Safety rules
23
41
 
24
- - Never `git push --force` to shared branches (use `--force-with-lease` for your own).
25
- - Never `git reset --hard` without inspecting `git status` first.
26
- - Don't amend already-pushed commits to shared branches.
42
+ | Action | Safe? | Rule |
43
+ |--------|-------|------|
44
+ | `push --force` to own branch | ✅ | `--force-with-lease` preferred |
45
+ | `push --force` to shared branch | ❌ | Always use PR + merge |
46
+ | `reset --hard` with uncommitted work | ❌ | `git stash` first |
47
+ | `amend` a pushed commit | ❌ | It rewrites shared history |
48
+ | `merge` vs `rebase` | Context | Rebase for feature branches; merge for PRs |
49
+
50
+ ## Pull requests
51
+
52
+ - Title: same format as commit messages
53
+ - Body: link to issue, describe tradeoffs, list changed files
54
+ - Keep PRs small: one reviewable concern per PR
55
+ - Self-review diff before requesting review
56
+
57
+ ## Merge strategies
58
+
59
+ ```
60
+ # Fast-forward merge (clean topic branch)
61
+ git checkout feature && git merge --ff-only main
62
+
63
+ # Merge commit (preserves branch history)
64
+ git merge --no-ff feature
65
+
66
+ # Rebase and fast-forward (clean linear history)
67
+ git rebase main && git merge --ff-only feature
68
+ ```
69
+
70
+ ## WrongStack-specific notes
71
+
72
+ - WrongStack uses `pnpm` workspaces — `git status` may show many modified files across packages
73
+ - Use `pnpm -r` for recursive commands across packages
74
+ - Check `pnpm-lock.yaml` changes — don't merge lockfile updates with unrelated changes
75
+ - When in doubt: small, frequent commits with clear messages beat large, vague ones
76
+
77
+ ## Anti-patterns
78
+
79
+ - **Mega-commits**: "Update stuff" across 15 packages — split it
80
+ - **WIP commits left in main**: Use `git stash` or a feature branch, not a commit message like "WIP"
81
+ - **Committing lockfile with logic changes**: Keep them separate for easier rollbacks
82
+ - **Branching from branches**: Always branch from `main` or a stable release tag
27
83
 
28
- ## PRs
84
+ ## Skills in scope
29
85
 
30
- - Subject summarizes the change, body links the issue and lists tradeoffs.
31
- - Keep PRs small: one reviewable change per PR.
32
- - Self-review the diff before requesting review.
86
+ - `refactor-planner` when a refactor involves multiple git-managed changes
87
+ - `multi-agent` for fleet-wide version audits across packages
@@ -1,62 +1,91 @@
1
1
  ---
2
2
  name: multi-agent
3
3
  description: |
4
- Multi-agent orchestration workflow. Covers leader/worker roles,
5
- task delegation, done conditions, and result aggregation.
6
- Use for parallel task execution.
7
- version: 1.0.0
4
+ Use this skill when a task would benefit from parallel execution across
5
+ multiple AI agents, or when orchestrating leader/worker patterns in WrongStack.
6
+ Triggers: user says "fan out", "parallel", "delegate", "subagent", "fleet", "coordinator".
7
+ version: 1.1.0
8
8
  ---
9
9
 
10
- # Multi-Agent Coordination
10
+ # Multi-Agent Coordination — WrongStack
11
11
 
12
- Guide for orchestrating multiple agents to work together on complex tasks.
12
+ ## When to fan out
13
13
 
14
- ## When to use multiple agents
14
+ Good fits:
15
+ - "Audit these 50 files for X" — one subagent per chunk of 5-10 files
16
+ - "Run tests in all 12 packages" — parallel `pnpm test` across packages
17
+ - "Refactor 3 independent modules" — separate agents for each
18
+ - "Review this PR + check the tests + check docs" — three parallel workers
15
19
 
16
- - Large refactoring across multiple modules
17
- - Parallel feature development
18
- - Code review + implementation simultaneously
19
- - Any task where separation of concerns speeds things up
20
+ Avoid:
21
+ - Single atomic task under 5 tool calls — overhead exceeds benefit
22
+ - Tasks requiring shared state — subagents have isolated contexts
23
+ - Long sequential dependencies chain within one agent, don't fan out
20
24
 
21
- ## Agent roles
25
+ ## Roles
22
26
 
23
- Define clear roles to avoid overlap:
27
+ | Role | Responsibility | Tools |
28
+ |------|---------------|-------|
29
+ | **Leader** | Coordinates, delegates, synthesizes | `delegate`, `plan`, `read` |
30
+ | **Worker** | Executes a narrow subtask | Any needed tools |
31
+ | **Reviewer** | Validates worker output, approves/rejects | `grep`, `test`, `read` |
32
+ | **Architect** | Makes design decisions when workers hit ambiguity | `read`, `glob`, `grep` |
24
33
 
25
- - **Leader** — Coordinates, delegates, synthesizes
26
- - **Worker** — Executes specific tasks
27
- - **Reviewer** — Reviews and approves
28
- - **Architect** — Makes design decisions
29
- - **Debugger** — Root cause analysis
34
+ ## Delegation patterns
30
35
 
31
- ## Task delegation principles
36
+ ### One-shot fan-out (all workers in one turn)
32
37
 
33
- 1. **Atomic tasks** — Each task should be independently executable
34
- 2. **Clear boundaries** — Tasks should not overlap
35
- 3. **Dependency awareness** Respect task dependencies
36
- 4. **Result aggregation** Leader synthesizes worker results
38
+ ```
39
+ batch_tool_use([
40
+ { tool: "delegate", input: { task: "Audit auth/session.ts for null-deref bugs", role: "bug-hunter" }},
41
+ { tool: "delegate", input: { task: "Audit auth/token.ts for null-deref bugs", role: "bug-hunter" }},
42
+ { tool: "delegate", input: { task: "Audit auth/refresh.ts for null-deref bugs", role: "bug-hunter" }},
43
+ ])
44
+ ```
37
45
 
38
- ## Communication
46
+ ### Fleet pattern (stateful, multiple turns)
47
+
48
+ ```
49
+ delegate → spawn N subagents → assign_task per subagent → await_tasks
50
+ ```
39
51
 
40
- Agents communicate via structured messages:
52
+ Use this when the task has dependencies — subagent 2 waits for subagent 1's artifact.
53
+
54
+ ## Communication
41
55
 
42
- - `task` Assign work
43
- - `result` — Return output
44
- - `progress` — Status updates
45
- - `error` — Failures
46
- - `stop` — Cancellation
56
+ Workers return structured results. Read `stopReason`:
57
+ - `end_turn` — clean finish, check `result`
58
+ - `budget_exhausted` — task too broad, narrow and retry
59
+ - `error` — infrastructure issue, surface it to user
60
+ - `aborted` — user cancelled, don't retry silently
47
61
 
48
- ## Done conditions
62
+ ## Result aggregation
49
63
 
50
- Choose appropriate done condition:
64
+ Leader collects and synthesizes:
51
65
 
52
- - `all_tasks_done` — Wait for all tasks
53
- - `critical_path_done` Wait for critical path
54
- - `first_completion` Stop at first success
55
- - `max_iterations` Bounded execution
66
+ ```
67
+ For each worker result:
68
+ - Extract key findings (don't just paste raw output)
69
+ - Deduplicate (multiple workers may find the same issue)
70
+ - Prioritize: critical > high > medium > low
71
+ - Present as unified report
72
+ ```
56
73
 
57
74
  ## Anti-patterns
58
75
 
59
- - Over-delegation — Don't fragment work too much
60
- - Under-delegation — Single agent bottleneck
61
- - Role confusion Workers doing leadership work
62
- - Result loss — Not aggregating agent outputs
76
+ - **Over-delegation**: Firing 50 subagents in one turn model context explodes, nothing gets done
77
+ - **Under-delegation**: One agent doing everything defeats the purpose, burns budget
78
+ - **Role mismatch**: Using `bug-hunter` to write documentation, or `refactor-planner` for security audits
79
+ - **Result loss**: Subagents return useful data but leader doesn't aggregate always check `result`
80
+ - **Silent failure**: `budget_exhausted` subagent output ignored — partial results are still results
81
+
82
+ ## Context sharing
83
+
84
+ Subagents share **nothing** — no memory, no session state, no variable scope. If subagent B needs output from subagent A, the leader must pass it explicitly as part of the task description or pass it via a shared file the leader writes before delegating.
85
+
86
+ ## Skills in scope
87
+
88
+ - `bug-hunter` — parallel file audits
89
+ - `security-scanner` — parallel security scans
90
+ - `refactor-planner` — parallel module analysis
91
+ - `audit-log` — aggregating multiple session analyses