@givolt/i3-composer-agent 0.0.0-stage → 1.0.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 (231) hide show
  1. package/.agents/plugins/marketplace.json +23 -0
  2. package/.claude/commands/build.md +44 -0
  3. package/.claude/commands/code-simplify.md +22 -0
  4. package/.claude/commands/constraints.md +32 -0
  5. package/.claude/commands/plan.md +18 -0
  6. package/.claude/commands/review.md +16 -0
  7. package/.claude/commands/ship.md +72 -0
  8. package/.claude/commands/spec.md +17 -0
  9. package/.claude/commands/test.md +19 -0
  10. package/.claude/commands/webperf.md +32 -0
  11. package/.claude-plugin/marketplace.json +27 -0
  12. package/.claude-plugin/plugin.json +19 -0
  13. package/.codex-plugin/plugin.json +28 -0
  14. package/.gemini/commands/build.toml +43 -0
  15. package/.gemini/commands/code-simplify.toml +22 -0
  16. package/.gemini/commands/constraints.toml +32 -0
  17. package/.gemini/commands/planning.toml +18 -0
  18. package/.gemini/commands/review.toml +16 -0
  19. package/.gemini/commands/ship.toml +72 -0
  20. package/.gemini/commands/spec.toml +17 -0
  21. package/.gemini/commands/test.toml +19 -0
  22. package/.gemini/commands/webperf.toml +32 -0
  23. package/CHANGELOG.md +23 -0
  24. package/LICENSE +21 -0
  25. package/NOTICE.md +9 -0
  26. package/README.md +117 -2
  27. package/agents/code-reviewer.md +102 -0
  28. package/agents/security-auditor.md +112 -0
  29. package/agents/test-engineer.md +95 -0
  30. package/agents/web-performance-auditor.md +184 -0
  31. package/bin/i3-composer-agent.cjs +122 -0
  32. package/commands/build.toml +43 -0
  33. package/commands/code-simplify.toml +22 -0
  34. package/commands/constraints.toml +32 -0
  35. package/commands/planning.toml +18 -0
  36. package/commands/review.toml +16 -0
  37. package/commands/ship.toml +72 -0
  38. package/commands/spec.toml +17 -0
  39. package/commands/test.toml +19 -0
  40. package/commands/webperf.toml +32 -0
  41. package/docs/adoption-guide.md +129 -0
  42. package/docs/advanced-per-agent-configuration.md +70 -0
  43. package/docs/agents.md +123 -0
  44. package/docs/antigravity-setup.md +128 -0
  45. package/docs/codebuddy-setup.md +41 -0
  46. package/docs/codex-setup.md +34 -0
  47. package/docs/commandcode-setup.md +69 -0
  48. package/docs/comparison.md +131 -0
  49. package/docs/copilot-cli-setup.md +64 -0
  50. package/docs/copilot-setup.md +162 -0
  51. package/docs/cursor-setup.md +225 -0
  52. package/docs/developer-onboarding.md +116 -0
  53. package/docs/gemini-cli-setup.md +133 -0
  54. package/docs/getting-started.md +208 -0
  55. package/docs/opencode-setup.md +259 -0
  56. package/docs/other-hosts.md +7 -0
  57. package/docs/skill-anatomy.md +203 -0
  58. package/docs/windsurf-setup.md +48 -0
  59. package/evals/README.md +101 -0
  60. package/evals/cases/api-and-interface-design.json +45 -0
  61. package/evals/cases/browser-testing-with-devtools.json +44 -0
  62. package/evals/cases/ci-cd-and-automation.json +45 -0
  63. package/evals/cases/code-review-and-quality.json +49 -0
  64. package/evals/cases/code-simplification.json +45 -0
  65. package/evals/cases/constraint-driven-development.json +79 -0
  66. package/evals/cases/context-engineering.json +44 -0
  67. package/evals/cases/debugging-and-error-recovery.json +58 -0
  68. package/evals/cases/deprecation-and-migration.json +52 -0
  69. package/evals/cases/documentation-and-adrs.json +44 -0
  70. package/evals/cases/doubt-driven-development.json +43 -0
  71. package/evals/cases/frontend-ui-engineering.json +52 -0
  72. package/evals/cases/git-workflow-and-versioning.json +47 -0
  73. package/evals/cases/idea-refine.json +43 -0
  74. package/evals/cases/incremental-implementation.json +57 -0
  75. package/evals/cases/interview-me.json +42 -0
  76. package/evals/cases/observability-and-instrumentation.json +44 -0
  77. package/evals/cases/performance-optimization.json +53 -0
  78. package/evals/cases/planning-and-task-breakdown.json +45 -0
  79. package/evals/cases/security-and-hardening.json +53 -0
  80. package/evals/cases/shipping-and-launch.json +56 -0
  81. package/evals/cases/source-driven-development.json +44 -0
  82. package/evals/cases/spec-driven-development.json +72 -0
  83. package/evals/cases/test-driven-development.json +73 -0
  84. package/evals/cases/using-agent-skills.json +44 -0
  85. package/evals/fixtures/api-and-interface-design/service-brief.md +19 -0
  86. package/evals/fixtures/browser-testing-with-devtools/README.md +5 -0
  87. package/evals/fixtures/browser-testing-with-devtools/index.html +24 -0
  88. package/evals/fixtures/browser-testing-with-devtools/server.js +15 -0
  89. package/evals/fixtures/ci-cd-and-automation/package.json +8 -0
  90. package/evals/fixtures/ci-cd-and-automation/src/slug.js +3 -0
  91. package/evals/fixtures/ci-cd-and-automation/test/slug.test.js +9 -0
  92. package/evals/fixtures/code-review-and-quality/user-search.diff +16 -0
  93. package/evals/fixtures/code-simplification/config-parser.js +46 -0
  94. package/evals/fixtures/code-simplification/config-parser.test.js +15 -0
  95. package/evals/fixtures/context-engineering/context-audit.md +15 -0
  96. package/evals/fixtures/debugging-and-error-recovery/pagination.js +8 -0
  97. package/evals/fixtures/debugging-and-error-recovery/pagination.test.js +9 -0
  98. package/evals/fixtures/debugging-and-error-recovery/time-pressure.md +6 -0
  99. package/evals/fixtures/deprecation-and-migration/api-inventory.md +9 -0
  100. package/evals/fixtures/documentation-and-adrs/decision-context.md +16 -0
  101. package/evals/fixtures/doubt-driven-development/migration-plan.md +19 -0
  102. package/evals/fixtures/frontend-ui-engineering/Button.tsx +7 -0
  103. package/evals/fixtures/frontend-ui-engineering/design-system.md +11 -0
  104. package/evals/fixtures/git-workflow-and-versioning/.eval/working-tree.patch +21 -0
  105. package/evals/fixtures/git-workflow-and-versioning/app.js +7 -0
  106. package/evals/fixtures/git-workflow-and-versioning/app.test.js +9 -0
  107. package/evals/fixtures/incremental-implementation/reports.js +7 -0
  108. package/evals/fixtures/incremental-implementation/reports.test.js +12 -0
  109. package/evals/fixtures/incremental-implementation/tasks/plan.md +8 -0
  110. package/evals/fixtures/incremental-implementation-pressure/draft-export.js +17 -0
  111. package/evals/fixtures/incremental-implementation-pressure/scenario.md +9 -0
  112. package/evals/fixtures/observability-and-instrumentation/operations.md +11 -0
  113. package/evals/fixtures/observability-and-instrumentation/payment-retry.js +14 -0
  114. package/evals/fixtures/performance-optimization/benchmark.js +15 -0
  115. package/evals/fixtures/performance-optimization/products.js +14 -0
  116. package/evals/fixtures/planning-and-task-breakdown/notifications-spec.md +18 -0
  117. package/evals/fixtures/security-and-hardening/webhook.js +11 -0
  118. package/evals/fixtures/security-and-hardening/webhook.test.js +13 -0
  119. package/evals/fixtures/shipping-and-launch/authority-pressure.md +6 -0
  120. package/evals/fixtures/shipping-and-launch/launch-status.md +11 -0
  121. package/evals/fixtures/source-driven-development/framework-task.md +10 -0
  122. package/evals/fixtures/spec-driven-development/billing-brief.md +16 -0
  123. package/evals/fixtures/spec-driven-development-decomposition/portal-brief.md +22 -0
  124. package/evals/fixtures/test-driven-development/BUG.md +10 -0
  125. package/evals/fixtures/test-driven-development/README.md +28 -0
  126. package/evals/fixtures/test-driven-development/package.json +9 -0
  127. package/evals/fixtures/test-driven-development/src/split.js +8 -0
  128. package/evals/fixtures/test-driven-development/test/split.test.js +13 -0
  129. package/evals/fixtures/test-driven-development-ecosystem/README.md +9 -0
  130. package/evals/fixtures/test-driven-development-ecosystem/ledger.py +15 -0
  131. package/evals/fixtures/test-driven-development-ecosystem/test_ledger.py +19 -0
  132. package/evals/fixtures/using-agent-skills/incident.md +6 -0
  133. package/evals/plugin/code-review-fires/graders/off-by-one.md +7 -0
  134. package/evals/plugin/code-review-fires/graders/severity-labels.md +4 -0
  135. package/evals/plugin/code-review-fires/graders/skill-fired.md +5 -0
  136. package/evals/plugin/code-review-fires/prompt.md +31 -0
  137. package/evals/plugin/code-review-stays-quiet/graders/not-fired.md +8 -0
  138. package/evals/plugin/code-review-stays-quiet/graders/tdd-fired.md +6 -0
  139. package/evals/plugin/code-review-stays-quiet/prompt.md +8 -0
  140. package/evals/plugin/code-review-stays-quiet-on-commit-message/graders/not-fired.md +8 -0
  141. package/evals/plugin/code-review-stays-quiet-on-commit-message/prompt.md +25 -0
  142. package/evals/skill-impact.md +6 -0
  143. package/hooks/SDD-CACHE.md +167 -0
  144. package/hooks/SIMPLIFY-IGNORE.md +91 -0
  145. package/hooks/sdd-cache-post.sh +135 -0
  146. package/hooks/sdd-cache-pre.sh +106 -0
  147. package/hooks/sdd-cache-test.sh +246 -0
  148. package/hooks/session-start-test.sh +47 -0
  149. package/hooks/session-start.sh +33 -0
  150. package/hooks/simplify-ignore-test.sh +476 -0
  151. package/hooks/simplify-ignore.sh +352 -0
  152. package/package.json +89 -4
  153. package/plugin.json +7 -0
  154. package/rebrand/MAINTENANCE.md +112 -0
  155. package/rebrand/NOTICE.md +9 -0
  156. package/rebrand/PR-WORKFLOW.md +34 -0
  157. package/rebrand/UNIFICATION-SPEC.md +33 -0
  158. package/rebrand/VALIDATION.md +28 -0
  159. package/rebrand/VERSIONING.md +32 -0
  160. package/rebrand/apply.cjs +194 -0
  161. package/rebrand/brand.json +13 -0
  162. package/rebrand/catalog.cjs +56 -0
  163. package/rebrand/fork-patches.json +12 -0
  164. package/rebrand/overlay/.github/workflows/test-plugin-install.yml +177 -0
  165. package/rebrand/overlay/CHANGELOG.md +23 -0
  166. package/rebrand/overlay/bin/i3-composer-agent.cjs +122 -0
  167. package/rebrand/overlay/scripts/validate-brand.cjs +44 -0
  168. package/rebrand/overlay/tests/bundle.test.cjs +85 -0
  169. package/rebrand/package.template.json +82 -0
  170. package/rebrand/rebrand.sh +4 -0
  171. package/rebrand/record-upstream.cjs +37 -0
  172. package/rebrand/templates/README.md +86 -0
  173. package/rebrand/templates/codebuddy-setup.md +41 -0
  174. package/rebrand/templates/codex-setup.md +34 -0
  175. package/rebrand/tests/pipeline.test.cjs +185 -0
  176. package/rebrand/upstream.json +171 -0
  177. package/references/accessibility-checklist.md +160 -0
  178. package/references/definition-of-done.md +67 -0
  179. package/references/observability-checklist.md +92 -0
  180. package/references/orchestration-patterns.md +370 -0
  181. package/references/performance-checklist.md +236 -0
  182. package/references/security-checklist.md +248 -0
  183. package/references/testing-patterns.md +235 -0
  184. package/scripts/floor-guard-reference-test.js +291 -0
  185. package/scripts/lib/skill-lint-test.js +650 -0
  186. package/scripts/lib/skill-lint.js +584 -0
  187. package/scripts/run-evals-test.js +623 -0
  188. package/scripts/run-evals.js +638 -0
  189. package/scripts/validate-artifact-paths-test.js +179 -0
  190. package/scripts/validate-artifact-paths.js +128 -0
  191. package/scripts/validate-brand.cjs +44 -0
  192. package/scripts/validate-commands-test.js +216 -0
  193. package/scripts/validate-commands.js +222 -0
  194. package/scripts/validate-reference-links-test.js +495 -0
  195. package/scripts/validate-reference-links.js +187 -0
  196. package/scripts/validate-skills.js +69 -0
  197. package/scripts/validate-versions-test.js +32 -0
  198. package/scripts/validate-versions.js +35 -0
  199. package/skills/api-and-interface-design/SKILL.md +367 -0
  200. package/skills/browser-testing-with-devtools/SKILL.md +317 -0
  201. package/skills/ci-cd-and-automation/SKILL.md +390 -0
  202. package/skills/code-review-and-quality/SKILL.md +398 -0
  203. package/skills/code-simplification/SKILL.md +331 -0
  204. package/skills/constraint-driven-development/SKILL.md +311 -0
  205. package/skills/constraint-driven-development/references/floor-guard.md +182 -0
  206. package/skills/context-engineering/SKILL.md +353 -0
  207. package/skills/debugging-and-error-recovery/SKILL.md +300 -0
  208. package/skills/deprecation-and-migration/SKILL.md +247 -0
  209. package/skills/documentation-and-adrs/SKILL.md +288 -0
  210. package/skills/doubt-driven-development/SKILL.md +243 -0
  211. package/skills/frontend-ui-engineering/SKILL.md +340 -0
  212. package/skills/git-workflow-and-versioning/SKILL.md +355 -0
  213. package/skills/idea-refine/SKILL.md +178 -0
  214. package/skills/idea-refine/examples.md +238 -0
  215. package/skills/idea-refine/frameworks.md +99 -0
  216. package/skills/idea-refine/refinement-criteria.md +113 -0
  217. package/skills/idea-refine/scripts/idea-refine.sh +15 -0
  218. package/skills/incremental-implementation/SKILL.md +249 -0
  219. package/skills/interview-me/SKILL.md +235 -0
  220. package/skills/observability-and-instrumentation/SKILL.md +238 -0
  221. package/skills/performance-optimization/SKILL.md +267 -0
  222. package/skills/performance-optimization/references/optimization-patterns.md +250 -0
  223. package/skills/planning-and-task-breakdown/SKILL.md +257 -0
  224. package/skills/security-and-hardening/SKILL.md +216 -0
  225. package/skills/security-and-hardening/references/hardening-patterns.md +324 -0
  226. package/skills/shipping-and-launch/SKILL.md +330 -0
  227. package/skills/source-driven-development/SKILL.md +216 -0
  228. package/skills/spec-driven-development/SKILL.md +259 -0
  229. package/skills/test-driven-development/SKILL.md +398 -0
  230. package/skills/using-agent-skills/SKILL.md +192 -0
  231. package/tests/bundle.test.cjs +85 -0
