agent-concepts 0.0.0-stage → 0.4.0

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 (139) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +771 -2
  3. package/concepts/bc-brainstorming/body/SKILL.md +43 -0
  4. package/concepts/bc-code-review/body/SKILL.md +120 -0
  5. package/concepts/bc-codebase-design/body/SKILL.md +54 -0
  6. package/concepts/bc-codebase-docs/body/SKILL.md +150 -0
  7. package/concepts/bc-council-audit-security/body/SKILL.md +72 -0
  8. package/concepts/bc-council-chain/body/SKILL.md +71 -0
  9. package/concepts/bc-council-challenge-plan/body/SKILL.md +78 -0
  10. package/concepts/bc-council-find-bugs/body/SKILL.md +70 -0
  11. package/concepts/bc-council-improve-architecture/body/SKILL.md +52 -0
  12. package/concepts/bc-council-mode/body/SKILL.md +56 -0
  13. package/concepts/bc-council-mode/body/examples/agents/README.md +11 -0
  14. package/concepts/bc-council-mode/body/examples/agents/council-change.md +14 -0
  15. package/concepts/bc-council-mode/body/examples/agents/council-compat.md +14 -0
  16. package/concepts/bc-council-mode/body/examples/agents/council-risk.md +14 -0
  17. package/concepts/bc-council-mode/body/references/pass-contracts.md +133 -0
  18. package/concepts/bc-delegate-investigation/body/SKILL.md +119 -0
  19. package/concepts/bc-delegate-investigation/body/examples/pi-settings-snippet.json +8 -0
  20. package/concepts/bc-delegate-investigation/body/pi.md +168 -0
  21. package/concepts/bc-design/body/SKILL.md +49 -0
  22. package/concepts/bc-design/body/design-framework.md +39 -0
  23. package/concepts/bc-design/body/existing-app.md +9 -0
  24. package/concepts/bc-design/body/new-work.md +22 -0
  25. package/concepts/bc-design/body/principles.md +34 -0
  26. package/concepts/bc-design/body/surfaces.md +13 -0
  27. package/concepts/bc-diagnosing-bugs/body/SKILL.md +83 -0
  28. package/concepts/bc-dispatching-parallel-agents/body/SKILL.md +63 -0
  29. package/concepts/bc-domain-modeling/body/SKILL.md +40 -0
  30. package/concepts/bc-executing-plans/body/SKILL.md +50 -0
  31. package/concepts/bc-explain-visually/body/SKILL.md +167 -0
  32. package/concepts/bc-find-bugs/body/SKILL.md +90 -0
  33. package/concepts/bc-finishing-development-branch/body/SKILL.md +73 -0
  34. package/concepts/bc-grilling/body/SKILL.md +22 -0
  35. package/concepts/bc-handoff/body/SKILL.md +104 -0
  36. package/concepts/bc-handoff/body/pickup.md +107 -0
  37. package/concepts/bc-handoff/body/writing.md +217 -0
  38. package/concepts/bc-improve-codebase-architecture/body/SKILL.md +101 -0
  39. package/concepts/bc-json-canvas/body/SKILL.md +40 -0
  40. package/concepts/bc-json-canvas/body/references/EXAMPLES.md +71 -0
  41. package/concepts/bc-json-canvas/body/references/SPEC.md +55 -0
  42. package/concepts/bc-json-canvas/body/references/VALIDATION.md +26 -0
  43. package/concepts/bc-minimal-solution-ladder/body/SKILL.md +120 -0
  44. package/concepts/bc-obsidian-bases/body/SKILL.md +59 -0
  45. package/concepts/bc-obsidian-bases/body/references/EXAMPLES.md +80 -0
  46. package/concepts/bc-obsidian-bases/body/references/FUNCTIONS.md +49 -0
  47. package/concepts/bc-obsidian-bases/body/references/SYNTAX.md +82 -0
  48. package/concepts/bc-obsidian-bases/body/references/TROUBLESHOOTING.md +41 -0
  49. package/concepts/bc-obsidian-markdown/body/SKILL.md +47 -0
  50. package/concepts/bc-obsidian-markdown/body/references/CALLOUTS.md +40 -0
  51. package/concepts/bc-obsidian-markdown/body/references/EMBEDS.md +35 -0
  52. package/concepts/bc-obsidian-markdown/body/references/PROPERTIES.md +37 -0
  53. package/concepts/bc-optimize-code/body/SKILL.md +41 -0
  54. package/concepts/bc-performance-guardrails/body/SKILL.md +53 -0
  55. package/concepts/bc-performance-guardrails/body/measuring.md +29 -0
  56. package/concepts/bc-performance-guardrails/body/targets.md +20 -0
  57. package/concepts/bc-pipeline-to-done/body/SKILL.md +205 -0
  58. package/concepts/bc-pipeline-to-done/body/agents/bc-drain-auditor.md +19 -0
  59. package/concepts/bc-pipeline-to-done/body/agents/bc-drain-reviewer.md +19 -0
  60. package/concepts/bc-pipeline-to-done/body/agents/bc-drain-worker.md +19 -0
  61. package/concepts/bc-pipeline-to-done/body/execute-issue.md +71 -0
  62. package/concepts/bc-pipeline-to-done/body/recovery-bundle.md +79 -0
  63. package/concepts/bc-pipeline-to-done/body/review-contract.md +105 -0
  64. package/concepts/bc-pipeline-to-done/body/roles.md +13 -0
  65. package/concepts/bc-pipeline-to-done/body/scripts/publish-check.py +172 -0
  66. package/concepts/bc-pipeline-to-done/body/source-issues.md +86 -0
  67. package/concepts/bc-pipeline-to-done/body/source-work-items.md +76 -0
  68. package/concepts/bc-plain-language/body/SKILL.md +134 -0
  69. package/concepts/bc-plan-slicing/body/SKILL.md +56 -0
  70. package/concepts/bc-plan-to-pipeline/body/SKILL.md +89 -0
  71. package/concepts/bc-prd-drafting/body/SKILL.md +43 -0
  72. package/concepts/bc-prompting-agents/body/SKILL.md +278 -0
  73. package/concepts/bc-prototype/body/SKILL.md +40 -0
  74. package/concepts/bc-qmd/body/SKILL.md +64 -0
  75. package/concepts/bc-research/body/SKILL.md +26 -0
  76. package/concepts/bc-security-audit/body/AI-AND-LLM.md +25 -0
  77. package/concepts/bc-security-audit/body/ATTACK-CLASSES.md +35 -0
  78. package/concepts/bc-security-audit/body/DESKTOP-MOBILE-AND-LOCAL-IPC.md +28 -0
  79. package/concepts/bc-security-audit/body/RECONNAISSANCE.md +49 -0
  80. package/concepts/bc-security-audit/body/SKILL.md +117 -0
  81. package/concepts/bc-security-audit/body/SUPPLY-CHAIN-AND-RELEASE.md +28 -0
  82. package/concepts/bc-security-audit/body/VALIDATION-AND-REPORTING.md +124 -0
  83. package/concepts/bc-security-audit/body/WEB-PROTOCOL-AND-AUTH.md +27 -0
  84. package/concepts/bc-security-audit/body/validate_audit.py +151 -0
  85. package/concepts/bc-self-improve/body/SKILL.md +104 -0
  86. package/concepts/bc-seo/body/CITATIONS.md +23 -0
  87. package/concepts/bc-seo/body/IMAGE-SEO.md +350 -0
  88. package/concepts/bc-seo/body/SKILL.md +453 -0
  89. package/concepts/bc-setup-project/body/SKILL.md +252 -0
  90. package/concepts/bc-setup-project/body/scaffold.py +2751 -0
  91. package/concepts/bc-setup-project/body/starter-items.md +157 -0
  92. package/concepts/bc-setup-project/body/work-data.md +114 -0
  93. package/concepts/bc-setup-project/body/work_index.py +626 -0
  94. package/concepts/bc-setup-project/body/work_spent.py +220 -0
  95. package/concepts/bc-subagent-driven-development/body/SKILL.md +61 -0
  96. package/concepts/bc-tdd/body/SKILL.md +184 -0
  97. package/concepts/bc-tdd/body/formal.md +77 -0
  98. package/concepts/bc-tdd/body/mocking.md +49 -0
  99. package/concepts/bc-tdd/body/properties.md +59 -0
  100. package/concepts/bc-tdd/body/refactoring.md +12 -0
  101. package/concepts/bc-tdd/body/scripts/confirm-red.py +136 -0
  102. package/concepts/bc-tdd/body/tests.md +59 -0
  103. package/concepts/bc-teach/body/GLOSSARY-FORMAT.md +36 -0
  104. package/concepts/bc-teach/body/LEARNING-RECORD-FORMAT.md +60 -0
  105. package/concepts/bc-teach/body/MISSION-FORMAT.md +34 -0
  106. package/concepts/bc-teach/body/RESOURCES-FORMAT.md +53 -0
  107. package/concepts/bc-teach/body/REVIEW-FORMAT.md +48 -0
  108. package/concepts/bc-teach/body/SKILL.md +281 -0
  109. package/concepts/bc-teach/body/WIKI-FORMAT.md +58 -0
  110. package/concepts/bc-teach/body/scripts/due.py +65 -0
  111. package/concepts/bc-to-spec/body/SKILL.md +21 -0
  112. package/concepts/bc-to-tickets/body/SKILL.md +21 -0
  113. package/concepts/bc-triage/body/AGENT-BRIEF.md +38 -0
  114. package/concepts/bc-triage/body/OUT-OF-SCOPE.md +51 -0
  115. package/concepts/bc-triage/body/SKILL.md +81 -0
  116. package/concepts/bc-unslop/body/SKILL.md +269 -0
  117. package/concepts/bc-using-git-worktrees/body/SKILL.md +91 -0
  118. package/concepts/bc-wiki-maintain/body/SKILL.md +361 -0
  119. package/concepts/bc-wiki-maintain/body/runner/README.md +552 -0
  120. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-lint.service +24 -0
  121. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-lint.timer +15 -0
  122. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-maintain-all.service +29 -0
  123. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-maintain-all.timer +16 -0
  124. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-maintain.service +28 -0
  125. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-maintain.timer +12 -0
  126. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-notify@.service +15 -0
  127. package/concepts/bc-wiki-maintain/body/runner/notify-failure.sh +92 -0
  128. package/concepts/bc-wiki-maintain/body/runner/run-lint.sh +69 -0
  129. package/concepts/bc-wiki-maintain/body/runner/run-promotion-all.sh +103 -0
  130. package/concepts/bc-wiki-maintain/body/runner/run-promotion.sh +270 -0
  131. package/concepts/bc-wiki-maintain/body/wiki_lint.py +958 -0
  132. package/concepts/bc-wiki-maintain/body/wiki_search.py +206 -0
  133. package/concepts/bc-work-sync/body/PLAN.md +46 -0
  134. package/concepts/bc-work-sync/body/SKILL.md +71 -0
  135. package/concepts/bc-writing-plans/body/SKILL.md +79 -0
  136. package/package.json +130 -4
  137. package/packages/agent-kernel-pi/AGENT-KERNEL.md +109 -0
  138. package/packages/agent-kernel-pi/index.js +8 -0
  139. package/packages/agent-kernel-pi/package.json +12 -0