@@ -0,0 +1,69 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * validate-skills.js
4
+ *
5
+ * CLI that validates every skill in skills/ against the rules in
6
+ * docs/skill-anatomy.md. The rules themselves live in scripts/lib/skill-lint.js
7
+ * (a single source of truth, importable and unit-testable); this file is a thin
8
+ * wrapper that walks the skills directory, runs the linter, prints the report,
9
+ * and sets the exit code.
10
+ *
11
+ * Exit codes: 0 = all clear, 1 = one or more errors
12
+ */
13
+
14
+ 'use strict';
15
+
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+
19
+ const { lintSkill } = require('./lib/skill-lint');
20
+
21
+ const SKILLS_DIR = path.resolve(__dirname, '..', 'skills');
22
+
23
+ // ─── Main ────────────────────────────────────────────────────────────────────
24
+
25
+ function main() {
26
+ if (!fs.existsSync(SKILLS_DIR)) {
27
+ console.error(`ERROR: skills directory not found at ${SKILLS_DIR}`);
28
+ process.exit(1);
29
+ }
30
+
31
+ const skillDirs = fs.readdirSync(SKILLS_DIR)
32
+ .filter(d => fs.statSync(path.join(SKILLS_DIR, d)).isDirectory())
33
+ .sort();
34
+
35
+ const knownSkills = new Set(skillDirs);
36
+
37
+ let totalErrors = 0;
38
+ let totalWarnings = 0;
39
+
40
+ for (const dirName of skillDirs) {
41
+ const { errors, warnings, exempt } = lintSkill(dirName, SKILLS_DIR, knownSkills);
42
+ totalErrors += errors.length;
43
+ totalWarnings += warnings.length;
44
+
45
+ if (errors.length === 0 && warnings.length === 0) {
46
+ const tag = exempt ? ' (section checks exempt)' : '';
47
+ console.log(` ✓ ${dirName}${tag}`);
48
+ } else {
49
+ const icon = errors.length > 0 ? ' ✗ ' : ' ⚠ ';
50
+ console.log(`${icon} ${dirName}`);
51
+ for (const msg of errors) console.log(` ERROR: ${msg}`);
52
+ for (const msg of warnings) console.log(` WARN: ${msg}`);
53
+ }
54
+ }
55
+
56
+ const status = totalErrors > 0 ? 'FAILED' : totalWarnings > 0 ? 'PASSED WITH WARNINGS' : 'PASSED';
57
+ console.log(`\n${skillDirs.length} skills checked — ${totalErrors} error(s), ${totalWarnings} warning(s) — ${status}`);
58
+
59
+ if (totalErrors > 0) process.exit(1);
60
+ }
61
+
62
+ // Surface unexpected failures (fs errors, bad symlinks, …) as a structured
63
+ // one-line CI error instead of an uncaught stack trace.
64
+ try {
65
+ main();
66
+ } catch (err) {
67
+ console.error(`\nERROR: validate-skills failed unexpectedly: ${err.message}`);
68
+ process.exit(1);
69
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+
3
+ const assert = require("node:assert/strict");
4
+ const { readFileSync } = require("node:fs");
5
+ const test = require("node:test");
6
+
7
+ const manifestPaths = [
8
+ "package.json",
9
+ "plugin.json",
10
+ ".codex-plugin/plugin.json",
11
+ ".claude-plugin/plugin.json",
12
+ ".claude-plugin/marketplace.json",
13
+ ".agents/plugins/marketplace.json",
14
+ ];
15
+
16
+ function readManifestVersion(manifestPath) {
17
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
18
+ return manifest.version ?? manifest.plugins?.[0]?.version;
19
+ }
20
+
21
+ test("all plugin manifests use the root plugin.json version", () => {
22
+ const expectedVersion = readManifestVersion("plugin.json");
23
+ assert.ok(expectedVersion, "plugin.json must define a version");
24
+
25
+ for (const manifestPath of manifestPaths) {
26
+ assert.equal(
27
+ readManifestVersion(manifestPath),
28
+ expectedVersion,
29
+ `${manifestPath} must use version ${expectedVersion}`,
30
+ );
31
+ }
32
+ });
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+
3
+ "use strict";
4
+
5
+ const { readFileSync } = require("node:fs");
6
+
7
+ const manifestPaths = [
8
+ "package.json",
9
+ "plugin.json",
10
+ ".codex-plugin/plugin.json",
11
+ ".claude-plugin/plugin.json",
12
+ ".claude-plugin/marketplace.json",
13
+ ".agents/plugins/marketplace.json",
14
+ ];
15
+
16
+ function readManifestVersion(manifestPath) {
17
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
18
+ return manifest.version ?? manifest.plugins?.[0]?.version;
19
+ }
20
+
21
+ const expectedVersion = readManifestVersion("plugin.json");
22
+ if (!expectedVersion) {
23
+ throw new Error("plugin.json is missing a version field");
24
+ }
25
+
26
+ for (const manifestPath of manifestPaths) {
27
+ const version = readManifestVersion(manifestPath);
28
+ if (version !== expectedVersion) {
29
+ throw new Error(
30
+ `${manifestPath} has version ${version ?? "<missing>"}; expected ${expectedVersion}`,
31
+ );
32
+ }
33
+ }
34
+
35
+ console.log(`All plugin manifests use version ${expectedVersion}.`);
@@ -0,0 +1,367 @@
1
+ ---
2
+ name: api-and-interface-design
3
+ description: Guides stable API and interface design. Use when designing APIs, module boundaries, or any public interface. Use when creating REST or GraphQL endpoints, defining type contracts between modules, or establishing boundaries between frontend and backend.
4
+ ---
5
+
6
+ # API and Interface Design
7
+
8
+ ## Overview
9
+
10
+ Design stable, well-documented interfaces that are hard to misuse. Good interfaces make the right thing easy and the wrong thing hard. This applies to REST APIs, GraphQL schemas, module boundaries, component props, and any surface where one piece of code talks to another.
11
+
12
+ ## When to Use
13
+
14
+ - Designing new API endpoints
15
+ - Defining module boundaries or contracts between teams
16
+ - Creating component prop interfaces
17
+ - Establishing database schema that informs API shape
18
+ - Changing existing public interfaces
19
+
20
+ ## Core Principles
21
+
22
+ ### Hyrum's Law
23
+
24
+ > With a sufficient number of users of an API, all observable behaviors of your system will be depended on by somebody, regardless of what you promise in the contract.
25
+
26
+ This means: every public behavior — including undocumented quirks, error message text, timing, and ordering — becomes a de facto contract once users depend on it. Design implications:
27
+
28
+ - **Be intentional about what you expose.** Every observable behavior is a potential commitment.
29
+ - **Don't leak implementation details.** If users can observe it, they will depend on it.
30
+ - **Plan for deprecation at design time.** See `deprecation-and-migration` for how to safely remove things users depend on.
31
+ - **Tests are not enough.** Even with perfect contract tests, Hyrum's Law means "safe" changes can break real users who depend on undocumented behavior.
32
+
33
+ ### The One-Version Rule
34
+
35
+ Avoid forcing consumers to choose between multiple versions of the same dependency or API. Diamond dependency problems arise when different consumers need different versions of the same thing. Design for a world where only one version exists at a time — extend rather than fork.
36
+
37
+ ### 1. Contract First
38
+
39
+ Define the interface before implementing it. The contract is the spec — implementation follows.
40
+
41
+ ```typescript
42
+ // Define the contract first
43
+ interface TaskAPI {
44
+ // Creates a task and returns the created task with server-generated fields
45
+ createTask(input: CreateTaskInput): Promise<Task>;
46
+
47
+ // Returns paginated tasks matching filters
48
+ listTasks(params: ListTasksParams): Promise<PaginatedResult<Task>>;
49
+
50
+ // Returns a single task or throws NotFoundError
51
+ getTask(id: string): Promise<Task>;
52
+
53
+ // Partial update — only provided fields change
54
+ updateTask(id: string, input: UpdateTaskInput): Promise<Task>;
55
+
56
+ // Idempotent delete — succeeds even if already deleted
57
+ deleteTask(id: string): Promise<void>;
58
+ }
59
+ ```
60
+
61
+ ### 2. Consistent Error Semantics
62
+
63
+ Pick one error strategy and use it everywhere:
64
+
65
+ ```typescript
66
+ // REST: HTTP status codes + structured error body
67
+ // Every error response follows the same shape
68
+ interface APIError {
69
+ error: {
70
+ code: string; // Machine-readable: "VALIDATION_ERROR"
71
+ message: string; // Human-readable: "Email is required"
72
+ details?: unknown; // Additional context when helpful
73
+ };
74
+ }
75
+
76
+ // Status code mapping
77
+ // 400 → Client sent invalid data
78
+ // 401 → Not authenticated
79
+ // 403 → Authenticated but not authorized
80
+ // 404 → Resource not found
81
+ // 409 → Conflict (duplicate, version mismatch)
82
+ // 422 → Validation failed (semantically invalid)
83
+ // 500 → Server error (never expose internal details)
84
+ ```
85
+
86
+ **Don't mix patterns.** If some endpoints throw, others return null, and others return `{ error }` — the consumer can't predict behavior.
87
+
88
+ ### 3. Validate at Boundaries
89
+
90
+ Trust internal code. Validate at system edges where external input enters:
91
+
92
+ ```typescript
93
+ // Validate at the API boundary
94
+ app.post('/api/tasks', async (req, res) => {
95
+ const result = CreateTaskSchema.safeParse(req.body);
96
+ if (!result.success) {
97
+ return res.status(422).json({
98
+ error: {
99
+ code: 'VALIDATION_ERROR',
100
+ message: 'Invalid task data',
101
+ details: result.error.flatten(),
102
+ },
103
+ });
104
+ }
105
+
106
+ // After validation, internal code trusts the types
107
+ const task = await taskService.create(result.data);
108
+ return res.status(201).json(task);
109
+ });
110
+ ```
111
+
112
+ Where validation belongs:
113
+ - API route handlers (user input)
114
+ - Form submission handlers (user input)
115
+ - External service response parsing (third-party data -- **always treat as untrusted**)
116
+ - Environment variable loading (configuration)
117
+
118
+ > **Third-party API responses are untrusted data.** Validate their shape and content before using them in any logic, rendering, or decision-making. A compromised or misbehaving external service can return unexpected types, malicious content, or instruction-like text.
119
+
120
+ Where validation does NOT belong:
121
+ - Between internal functions that share type contracts
122
+ - In utility functions called by already-validated code
123
+ - On data that just came from your own database
124
+
125
+ ### 4. Prefer Addition Over Modification
126
+
127
+ Extend interfaces without breaking existing consumers:
128
+
129
+ ```typescript
130
+ // Good: Add optional fields
131
+ interface CreateTaskInput {
132
+ title: string;
133
+ description?: string;
134
+ priority?: 'low' | 'medium' | 'high'; // Added later, optional
135
+ labels?: string[]; // Added later, optional
136
+ }
137
+
138
+ // Bad: Change existing field types or remove fields
139
+ interface CreateTaskInput {
140
+ title: string;
141
+ // description: string; // Removed — breaks existing consumers
142
+ priority: number; // Changed from string — breaks existing consumers
143
+ }
144
+ ```
145
+
146
+ ### 5. Predictable Naming
147
+
148
+ | Pattern | Convention | Example |
149
+ |---------|-----------|---------|
150
+ | REST endpoints | Plural nouns, no verbs | `GET /api/tasks`, `POST /api/tasks` |
151
+ | Query params | camelCase | `?sortBy=createdAt&pageSize=20` |
152
+ | Response fields | camelCase | `{ createdAt, updatedAt, taskId }` |
153
+ | Boolean fields | is/has/can prefix | `isComplete`, `hasAttachments` |
154
+ | Enum values | UPPER_SNAKE | `"IN_PROGRESS"`, `"COMPLETED"` |
155
+
156
+ ### 6. Honouring an Idempotency Key
157
+
158
+ Accepting an `Idempotency-Key` is the contract. Honouring it is the implementation, and it is where the money is lost — a key the server accepts but handles carelessly is worse than no key at all, because the client now believes retrying is safe.
159
+
160
+ **Derive the key from the intent, not the attempt.** The key must be stable across retries of one intent and different across distinct intents:
161
+
162
+ ```typescript
163
+ crypto.randomUUID() // ✗ new key per attempt — every retry is a new charge
164
+ `${userId}:${amount}` // ✗ two legitimate $50 charges collapse into one
165
+ `${orderId}:${Date.now()}` // ✗ a timestamp is randomUUID() wearing a hat
166
+
167
+ req.headers['idempotency-key'] // ✓ client generates once, reuses on retry
168
+ `charge:v1:${orderId}` // ✓ derived from an immutable identifier
169
+ ```
170
+
171
+ The key comes from the client or the initiating event — never from the layer doing the retrying.
172
+
173
+ **Claim atomically. A check followed by an act is a race:**
174
+
175
+ ```typescript
176
+ // ✗ TOCTOU: two concurrent retries both read "not seen", both charge
177
+ if (!(await db.exists(key))) {
178
+ await chargeCard(amount);
179
+ await db.insert(key);
180
+ }
181
+
182
+ // ✓ let the unique constraint pick the winner
183
+ try {
184
+ await db.insert({ key, state: 'in_progress', requestHash });
185
+ } catch (e) {
186
+ if (isUniqueViolation(e)) return replayOrReject(key);
187
+ throw e;
188
+ }
189
+ const result = await chargeCard(amount);
190
+ await db.update({ key, state: 'succeeded', response: result });
191
+ ```
192
+
193
+ The unique constraint *is* the mechanism. A store that cannot enforce uniqueness in one operation cannot back this.
194
+
195
+ **Guard the payload.** Same key with a different body is a client bug, and must fail loudly rather than serving the first response to a second request:
196
+
197
+ ```typescript
198
+ if (existing.requestHash !== hash(req.body)) {
199
+ return res.status(422).json({ error: 'idempotency key reused with a different payload' });
200
+ }
201
+ ```
202
+
203
+ **Decide what an in-flight duplicate gets.** The first request is still running when the second arrives — the common case under retry storms:
204
+
205
+ | Strategy | Response | Use when |
206
+ |---|---|---|
207
+ | Reject | `409 Conflict` | Client can retry later; simplest and safest |
208
+ | Wait | Block for the result, bounded | Caller needs it synchronously |
209
+ | Return pending | `202` + status URL | Long-running effects |
210
+
211
+ Never let the second caller through because the first "seems stuck". A stalled attempt whose fate is unknown is exactly when duplicating costs most.
212
+
213
+ **Every call has three outcomes, not two: success, failure, and _unknown_.** A timeout tells you nothing about whether the effect applied. Record the intent *before* calling out, so a crash between the call and the response leaves evidence something must resolve later — rather than a silently retried charge.
214
+
215
+ **Set retention from the longest retry chain**, not from disk cost. Keys must outlive every path that can re-deliver the same intent, including a dead-letter queue replayed a week later and any provider dispute window. A 24-hour key TTL behind a 7-day DLQ is a duplicate waiting to happen.
216
+
217
+ ## REST API Patterns
218
+
219
+ ### Resource Design
220
+
221
+ ```
222
+ GET /api/tasks → List tasks (with query params for filtering)
223
+ POST /api/tasks → Create a task
224
+ GET /api/tasks/:id → Get a single task
225
+ PATCH /api/tasks/:id → Update a task (partial)
226
+ DELETE /api/tasks/:id → Delete a task
227
+
228
+ GET /api/tasks/:id/comments → List comments for a task (sub-resource)
229
+ POST /api/tasks/:id/comments → Add a comment to a task
230
+ ```
231
+
232
+ ### Pagination
233
+
234
+ Paginate list endpoints:
235
+
236
+ ```typescript
237
+ // Request
238
+ GET /api/tasks?page=1&pageSize=20&sortBy=createdAt&sortOrder=desc
239
+
240
+ // Response
241
+ {
242
+ "data": [...],
243
+ "pagination": {
244
+ "page": 1,
245
+ "pageSize": 20,
246
+ "totalItems": 142,
247
+ "totalPages": 8
248
+ }
249
+ }
250
+ ```
251
+
252
+ ### Filtering
253
+
254
+ Use query parameters for filters:
255
+
256
+ ```
257
+ GET /api/tasks?status=in_progress&assignee=user123&createdAfter=2025-01-01
258
+ ```
259
+
260
+ ### Partial Updates (PATCH)
261
+
262
+ Accept partial objects — only update what's provided:
263
+
264
+ ```typescript
265
+ // Only title changes, everything else preserved
266
+ PATCH /api/tasks/123
267
+ { "title": "Updated title" }
268
+ ```
269
+
270
+ ## TypeScript Interface Patterns
271
+
272
+ ### Use Discriminated Unions for Variants
273
+
274
+ ```typescript
275
+ // Good: Each variant is explicit
276
+ type TaskStatus =
277
+ | { type: 'pending' }
278
+ | { type: 'in_progress'; assignee: string; startedAt: Date }
279
+ | { type: 'completed'; completedAt: Date; completedBy: string }
280
+ | { type: 'cancelled'; reason: string; cancelledAt: Date };
281
+
282
+ // Consumer gets type narrowing
283
+ function getStatusLabel(status: TaskStatus): string {
284
+ switch (status.type) {
285
+ case 'pending': return 'Pending';
286
+ case 'in_progress': return `In progress (${status.assignee})`;
287
+ case 'completed': return `Done on ${status.completedAt}`;
288
+ case 'cancelled': return `Cancelled: ${status.reason}`;
289
+ }
290
+ }
291
+ ```
292
+
293
+ ### Input/Output Separation
294
+
295
+ ```typescript
296
+ // Input: what the caller provides
297
+ interface CreateTaskInput {
298
+ title: string;
299
+ description?: string;
300
+ }
301
+
302
+ // Output: what the system returns (includes server-generated fields)
303
+ interface Task {
304
+ id: string;
305
+ title: string;
306
+ description: string | null;
307
+ createdAt: Date;
308
+ updatedAt: Date;
309
+ createdBy: string;
310
+ }
311
+ ```
312
+
313
+ ### Use Branded Types for IDs
314
+
315
+ ```typescript
316
+ type TaskId = string & { readonly __brand: 'TaskId' };
317
+ type UserId = string & { readonly __brand: 'UserId' };
318
+
319
+ // Prevents accidentally passing a UserId where a TaskId is expected
320
+ function getTask(id: TaskId): Promise<Task> { ... }
321
+ ```
322
+
323
+ ## Common Rationalizations
324
+
325
+ | Rationalization | Reality |
326
+ |---|---|
327
+ | "We'll document the API later" | The types ARE the documentation. Define them first. |
328
+ | "We don't need pagination for now" | You will the moment someone has 100+ items. Add it from the start. |
329
+ | "PATCH is complicated, let's just use PUT" | PUT requires the full object every time. PATCH is what clients actually want. |
330
+ | "We'll version the API when we need to" | Breaking changes without versioning break consumers. Design for extension from the start. |
331
+ | "Nobody uses that undocumented behavior" | Hyrum's Law: if it's observable, somebody depends on it. Treat every public behavior as a commitment. |
332
+ | "We can just maintain two versions" | Multiple versions multiply maintenance cost and create diamond dependency problems. Prefer the One-Version Rule. |
333
+ | "Internal APIs don't need contracts" | Internal consumers are still consumers. Contracts prevent coupling and enable parallel work. |
334
+ | "Accepting the Idempotency-Key header is enough" | The header is the contract; storing the key against the result is the implementation. A key you accept but don't honour tells the client retrying is safe when it isn't. |
335
+ | "Our queue guarantees exactly-once delivery" | No queue does across a consumer crash — the broker's ack and your side effect are not in one transaction. Design for at-least-once with idempotent processing. |
336
+ | "Duplicate requests are rare" | They're *correlated*. Retries spike exactly when a dependency is degraded — the moment duplicates are most likely and most expensive. |
337
+
338
+ ## Red Flags
339
+
340
+ - Endpoints that return different shapes depending on conditions
341
+ - Inconsistent error formats across endpoints
342
+ - Validation scattered throughout internal code instead of at boundaries
343
+ - Breaking changes to existing fields (type changes, removals)
344
+ - List endpoints without pagination
345
+ - Verbs in REST URLs (`/api/createTask`, `/api/getUsers`)
346
+ - Third-party API responses used without validation or sanitization
347
+ - A `SELECT` for an idempotency key followed by an `INSERT` — that's a race, not a guard
348
+ - An idempotency key derived from a UUID, timestamp, or anything else regenerated per attempt
349
+ - The same key accepted with a different request body, silently returning the first response
350
+ - A key retention window shorter than the longest path that can re-deliver the request
351
+
352
+ ## Verification
353
+
354
+ After designing an API:
355
+
356
+ - [ ] Every endpoint has typed input and output schemas
357
+ - [ ] Error responses follow a single consistent format
358
+ - [ ] Validation happens at system boundaries only
359
+ - [ ] List endpoints support pagination
360
+ - [ ] New fields are additive and optional (backward compatible)
361
+ - [ ] Naming follows consistent conventions across all endpoints
362
+ - [ ] API documentation or types are committed alongside the implementation
363
+ - [ ] State-changing endpoints either honour an idempotency key or are documented as unsafe to retry
364
+ - [ ] The key is claimed in one atomic operation, guarded by a unique constraint
365
+ - [ ] A reused key with a different payload fails loudly rather than replaying the wrong response
366
+ - [ ] The in-flight-duplicate response is a deliberate choice (409, wait, or 202) rather than whatever falls out
367
+ - [ ] Key retention outlives the longest retry path, including dead-letter replay