@@ -0,0 +1,220 @@
1
+ #!/usr/bin/env python3
2
+ """Print a work item's `Spent:` line: estimated active time, tokens and cost from agent session files.
3
+
4
+ Usage: python3 .bc-agent/scripts/work_spent.py <item-name> [--json] [work-dir]
5
+
6
+ A session counts when it has an entry inside the item's active period (from its first committed move into
7
+ work/2-active/ to its move out, or now), its working folder is the project or one of its git worktrees, and
8
+ its file mentions the item name; a Pi child (subagent) session whose parent counts is counted too,
9
+ whatever its folder and whether or not it mentions the item. Active time sums the gaps between a session's entries in the period, each
10
+ gap capped at IDLE_CAP. Session roots default to each tool's standard folder; tests and dry runs override
11
+ them with WORK_SPENT_PI_SESSIONS, WORK_SPENT_CLAUDE_SESSIONS and WORK_SPENT_CODEX_SESSIONS.
12
+ """
13
+ from datetime import datetime, timedelta, timezone
14
+ import json
15
+ import os
16
+ from pathlib import Path
17
+ import subprocess
18
+ import sys
19
+
20
+ sys.dont_write_bytecode = True # importing work_index must leave no __pycache__ in the project
21
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
22
+ import work_index # noqa: E402
23
+
24
+ IDLE_CAP = timedelta(minutes=15)
25
+ HOME = Path.home()
26
+ TOOLS = { # tool: (label, env override, default root)
27
+ "pi": ("pi", "WORK_SPENT_PI_SESSIONS", HOME / ".pi/agent/sessions"),
28
+ "claude": ("claude-code", "WORK_SPENT_CLAUDE_SESSIONS", HOME / ".claude/projects"),
29
+ "codex": ("codex", "WORK_SPENT_CODEX_SESSIONS", Path(os.environ.get("CODEX_HOME", HOME / ".codex")) / "sessions"),
30
+ }
31
+ COSTED = {"pi"} # tools whose session files record cost
32
+ NOT_MEASURED = "Spent: not measured (no agent session for this item was found)"
33
+
34
+
35
+ def when(stamp) -> datetime | None:
36
+ try:
37
+ moment = datetime.fromisoformat(str(stamp).replace("Z", "+00:00"))
38
+ except ValueError:
39
+ return None
40
+ return moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)
41
+
42
+
43
+ def find_item(work: Path, name: str) -> Path:
44
+ folders = ["1-planned", "2-active"] + work_index.archive_folders(work, "3-done") + work_index.archive_folders(work, "4-dropped")
45
+ for folder in folders:
46
+ for entry in work_index.entries(work, folder):
47
+ if entry.removesuffix(".md") == name:
48
+ return work / folder / entry / "plan.md" if (work / folder / entry).is_dir() else work / folder / entry
49
+ raise work_index.WorkIndexError(f"no work item named {name}")
50
+
51
+
52
+ def active_period(path: Path) -> tuple[datetime, datetime]:
53
+ start = end = None
54
+ for event in work_index.item_history(path):
55
+ entered = (event["event"] == "created" and event["folder"] == "active") or event.get("to") == "active"
56
+ if start is None and entered:
57
+ start = when(event["date"])
58
+ elif start is not None and event.get("from") == "active":
59
+ end = when(event["date"])
60
+ break
61
+ if start is None:
62
+ raise work_index.WorkIndexError(f"{path.name}: no committed move into work/2-active/, so no active period")
63
+ return start, end or datetime.now(timezone.utc)
64
+
65
+
66
+ def project_folders(project: Path) -> list[Path]:
67
+ folders = [project.resolve()]
68
+ try:
69
+ result = subprocess.run(["git", "worktree", "list", "--porcelain"], cwd=project, capture_output=True, text=True)
70
+ folders += [Path(line[9:]).resolve() for line in result.stdout.splitlines() if line.startswith("worktree ")]
71
+ except OSError:
72
+ pass
73
+ return folders
74
+
75
+
76
+ def records(path: Path) -> list[dict]:
77
+ out = []
78
+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
79
+ try:
80
+ record = json.loads(line)
81
+ except ValueError:
82
+ continue
83
+ if isinstance(record, dict):
84
+ out.append(record)
85
+ return out
86
+
87
+
88
+ def read_session(tool: str, path: Path) -> tuple[str | None, list[tuple[datetime | None, int, float]]]:
89
+ """The session's working folder and its (time, tokens, cost) entries."""
90
+ cwd, entries, seen = None, [], set()
91
+ for r in records(path):
92
+ moment = when(r.get("timestamp"))
93
+ tokens, cost = 0, 0.0
94
+ message = r.get("message") if isinstance(r.get("message"), dict) else {}
95
+ payload = r.get("payload") if isinstance(r.get("payload"), dict) else {}
96
+ if tool == "pi":
97
+ cwd = cwd or (r.get("cwd") if r.get("type") == "session" else None)
98
+ usage = message.get("usage") or {}
99
+ tokens = usage.get("totalTokens") or 0
100
+ cost = (usage.get("cost") or {}).get("total") or 0.0
101
+ elif tool == "claude":
102
+ cwd = cwd or r.get("cwd")
103
+ usage = message.get("usage") or {}
104
+ if usage and message.get("id") not in seen:
105
+ seen.add(message.get("id"))
106
+ tokens = sum(usage.get(k) or 0 for k in ("input_tokens", "output_tokens",
107
+ "cache_creation_input_tokens", "cache_read_input_tokens"))
108
+ else:
109
+ cwd = cwd or (payload.get("cwd") if r.get("type") == "session_meta" else None)
110
+ if payload.get("type") == "token_count":
111
+ tokens = ((payload.get("info") or {}).get("last_token_usage") or {}).get("total_tokens") or 0
112
+ entries.append((moment, tokens, cost))
113
+ return cwd, entries
114
+
115
+
116
+ def inside(cwd: str | None, folders: list[Path]) -> bool:
117
+ if not cwd:
118
+ return False
119
+ here = Path(cwd).resolve()
120
+ return any(here == f or f in here.parents for f in folders)
121
+
122
+
123
+ def parent_file(path: Path, root: Path) -> Path | None:
124
+ """The Pi session file whose folder holds this child session (`<parent-id>.jsonl` beside `<parent-id>/`)."""
125
+ for folder in path.parents:
126
+ if folder == root or root not in folder.parents:
127
+ return None
128
+ if folder.with_suffix(".jsonl").is_file():
129
+ return folder.with_suffix(".jsonl")
130
+ return None
131
+
132
+
133
+ def spent(work: Path, name: str) -> dict:
134
+ start, end = active_period(find_item(work, name))
135
+ folders = project_folders(work.resolve().parent)
136
+ tools, sessions = {}, []
137
+
138
+ def count(tool: str, label: str, path: Path, cwd: str | None, within: list, via: str) -> None:
139
+ active = sum((min(b[0] - a[0], IDLE_CAP) for a, b in zip(within, within[1:])), timedelta())
140
+ tools[tool] += 1
141
+ sessions.append({"tool": label, "file": str(path), "cwd": cwd, "via": via,
142
+ "active_seconds": int(active.total_seconds()), "tokens": sum(e[1] for e in within),
143
+ "cost": round(sum(e[2] for e in within), 6) if tool in COSTED else None})
144
+
145
+ for tool, (label, env, default) in TOOLS.items():
146
+ root = Path(os.environ.get(env) or default)
147
+ if not root.is_dir():
148
+ tools[tool] = None
149
+ continue
150
+ tools[tool] = 0
151
+ matched, rest = set(), []
152
+ for path in sorted(root.rglob("*.jsonl")):
153
+ try:
154
+ if datetime.fromtimestamp(path.stat().st_mtime, timezone.utc) < start:
155
+ continue
156
+ mentions = name in path.read_text(encoding="utf-8", errors="replace")
157
+ except OSError:
158
+ continue
159
+ cwd, entries = read_session(tool, path)
160
+ within = sorted((e for e in entries if e[0] and start <= e[0] <= end), key=lambda e: e[0])
161
+ if not within:
162
+ continue
163
+ if mentions and inside(cwd, folders):
164
+ matched.add(path)
165
+ count(tool, label, path, cwd, within, "match")
166
+ elif tool == "pi":
167
+ rest.append((path, cwd, within))
168
+ # A Pi child session (a subagent, often in a since-removed worktree) counts when its parent counted,
169
+ # whatever its folder and even when its task names only a step of the item.
170
+ for path, cwd, within in rest:
171
+ parent = parent_file(path, root)
172
+ if parent in matched:
173
+ count(tool, label, path, cwd, within, f"child of {parent.name}")
174
+ return {"item": name, "period": {"start": start.isoformat(), "end": end.isoformat()},
175
+ "line": spent_line(tools, sessions), "sessions": sessions}
176
+
177
+
178
+ def tokens_text(n: int) -> str:
179
+ for size, unit in ((1_000_000, "M"), (1_000, "k")):
180
+ if n >= size:
181
+ return f"{n / size:.1f}".removesuffix(".0") + unit
182
+ return str(n)
183
+
184
+
185
+ def spent_line(tools: dict, sessions: list[dict]) -> str:
186
+ if not sessions:
187
+ return NOT_MEASURED
188
+ minutes = sum(s["active_seconds"] for s in sessions) // 60
189
+ active = f"{minutes // 60}h {minutes % 60}m" if minutes >= 60 else f"{minutes}m"
190
+ costs = [s["cost"] for s in sessions if s["cost"] is not None]
191
+ cost = f"${sum(costs):.2f}" if costs else "cost unknown"
192
+ sources = []
193
+ for tool, (label, _, _) in TOOLS.items():
194
+ count = tools[tool]
195
+ if count is None:
196
+ sources.append(f"{label} no files")
197
+ else:
198
+ sources.append(f"{label} {count} session{'' if count == 1 else 's'}"
199
+ + (" without cost" if count and tool not in COSTED else ""))
200
+ return (f"Spent: {active} active, {tokens_text(sum(s['tokens'] for s in sessions))} tokens, {cost} "
201
+ f"(estimated; {', '.join(sources)}; other tools not counted)")
202
+
203
+
204
+ def main(argv: list[str]) -> int:
205
+ args = [a for a in argv if a != "--json"]
206
+ if not args:
207
+ print(__doc__.split("\n\n")[1], file=sys.stderr)
208
+ return 2
209
+ work = Path(args[1]) if len(args) > 1 else Path(__file__).resolve().parents[2] / "work"
210
+ try:
211
+ data = spent(work, args[0])
212
+ except work_index.WorkIndexError as error:
213
+ print(f"work-spent: {error}", file=sys.stderr)
214
+ return 1
215
+ print(json.dumps(data, indent=2) if "--json" in argv else data["line"])
216
+ return 0
217
+
218
+
219
+ if __name__ == "__main__":
220
+ raise SystemExit(main(sys.argv[1:]))
@@ -0,0 +1,61 @@
1
+ ---
2
+ name: bc-subagent-driven-development
3
+ description: Use when executing a written implementation plan in the current session with fresh agents for individual tasks and review checkpoints.
4
+ ---
5
+
6
+ # Subagent-Driven Development
7
+
8
+ A controller executes a plan by giving each task to a fresh implementer agent, then running spec-compliance and code-quality review before moving on.
9
+
10
+ At preflight, run the machine's storage health check if one exists, and stop and report on critical or unknown health or if the configured check cannot run. If no storage health check is configured, skip it and note that in one line in the report. At completion, prove each worker's commits are in `HEAD` (ancestor or patch-equivalent) and record that proof before removing worktrees or branches. Every implementer/reviewer packet says: run pytest through the guarded test runner the project's or machine's instructions name (otherwise plain `pytest`, with `tmp_path` for test fixtures and cleanup even on failure; never custom `--basetemp`); make scratch folders with `mktemp -d`, never under `/tmp`; run targeted tests only and reuse the shared full-suite evidence. The `agent-kernel` concept's Storage safety section holds the temp-file and scratch-folder rules, when loaded. Why: fresh agents cannot infer shared storage ownership.
11
+
12
+ ## Use when
13
+
14
+ - A written plan exists with reasonably independent tasks.
15
+ - The harness supports subagents or equivalent fresh-context workers.
16
+ - The controller should stay in this session and own integration.
17
+
18
+ Do not use for tightly coupled tasks that require constant shared context; execute inline or rewrite the plan.
19
+
20
+ ## Controller preflight
21
+
22
+ 1. Read the whole plan once.
23
+ 2. Extract every task with its full text and dependency context.
24
+ 3. Inspect git status/branch and establish isolation if needed.
25
+ 4. Create a task list for controller tracking.
26
+
27
+ Never make the implementer read the whole plan to find its task. Paste the exact task and curated context into the packet.
28
+
29
+ ## Per-task loop
30
+
31
+ 1. Dispatch implementer with full task text, context, working directory, constraints, and status contract.
32
+ 2. If implementer returns `NEEDS_CONTEXT`, provide missing context and re-dispatch.
33
+ 3. If `BLOCKED`, change something: more context, better model, smaller task, or escalate to the user. Do not retry blindly.
34
+ 4. If `DONE_WITH_CONCERNS`, read concerns before review.
35
+ 5. Run spec-compliance review: did the change implement exactly the task, no less and no extra?
36
+ 6. Fix/re-review until spec compliant.
37
+ 7. Run code-quality review: bugs, tests, maintainability, architecture, edge cases.
38
+ 8. Fix/re-review until quality issues are resolved or explicitly deferred.
39
+ 9. Parent verifies and marks task complete.
40
+
41
+ Do not dispatch multiple implementers in parallel unless tasks are proven independent and isolated; use `bc-dispatching-parallel-agents` for that case.
42
+
43
+ ## Implementer packet essentials
44
+
45
+ - Task name and full plan text for this task.
46
+ - Scene-setting: what came before and what this enables.
47
+ - Files/commands expected by the plan.
48
+ - Constraints: do not broaden scope, ask when unclear, commit if repo rules require.
49
+ - Report format: `DONE`, `DONE_WITH_CONCERNS`, `NEEDS_CONTEXT`, or `BLOCKED`; include files changed, tests run, evidence, concerns.
50
+
51
+ ## Completion
52
+
53
+ After all tasks pass review, run a final whole-diff review or relevant verification, then use the project’s branch-completion workflow if merge/PR/cleanup is needed.
54
+
55
+ ## Red flags
56
+
57
+ - Skipping spec review because code quality review “looks good.”
58
+ - Letting implementer self-review replace independent review.
59
+ - Proceeding with open Important/Critical review issues.
60
+ - Ignoring a blocked subagent or forcing the same failed prompt again.
61
+ - Trusting subagent success reports without checking diff and verification.
@@ -0,0 +1,184 @@
1
+ ---
2
+ name: bc-tdd
3
+ description: Use when writing new tests or behaviour-changing assertions, including a bug fix that adds a regression test or tests added as a side part of a feature; also for test-first, red-green-refactor, or new integration-test requests. Excludes reading, running or mechanically updating tests.
4
+ ---
5
+
6
+ # Test-Driven Development
7
+
8
+ Use targeted RED/GREEN checks, running pytest through the guarded test runner the project's or machine's instructions name (otherwise plain `pytest`, with `tmp_path` for test fixtures and cleanup even on failure; never custom `--basetemp`). Tests you write delete every temporary file and folder they create, even on failure; make scratch folders with `mktemp -d`, never under `/tmp`. Before a full suite, not each cycle, run the machine's storage health check if one exists and stop on critical or unknown health or if the configured check cannot run. If no storage health check is configured, skip it and note that in one line in the report. The `agent-kernel` concept's Storage safety section holds the temp-file and scratch-folder rules, when loaded. Why: fast feedback does not require repeated full suites.
9
+
10
+ If `~/.config/agent-concepts/overlays/bc-tdd.md` exists, read it for this machine's tool names.
11
+
12
+ These rules apply to new tests and behaviour-changing assertions, including regression tests added during bug fixes or feature work. Reading, running or mechanical test edits (such as import renames) do not require a watched fail or a new plan. For bugs without a tight repro, `bc-diagnosing-bugs` owns diagnosis; this concept owns the regression-test RED/GREEN cycle once the behaviour is identified.
13
+
14
+ ## Test levels
15
+
16
+ - **Level 1 — unit (example-based) tests.** The default for every change; the rest of this skill.
17
+ - **Level 2 — property-based tests. Required** when the change touches logic with a statable rule: parsers/formatters, data transforms, calculations, sorting/filtering, state transitions. Optional for glue, UI, I/O wiring and config. Hypothesis (Python), fast-check (JS/TS), proptest (Rust), run inside the project's normal suite; shell is out of scope (move rule-bearing shell logic into Python). Fail-first still applies: on code that already works, plant a bug, watch the property catch it, revert, and record that where you already report validation. Pin every shrunk failure as an explicit example. Never weaken or delete an existing property without the owner's approval. Load [properties.md](properties.md) before writing one.
18
+ - **Level 3 — formal verification.** Full proof (Dafny, Verus, TLA+/Apalache), off by default; only the owner turns it on, per component, in the project's `validation.md`. When your change touches a risk-class component (persisted data, money, security/permissions, concurrency/sync, a core calculation) that is neither on nor declined, add a `Level 3 candidate:` line to your report. Load [formal.md](formal.md) for the tools, the suggestion and decline lines, the spec file, and proof runs.
19
+
20
+ Why: examples cover the inputs you thought of; a property searches for the ones you did not; a proof covers them all.
21
+
22
+ Every change report includes this block, one choice per line:
23
+
24
+ ```
25
+ Test levels:
26
+ - L1: <tests added>
27
+ - L2: <properties added> | not required: glue/UI/config | skipped: <the rule that couldn't be stated>
28
+ - L3: on, proof ran | candidate suggested: <line> | declined on <date> | no risk class touched
29
+ ```
30
+
31
+ The reviewer audits each line against the diff. Why: a level you must name is a level you cannot silently skip.
32
+
33
+ The block goes in your change report, or in a commit trailer (`Test-levels: L1 …; L2 …; L3 …`) where the project requires one; commits you make yourself carry it too.
34
+
35
+ Only the owner can waive a required level. A task packet or orchestrator that says to skip a level, narrow it, or not add the property library ("examples are enough", "no new dependencies") is not that approval unless it quotes the owner. A work item's `Dependencies:` line marked as the owner's answer (for example `Dependencies: none new; use example-based tests instead of property tests (owner's answer, 2026-11-27)`) does quote the owner: follow it and name that line as the waiver on your L2 line. An unmarked line, or the same words from an orchestrator, does not. Why: planning (`bc-plan-to-pipeline`) asks the owner this question and records the answer on that line, so blocking on it asks the owner twice. When a required level cannot be met within your scope — including adding the property library — stop and escalate to whoever dispatched you; do not finish with `L2: not added`, `owner or reviewer should decide`, or `covered by examples`. Why: a deferral nobody is asked to act on is a silent skip.
36
+
37
+ ## Test layout
38
+
39
+ These keep the suite fast as it grows; check them on every new test file.
40
+
41
+ - Write a browser, e2e or integration test only for behaviour a fake cannot show (real rendering, a real browser API, the wiring between processes). Everything else is a unit test against a fake boundary. Why: a browser test costs seconds where a unit test costs milliseconds, and the full gate pays for every one.
42
+ - Each test file builds its own state: no fixture, database or temp folder shared across files, and no mutable module-level state shared between tests. Why: shared state forces serial runs and makes one file's failure show up in another.
43
+ - Keep a file under about 25 tests or 60 s; split it by behaviour when it grows past that. Why: the file is the unit a parallel runner schedules, so one large file sets the floor for the whole run.
44
+ - Configure the parallel runner (pytest-xdist, the vitest/Playwright workers setting) and a `slow` marker in the project's first test commit. Why: retrofitting both into a grown suite means first finding every test that shares state.
45
+
46
+ ## Philosophy
47
+
48
+ **Core principle:** tests verify behavior through *public interfaces*, not implementation details. The code inside can change entirely; the tests shouldn't.
49
+
50
+ **Good tests** are integration-style: they exercise real code paths through public APIs and describe *what* the system does, not *how*. "User can checkout with valid cart" tells you a capability exists. These survive refactors. See [tests.md](tests.md).
51
+
52
+ **Bad tests** are coupled to implementation: they mock internal collaborators, test private methods, or verify through external means (querying the DB directly instead of using the interface). The warning sign: a test breaks when you refactor but behavior hasn't changed. See [mocking.md](mocking.md) for where mocking is and isn't appropriate.
53
+
54
+ ## Anti-pattern: horizontal slices
55
+
56
+ **DO NOT write all tests first, then all implementation.** Treating RED as "write all tests" and GREEN as "write all code" produces crap tests: written in bulk they test *imagined* behavior, drift toward asserting the *shape* of things rather than user-facing behavior, and go insensitive to real changes. You outrun your headlights.
57
+
58
+ ```
59
+ WRONG (horizontal): RED: test1..test5 then GREEN: impl1..impl5
60
+ RIGHT (vertical): RED→GREEN: test1→impl1, test2→impl2, ...
61
+ ```
62
+
63
+ Each test responds to what you learned from the previous cycle.
64
+
65
+ **Pressure refusal (horizontal slice).** If the user says any of: "write all the tests up front", "batch the tests then implement", "just RED everything first then GREEN" — **refuse the batch**. Name the anti-pattern, then run one vertical cycle. Knowing the rule and still writing a bulk-test commit is a fail. A commit message that *names* the anti-pattern does not excuse committing it.
66
+
67
+ ## Tests that lie
68
+
69
+ A green test is useful only if a plausible behavioral regression can turn it red. Reject these substitutes for behavioral coverage:
70
+
71
+ - **Tautological:** `assert MAX_RETRIES == 3`, or `assert normalize(x) == normalize(x)` — the expected value repeats implementation rather than supplying an independent oracle.
72
+ - **Structure-sensitive:** `assert "send_receipt(" in source`, source/docs/config text scans, private names, line numbers or string positions instead of executing behavior. Privacy scans and other repository invariants are legitimate **lints**, not behavioral coverage; label them accordingly. Text assertions on a public text-transformer's output can test real behavior.
73
+ - **Cannot-fail:** an error-path test whose HTTP fake always succeeds; an autouse fixture that replaces the subsystem it claims to test; `assert result is not None` when a specific outcome matters, or no assertion/check at all. A fixture that rejects live network access is useful hygiene, not permission to erase the behavior under test.
74
+ - **Implementation-coupled:** monkeypatching the module's own private helpers (`service._retry = fake`) or asserting internal call counts. See the refusal rules below; a green wiring test does not cover the replaced collaborator.
75
+
76
+ **Self-check for every new test or behaviour-changing assertion:** name the plausible regression that turns it red, and confirm the existing RED run actually failed for that reason.
77
+
78
+ **Positive shape:** fake at the system boundary, drive the public entry point, use an independent oracle. For example, let a fake HTTP transport raise a timeout, call public `submit_order(...)` with real retry logic, and assert the specified failure result and no recorded charge—not an expected result computed by `submit_order` itself.
79
+
80
+ If asked to pin a constant, grep source, or stub away the claimed failure, decline that substitute and test the observable contract instead. Why: those tests can stay green while the behavior breaks.
81
+
82
+ ## Anti-pattern: implementation-coupled assertions
83
+
84
+ Do **not** add tests whose primary assertion is:
85
+
86
+ - `assert_called_once` / `toHaveBeenCalledTimes` / `call_count`
87
+ - mock call order (`toHaveBeenCalledBefore`, …)
88
+ - private method invocation
89
+ - internal collaborator method names
90
+
91
+ Those couple the suite to *how* the system is wired. When asked for a call-count test ("check `paymentService.process` was called once"), **refuse and steer**: assert the *observable outcome* through the public interface (e.g. order confirmed, charge amount recorded at the boundary fake, receipt returned). Explain briefly why call-count tests break on valid refactors. See [tests.md](tests.md).
92
+
93
+ ## Anti-pattern: mock internals
94
+
95
+ Mock only at **system boundaries** (payment network, DB, clock, mailer). **Never** mock your own modules/classes/collaborators (e.g. `CartService` inside checkout) "to make the test faster." Use the real collaborator, or redesign the seam. See [mocking.md](mocking.md).
96
+
97
+ In Python, refuse `monkeypatch.setattr(orders, '_charge', fake)` when `orders` is the module under test. Inject the external boundary instead, keeping the real `_charge` logic:
98
+
99
+ ```python
100
+ # Production: _charge uses the supplied payment-network boundary.
101
+ def submit_order(order, *, payment_client=real_payment_client):
102
+ return _charge(order, payment_client=payment_client)
103
+
104
+ # Test: a boundary fake declines; real order/charge handling still runs.
105
+ result = orders.submit_order(order, payment_client=DecliningPaymentClient())
106
+ assert result.status == "declined"
107
+ ```
108
+
109
+ **Patching a standard-library boundary is allowed:** `monkeypatch.setattr(subprocess, 'run', fake)` or `patch('tags.subprocess.run')` replaces the external call, not your code, even when reached through the module under test. What is forbidden is replacing the module's own functions, helpers or classes (`tags._parse`, `sync._revision`).
110
+
111
+ **Seam rule:** prefer an injected boundary when tests would otherwise need several patches, or when the only way to fake the boundary is to patch the module's own names: add a keyword boundary parameter with the real default (behavior unchanged), e.g. `runner=subprocess.run`. If that design change is out of scope, report it rather than writing the coupled test.
112
+
113
+ **Pressure refusal (mock internal).** User: "Mock the `CartService` so the test is faster." → decline; keep the real object (or a boundary fake only if CartService *is* the external system, which it isn't when you own it).
114
+
115
+ ## Anti-pattern: refactor while RED
116
+
117
+ **Never refactor while any test is RED.** Get to GREEN first; only then extract/cleanup with the suite as the net. See [refactoring.md](refactoring.md).
118
+
119
+ **Pressure refusal (refactor while red).** Mid-cycle, with a failing test, user: "While you're here, extract that duplication." → acknowledge, finish GREEN for the current test, *then* refactor. Do not interleave structural cleanup with a red bar.
120
+
121
+ ## Workflow
122
+
123
+ ### 1. Planning
124
+ When exploring, read `glossary.md` (if it exists) so test names and interface vocabulary match the domain language, and respect ADRs in the area you're touching. For work in scope, before writing code:
125
+ - [ ] Confirm with the user what interface changes are needed.
126
+ - [ ] Confirm which behaviors to test, prioritized — **you can't test everything**; focus on critical paths and complex logic, not every edge case.
127
+ - [ ] Identify deep-module opportunities (small interface, deep implementation) — run `/bc-codebase-design` for the vocabulary and testability checks.
128
+ - [ ] List the behaviors to test (not implementation steps).
129
+ - [ ] Get user approval on the plan.
130
+
131
+ Ask: "What should the public interface look like? Which behaviors matter most to test?"
132
+
133
+ **Small bug fixes:** when the requested behaviour and unchanged interface are clear, state the regression to test and proceed without interactive plan approval; still watch RED before the fix and GREEN after it. Ask if behaviour or interface needs a decision.
134
+
135
+ **Unattended mode:** when no user can answer (delegated child or headless job), do not stop for confirmation/approval. Record the behavior list and interface decision in your output or commit message, then proceed; keep the other planning checks.
136
+
137
+ ### 2. Tracer bullet
138
+ Write ONE test that confirms ONE thing. **RED:** test fails (watch it fail for the right reason). **GREEN:** minimal code to pass. This proves the path works end-to-end. [confirm-red.py](scripts/confirm-red.py) can run current changed tests against old code in a disposable tree (a full tracked-tree copy under `$TMPDIR` per run — on a large repo, require the configured storage health check to pass first; if none is configured, skip it with one report line): `python3 "$AGENT_CONCEPTS/concepts/bc-tdd/body/scripts/confirm-red.py" --base HEAD -- <test command...>` (for pytest, follow the runner and temp-file rules above; see `--help` for environment limits). Inspect the failure reason, not just its exit status.
139
+
140
+ If the test cannot be executed at all — no runner, missing fixture, unbuildable environment — you do not have a RED. Stop and report the blocker. Never proceed to GREEN against a test you have not watched fail. Why: GREEN without a watched fail is a green bar you invented.
141
+
142
+ **Tests written after the code:** coverage, regression and characterisation tests for existing code still need a watched fail. Revert the fix or make a minimal mutation that breaks the named covered behavior, watch the test go red for that reason, restore, then watch green. Record both runs. Use a disposable copy for mutations; do not disturb unrelated working-tree changes. A missing-symbol/collection failure alone does not prove behavior is covered.
143
+
144
+ ### 3. Incremental loop
145
+ For each remaining behavior: **RED** (next test fails) → **GREEN** (minimal code to pass). One test at a time; only enough code to pass the current test; don't anticipate future tests; keep tests on observable behavior.
146
+
147
+ ### 4. Refactor
148
+ After the current cycle is green, look for [refactor candidates](refactoring.md). **Never refactor while RED.**
149
+
150
+ ## Checklist per cycle
151
+ ```
152
+ [ ] Test describes behavior, not implementation; source/config scans are labelled lints
153
+ [ ] Plausible regression named; RED failed for that reason (confirm-red.py or behavioral mutation); both RED/GREEN runs recorded
154
+ [ ] Independent oracle; fixtures preserve the claimed failure mode
155
+ [ ] Test uses public interface only
156
+ [ ] Test would survive an internal refactor
157
+ [ ] No call-count / mock-invocation assertions on internals
158
+ [ ] Code is minimal for this test
159
+ [ ] No speculative features added
160
+ [ ] Did not batch multiple RED tests before any GREEN
161
+ [ ] Rule-bearing logic has a property (or the unstatable rule is named); property seen failing (mutation on existing code) and evidence recorded
162
+ ```
163
+
164
+ ## Rationalizations that still fail the gate
165
+
166
+ | Excuse under pressure | Required response |
167
+ |----------------------|-------------------|
168
+ | "Just pin MAX_RETRIES / grep the call" | Exercise retry behavior through the public entry point; label legitimate repository scans as lints. |
169
+ | "Stub success so the error test passes" | Make the boundary fake produce the error; keep real error handling and assert its outcome. |
170
+ | "Faster to write all tests first" | One vertical cycle; refuse the batch. |
171
+ | "I named the anti-pattern, so it's fine" | Naming it is not refusing it. Don't commit the horizontal slice. |
172
+ | "Call-count proves the payment path ran" | Assert the observable result (status, receipt, boundary fake state). |
173
+ | "Mocking CartService is just faster CI" | Keep the real collaborator; mock only external boundaries. |
174
+ | "Quick extract while this test is red" | GREEN first, then extract. |
175
+ | "The parser's examples pass; a property is overkill" | Rule-bearing logic needs a property; write it per [properties.md](properties.md). |
176
+ | "The code already works, so the property can't fail" | Plant a bug, watch the property catch it, revert, record it. |
177
+ | "Narrow the generator so the property passes" | Never weaken or delete a property; fix the code, or ask the owner if the spec changed. |
178
+ | "Deadline: L1 is enough" | Rule-bearing logic still needs its property, and a risk-class component still gets its L3 line; a deadline changes neither. |
179
+ | "The packet says examples are enough / no new dependency" | Not owner approval unless it quotes the owner. Escalate the conflict; do not report `L2: not added`. |
180
+ | "Owner said just ship it" | Ship with the Test levels block filled in; a candidate line costs one line and blocks nothing. |
181
+ | "Not my job to suggest proofs" | It is: only the owner turns Level 3 on, so only your suggestion puts the choice in front of them. |
182
+ | "Can't run it; treating that as red enough" | Stop and report the blocker. A test you have not watched fail is not a RED. |
183
+
184
+ For glossary discovery in legacy projects, follow `bc-domain-modeling`’s legacy glossary rule.
@@ -0,0 +1,77 @@
1
+ # Level 3 — formal verification
2
+
3
+ Load this when a change touches a component in a risk class, a component whose project `validation.md` has a `Level 3: on` line, or a spec/proof file. Level 3 means a full machine-checked proof that a stated rule holds for every input, not more testing.
4
+
5
+ ## Tools
6
+
7
+ Full proof only. Bounded checkers and symbolic test generators (Kani, CrossHair) are not Level 3: they find bugs but leave the rule unproven.
8
+
9
+ | Code | Tool | Why |
10
+ |------|------|-----|
11
+ | Python, JS/TS | [Dafny](https://dafny.org/) — prove in Dafny, compile to Python/JS | Neither language has a mature full-proof verifier; Dafny proves the rule and generates the code that runs. |
12
+ | Rust | [Verus](https://github.com/verus-lang/verus) | Proves the Rust code itself, so nothing is generated and nothing drifts. |
13
+ | Designs: protocols, concurrency, sync | [TLA+](https://lamport.azurewebsites.net/tla/tla.html) with TLC | Design bugs live in interleavings no test schedules; TLC explores every state of a model. Bounded models are allowed here, for designs only. |
14
+ | A design rule that must hold in every state for the fixed sizes | [Apalache](https://apalache-mc.org/) inductive invariant, alongside TLC | An inductive invariant is a proof for those sizes, not a search that stops at a depth. |
15
+ | Shell | none | Move the rule-bearing logic into a language above. |
16
+
17
+ ## Turning it on
18
+
19
+ Only the owner turns Level 3 on, per component, by adding a line to the project's `.bc-agent/conventions/validation.md`:
20
+
21
+ ```
22
+ Level 3: on — <component path> — <tool> <pinned version> — spec: <spec file> — command: <proof command>
23
+ ```
24
+
25
+ You never add, edit or remove this line. Why: a proof costs real effort for the life of the component, and only the owner decides that cost is worth paying.
26
+
27
+ ## Suggesting it
28
+
29
+ A component is in a **risk class** when it holds one of:
30
+
31
+ - persisted data that could be lost or corrupted;
32
+ - money;
33
+ - security or permissions;
34
+ - concurrency or sync;
35
+ - a core calculation many parts depend on.
36
+
37
+ Whenever your change touches a component in a risk class, and `validation.md` has neither a `Level 3: on` nor a `Level 3 declined` line for it, add this line to your report:
38
+
39
+ ```
40
+ Level 3 candidate: <component> — <risk> — <tool> — <rough effort>
41
+ ```
42
+
43
+ Suggest it even when nobody asked, under deadline, and when the owner said to just ship. Suggesting changes nothing in the code and blocks nothing; staying silent hides a choice that belongs to the owner.
44
+
45
+ When the owner refuses, record it in `validation.md` (writing a refusal the owner gave is allowed; turning Level 3 on is not):
46
+
47
+ ```
48
+ Level 3 declined: <component>, <YYYY-MM-DD>, <reason>
49
+ ```
50
+
51
+ Do not suggest that component again unless its risk class changes (for example a cache starts persisting user data). Report `L3: declined on <date>` instead.
52
+
53
+ ## Spec file
54
+
55
+ Before any proof, write a spec file at the path the `Level 3: on` line will name. It holds:
56
+
57
+ 1. **Rules.** Each rule is one plain-English line paired with its formal statement (Dafny `ensures`/lemma, Verus `ensures`/proof fn, TLA+ invariant or property).
58
+ 2. **Assumptions.** An explicit list of everything taken on trust: every `assume`, axiom, `{:axiom}`, Verus `external_body`/`assume`/`admit`, `{:verify false}`, TLA+ constraint that excludes states, model sizes, and the behavior of unproven code the proof calls.
59
+
60
+ The owner approves the plain-English rules and the assumptions list. An independent reviewer (`bc-code-review` Spec axis) checks that each formal rule says what its English line says, and that every escape hatch in the proof appears in the approved assumptions.
61
+
62
+ ## Running proofs
63
+
64
+ Run the recorded `command:` on every change that touches a Level 3 component, and once more in final validation before landing. Use the tool version pinned in the `Level 3: on` line.
65
+
66
+ If the tool is missing or the proof times out, the result is **untested**, never passed. An untested proof blocks landing changes to that component; changes that do not touch it are unaffected.
67
+
68
+ ## Dafny-generated code
69
+
70
+ - Commit both the Dafny source and the generated Python/JS; mark each generated file do-not-edit in a header comment.
71
+ - Validation regenerates from the current source and fails if the committed output differs.
72
+ - Put Level 2 property tests at the boundary where hand-written code calls the generated module.
73
+ - Never hand-edit a generated file: change the Dafny source and regenerate.
74
+
75
+ ## Trust boundaries
76
+
77
+ A proof covers only what it states, under its assumptions. It does not cover: the hand-written code around the proven module (Level 1–2 tests cover it), the Dafny compiler and target runtime, the TLA+ model's fidelity to the real implementation, sizes beyond the fixed model sizes, or anything listed as an assumption. Say which of these a report relies on rather than calling the component "proven correct".
@@ -0,0 +1,49 @@
1
+ # When to mock
2
+
3
+ Mock at **system boundaries** only:
4
+ - External APIs (payment, email, etc.)
5
+ - Databases (sometimes — prefer a test DB)
6
+ - Time / randomness
7
+ - File system (sometimes)
8
+
9
+ **Don't mock:**
10
+ - Your own classes/modules
11
+ - Internal collaborators
12
+ - Anything you control
13
+
14
+ ## Designing for mockability
15
+
16
+ At system boundaries, design interfaces that are easy to mock.
17
+
18
+ **1. Use dependency injection** — pass external dependencies in rather than creating them internally:
19
+
20
+ ```typescript
21
+ // Easy to mock
22
+ function processPayment(order, paymentClient) {
23
+ return paymentClient.charge(order.total);
24
+ }
25
+
26
+ // Hard to mock
27
+ function processPayment(order) {
28
+ const client = new StripeClient(process.env.STRIPE_KEY);
29
+ return client.charge(order.total);
30
+ }
31
+ ```
32
+
33
+ **2. Prefer SDK-style interfaces over generic fetchers** — one specific function per external operation, not one generic function with conditional logic:
34
+
35
+ ```typescript
36
+ // GOOD: each function is independently mockable
37
+ const api = {
38
+ getUser: (id) => fetch(`/users/${id}`),
39
+ getOrders: (userId) => fetch(`/users/${userId}/orders`),
40
+ createOrder: (data) => fetch("/orders", { method: "POST", body: data }),
41
+ };
42
+
43
+ // BAD: mocking requires conditional logic inside the mock
44
+ const api = {
45
+ fetch: (endpoint, options) => fetch(endpoint, options),
46
+ };
47
+ ```
48
+
49
+ The SDK approach means each mock returns one specific shape, no conditional logic in test setup, and it's easy to see which endpoints a test exercises.