kitskill 0.0.0-stage → 0.1.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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +397 -2
  3. package/THIRD-PARTY-NOTICES.md +24 -0
  4. package/banner.jpeg +0 -0
  5. package/bin/cli.mjs +464 -0
  6. package/lib/fs-safe.mjs +136 -0
  7. package/lib/hook.mjs +79 -0
  8. package/lib/installer.mjs +449 -0
  9. package/lib/manifest.mjs +47 -0
  10. package/lib/permissions.mjs +175 -0
  11. package/lib/profile.mjs +124 -0
  12. package/lib/project-scan.mjs +186 -0
  13. package/lib/validator.mjs +72 -0
  14. package/logo.png +0 -0
  15. package/logohead.png +0 -0
  16. package/package.json +54 -4
  17. package/templates/core/memory/PROJECT.md +33 -0
  18. package/templates/core/memory/decisions/ADR.md +22 -0
  19. package/templates/core/profile.json +17 -0
  20. package/templates/core/router.md +89 -0
  21. package/templates/core/state/STATE.md +32 -0
  22. package/templates/opencode/policy-plugin.js +66 -0
  23. package/templates/scripts/graph-client.mjs +231 -0
  24. package/templates/scripts/review-packet.mjs +250 -0
  25. package/templates/scripts/shrink-output.mjs +159 -0
  26. package/templates/scripts/ui-audit.mjs +639 -0
  27. package/templates/scripts/verify.mjs +293 -0
  28. package/templates/skills/ks-api/SKILL.md +87 -0
  29. package/templates/skills/ks-api/references/api-contract.md +131 -0
  30. package/templates/skills/ks-build/SKILL.md +92 -0
  31. package/templates/skills/ks-data/SKILL.md +81 -0
  32. package/templates/skills/ks-data/references/data-migrations.md +120 -0
  33. package/templates/skills/ks-deliver/SKILL.md +99 -0
  34. package/templates/skills/ks-deliver/references/doc-patterns.md +180 -0
  35. package/templates/skills/ks-design/SKILL.md +147 -0
  36. package/templates/skills/ks-design/references/app-models.md +216 -0
  37. package/templates/skills/ks-design/references/design-contract.md +98 -0
  38. package/templates/skills/ks-design/references/visual-directions.md +159 -0
  39. package/templates/skills/ks-plan/SKILL.md +84 -0
  40. package/templates/skills/ks-review/SKILL.md +71 -0
  41. package/templates/skills/ks-secure/SKILL.md +55 -0
@@ -0,0 +1,293 @@
1
+ #!/usr/bin/env node
2
+ import { createHash } from 'node:crypto';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { existsSync, readFileSync } from 'node:fs';
5
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+
9
+ export const VERIFICATION_SCHEMA = 1;
10
+ export const CONFIG_PATH = '.kitskill/verify.json';
11
+ export const EVIDENCE_PATH = '.kitskill/verification.json';
12
+ export const REPORT_PATH = '.kitskill/state/VERIFICATION.md';
13
+ const DEFAULT_TIMEOUT_MS = 120_000;
14
+ const DEFAULT_LEVEL = 2;
15
+ const NORMAL_LEVEL = 2;
16
+ const SENSITIVE_PATH = /(^|\/)(auth|authz|security|payment|billing|migrations?|schema|openapi|secrets?|\.env)(\/|\.|$)/i;
17
+ const IGNORED_PATH = /(^|\/)(\.kitskill|\.agents|\.opencode|\.claude)\//;
18
+ const IGNORED_FILE = /^(AGENTS\.md|CLAUDE\.md|opencode\.jsonc?)$/;
19
+
20
+ function isIgnored(file) {
21
+ return IGNORED_PATH.test(file) || IGNORED_FILE.test(file);
22
+ }
23
+
24
+ function normalizeConfig(raw) {
25
+ if (!raw || typeof raw !== 'object') {
26
+ throw new Error('verify.json must be an object');
27
+ }
28
+ const timeoutMs =
29
+ Number.isInteger(raw.timeoutMs) && raw.timeoutMs > 0 ? raw.timeoutMs : DEFAULT_TIMEOUT_MS;
30
+ const hookLevel =
31
+ raw.hookLevel === 'auto' ||
32
+ (Number.isInteger(raw.hookLevel) && raw.hookLevel >= 0 && raw.hookLevel <= 3)
33
+ ? raw.hookLevel
34
+ : DEFAULT_LEVEL;
35
+ const entries = [];
36
+ if (Array.isArray(raw.checks)) {
37
+ for (const item of raw.checks) {
38
+ if (!item || typeof item !== 'object') {
39
+ throw new Error('each check must be an object');
40
+ }
41
+ entries.push({
42
+ name: item.name,
43
+ command: item.command,
44
+ timeoutMs: item.timeoutMs ?? timeoutMs,
45
+ level: item.level ?? DEFAULT_LEVEL,
46
+ });
47
+ }
48
+ } else if (raw.checks && typeof raw.checks === 'object') {
49
+ for (const [name, value] of Object.entries(raw.checks)) {
50
+ entries.push({
51
+ name,
52
+ command: typeof value === 'string' ? value : value?.command,
53
+ timeoutMs: typeof value === 'object' ? value?.timeoutMs ?? timeoutMs : timeoutMs,
54
+ level: typeof value === 'object' ? value?.level ?? DEFAULT_LEVEL : DEFAULT_LEVEL,
55
+ });
56
+ }
57
+ } else {
58
+ throw new Error('checks must be an object or an array');
59
+ }
60
+
61
+ const checks = entries.map((entry) => {
62
+ const name = String(entry.name ?? '').trim();
63
+ const command = String(entry.command ?? '').trim();
64
+ if (!name || !command) {
65
+ throw new Error('every check needs a name and a command');
66
+ }
67
+ if (!Number.isInteger(entry.timeoutMs) || entry.timeoutMs <= 0) {
68
+ throw new Error(`check "${name}" has an invalid timeoutMs`);
69
+ }
70
+ if (!Number.isInteger(entry.level) || entry.level < 1 || entry.level > 3) {
71
+ throw new Error(`check "${name}" has an invalid level`);
72
+ }
73
+ return { name, command, timeoutMs: entry.timeoutMs, level: entry.level };
74
+ });
75
+
76
+ if (checks.length === 0) {
77
+ throw new Error('no checks configured');
78
+ }
79
+ return { timeoutMs, hookLevel, checks };
80
+ }
81
+
82
+ function gitOutput(root, args) {
83
+ const run = spawnSync('git', args, { cwd: root, encoding: 'utf8' });
84
+ return run.status === 0 ? run.stdout : null;
85
+ }
86
+
87
+ export function changedSummary(root = process.cwd()) {
88
+ const status = gitOutput(root, ['status', '--porcelain']);
89
+ if (status === null) return null;
90
+ const files = new Set();
91
+ let lines = 0;
92
+ const numstat = gitOutput(root, ['diff', '--numstat', 'HEAD']);
93
+ if (numstat !== null) {
94
+ for (const row of numstat.split('\n')) {
95
+ const [added, removed, file] = row.split('\t');
96
+ if (!file || isIgnored(file)) continue;
97
+ files.add(file);
98
+ lines += (Number(added) || 0) + (Number(removed) || 0);
99
+ }
100
+ }
101
+ for (const row of status.split('\n')) {
102
+ if (!row.startsWith('?? ')) continue;
103
+ const file = row.slice(3).trim();
104
+ if (!file || isIgnored(file)) continue;
105
+ files.add(file);
106
+ try {
107
+ lines += readFileSync(path.join(root, file), 'utf8').split('\n').length;
108
+ } catch {
109
+ lines += 1;
110
+ }
111
+ }
112
+ return { files: files.size, lines, paths: [...files] };
113
+ }
114
+
115
+ export function detectLevel(summary) {
116
+ if (!summary || summary.files === 0) return 0;
117
+ if (summary.paths.some((file) => SENSITIVE_PATH.test(file))) return 3;
118
+ if (summary.files <= 1 && summary.lines <= 20) return 1;
119
+ return NORMAL_LEVEL;
120
+ }
121
+
122
+ export async function loadConfig(root = process.cwd()) {
123
+ const file = path.join(root, CONFIG_PATH);
124
+ if (!existsSync(file)) {
125
+ throw new Error(
126
+ `missing ${CONFIG_PATH}; add {"checks":{"test":"npm test"}}`,
127
+ );
128
+ }
129
+ let raw;
130
+ try {
131
+ raw = JSON.parse(await readFile(file, 'utf8'));
132
+ } catch (error) {
133
+ throw new Error(`${CONFIG_PATH} is not valid JSON: ${error.message}`);
134
+ }
135
+ return normalizeConfig(raw);
136
+ }
137
+
138
+ function shellCommand(command) {
139
+ return process.platform === 'win32'
140
+ ? { file: 'cmd.exe', args: ['/d', '/s', '/c', command] }
141
+ : { file: '/bin/sh', args: ['-c', command] };
142
+ }
143
+
144
+ function runCheck(check, root) {
145
+ const started = Date.now();
146
+ const { file, args } = shellCommand(check.command);
147
+ const run = spawnSync(file, args, {
148
+ cwd: root,
149
+ encoding: 'utf8',
150
+ timeout: check.timeoutMs,
151
+ maxBuffer: 10 * 1024 * 1024,
152
+ });
153
+ const durationMs = Date.now() - started;
154
+ const timedOut =
155
+ run.error?.code === 'ETIMEDOUT' ||
156
+ (run.signal === 'SIGTERM' && durationMs >= check.timeoutMs - 100);
157
+ const stdout = run.stdout ?? '';
158
+ const stderr = run.stderr ?? '';
159
+ const digest = createHash('sha256').update(stdout).update(stderr).digest('hex');
160
+ return {
161
+ name: check.name,
162
+ command: check.command,
163
+ ok: !timedOut && run.status === 0,
164
+ exitCode: run.status ?? (timedOut ? 124 : 1),
165
+ timedOut,
166
+ durationMs,
167
+ digest,
168
+ stdoutBytes: Buffer.byteLength(stdout),
169
+ stderrBytes: Buffer.byteLength(stderr),
170
+ };
171
+ }
172
+
173
+ function renderReport(evidence) {
174
+ const lines = [
175
+ '# Verification',
176
+ '',
177
+ `Generated: ${evidence.generatedAt}`,
178
+ `Level: ${evidence.level} (${evidence.levelSource})`,
179
+ `Result: ${evidence.ok ? 'PASS' : 'FAIL'}`,
180
+ '',
181
+ '| Check | Result | Duration | Digest |',
182
+ '|---|---|---:|---|',
183
+ ];
184
+ for (const check of evidence.checks) {
185
+ lines.push(
186
+ `| ${check.name} | ${check.ok ? 'PASS' : 'FAIL'} | ${check.durationMs} ms | \`${check.digest.slice(0, 12)}\` |`,
187
+ );
188
+ }
189
+ if (evidence.skipped.length > 0) {
190
+ lines.push('');
191
+ lines.push(
192
+ `Skipped by level: ${evidence.skipped.map((item) => `${item.name} (${item.level})`).join(', ')}`,
193
+ );
194
+ }
195
+ lines.push('');
196
+ lines.push('Evidence is a digest only; command output is not stored.');
197
+ return `${lines.join('\n')}\n`;
198
+ }
199
+
200
+ export async function runVerify(root = process.cwd(), { config, level } = {}) {
201
+ const resolved = config ?? (await loadConfig(root));
202
+ let requested;
203
+ let levelSource = 'explicit';
204
+ if (level === 'auto' || (level === undefined && resolved.hookLevel === 'auto')) {
205
+ const summary = changedSummary(root);
206
+ requested = detectLevel(summary);
207
+ levelSource = 'auto';
208
+ if (summary === null) {
209
+ requested = resolved.hookLevel === 'auto' ? DEFAULT_LEVEL : resolved.hookLevel;
210
+ levelSource = 'fallback';
211
+ }
212
+ } else if (Number.isInteger(level) && level >= 0 && level <= 3) {
213
+ requested = level;
214
+ } else {
215
+ requested = resolved.hookLevel ?? DEFAULT_LEVEL;
216
+ levelSource = 'config';
217
+ }
218
+ const selected = resolved.checks.filter((check) => check.level <= requested);
219
+ const skipped = resolved.checks
220
+ .filter((check) => check.level > requested)
221
+ .map((check) => ({ name: check.name, level: check.level }));
222
+ const checks = selected.map((check) => runCheck(check, root));
223
+ const passed = checks.filter((check) => check.ok).length;
224
+ const evidence = {
225
+ schema: VERIFICATION_SCHEMA,
226
+ generatedAt: new Date().toISOString(),
227
+ level: requested,
228
+ levelSource,
229
+ ok: passed === checks.length,
230
+ checks,
231
+ skipped,
232
+ summary: {
233
+ total: checks.length,
234
+ passed,
235
+ failed: checks.length - passed,
236
+ skipped: skipped.length,
237
+ },
238
+ };
239
+ await mkdir(path.join(root, '.kitskill/state'), { recursive: true });
240
+ await writeFile(
241
+ path.join(root, EVIDENCE_PATH),
242
+ `${JSON.stringify(evidence, null, 2)}\n`,
243
+ 'utf8',
244
+ );
245
+ await writeFile(path.join(root, REPORT_PATH), renderReport(evidence), 'utf8');
246
+ return evidence;
247
+ }
248
+
249
+ async function main(argv) {
250
+ const json = argv.includes('--json');
251
+ const quiet = argv.includes('--quiet');
252
+ const levelIndex = argv.indexOf('--level');
253
+ const levelValue = levelIndex >= 0 ? argv[levelIndex + 1] : undefined;
254
+ const level =
255
+ levelValue === 'auto'
256
+ ? 'auto'
257
+ : levelValue === undefined
258
+ ? undefined
259
+ : Number.parseInt(levelValue, 10);
260
+ let evidence;
261
+ try {
262
+ evidence = await runVerify(process.cwd(), { level });
263
+ } catch (error) {
264
+ process.stderr.write(`kitskill verify: ${error.message}\n`);
265
+ return 2;
266
+ }
267
+ if (json) {
268
+ process.stdout.write(`${JSON.stringify(evidence, null, 2)}\n`);
269
+ } else if (!quiet) {
270
+ for (const check of evidence.checks) {
271
+ process.stdout.write(
272
+ `${check.ok ? 'PASS' : 'FAIL'} ${check.name} (${check.durationMs} ms)\n`,
273
+ );
274
+ }
275
+ process.stdout.write(
276
+ `${evidence.ok ? 'PASS' : 'FAIL'} verification: ` +
277
+ `${evidence.summary.passed}/${evidence.summary.total}` +
278
+ (evidence.summary.skipped > 0 ? ` (${evidence.summary.skipped} skipped)` : '') +
279
+ ` at level ${evidence.level}\n`,
280
+ );
281
+ }
282
+ return evidence.ok ? 0 : 1;
283
+ }
284
+
285
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
286
+ main(process.argv.slice(2)).then(
287
+ (code) => process.exit(code),
288
+ (error) => {
289
+ process.stderr.write(`${error.stack ?? error.message}\n`);
290
+ process.exit(1);
291
+ },
292
+ );
293
+ }
@@ -0,0 +1,87 @@
1
+ ---
2
+ name: ks-api
3
+ description: "Design, change, review, or document an API contract. Use when adding or changing an endpoint, defining resources, errors, pagination, auth, versioning, or API docs."
4
+ license: MIT
5
+ ---
6
+
7
+ # ks-api
8
+
9
+ Design the contract before the implementation, then prove the implementation and
10
+ the contract agree.
11
+
12
+ ## When to use
13
+
14
+ - A new API or a new endpoint with consumers.
15
+ - A change to a public or shared contract.
16
+ - Errors, pagination, auth, versioning, or API documentation.
17
+ - An API review before implementation or release.
18
+
19
+ Skip for a purely internal function call with no external contract.
20
+
21
+ ## Procedure
22
+
23
+ 1. **Name the consumers and the job.** Who calls it, from where, how often, and
24
+ what must they accomplish? A public API, a mobile app, and a server-to-server
25
+ call have different contracts.
26
+ 2. **Choose the style.** REST/JSON is the default. Use GraphQL, RPC, or events
27
+ only when the access pattern or transport justifies it.
28
+ 3. **Model resources by domain.** Use plural nouns for collections, methods for
29
+ actions, and avoid exposing database tables. Put actions that do not fit CRUD
30
+ in a small number of explicit endpoints.
31
+ 4. **Define the contract.** For a public API or one consumed by another app/team,
32
+ write OpenAPI 3.1 with JSON Schema and keep it versioned with the code. For a
33
+ solo full-stack app with no separate consumer, a typed schema or shared type
34
+ is enough. Use AsyncAPI for event channels.
35
+ 5. **Define errors.** Use RFC 9457 `application/problem+json` (`type`, `title`,
36
+ `status`, `detail`, `instance`). Add field errors where useful. Never return
37
+ stacks, secrets, or internal identifiers.
38
+ 6. **Define collections.** For small stable sets, `limit`/`offset` is enough. For
39
+ large or mutable sets, use cursor pagination. Allowlist filters and sort
40
+ fields; cap page size.
41
+ 7. **Make retries safe.** Use idempotency keys for unsafe retryable writes such
42
+ as payments and orders. Use `ETag`/`If-Match` for lost-update protection.
43
+ 8. **Secure it.** HTTPS everywhere; OAuth2/OIDC or the framework's session for
44
+ users; API keys only for server-to-server. Enforce object-level authorization,
45
+ payload limits, rate limits, and input validation. Keep secrets out of code
46
+ and URLs.
47
+ 9. **Version only when needed.** Version public/consumed APIs; add optional
48
+ fields compatibly; deprecate with an announced window. Internal APIs can
49
+ evolve with the app.
50
+ 10. **Make it observable.** Structured logs with a request ID; latency and error
51
+ metrics per endpoint; never log tokens, PII, or secrets.
52
+ 11. **Test the contract.** Integration tests for real behavior; contract tests
53
+ when consumers are separate; schema validation and breaking-change checks in
54
+ CI.
55
+ 12. **Generate reference docs from the contract.** Add a quickstart and examples
56
+ separately; do not hand-maintain a duplicate endpoint list.
57
+
58
+ ## Small-project defaults
59
+
60
+ - REST/JSON; OpenAPI only when another consumer exists.
61
+ - One error shape; one pagination style.
62
+ - Idempotency for money and retryable writes, not every endpoint.
63
+ - Framework auth before custom auth.
64
+ - Structured logs and basic metrics before a full observability stack.
65
+ - Versioning after the first external consumer, not before.
66
+
67
+ ## Output
68
+
69
+ - Consumers, style, and resource model.
70
+ - Contract path and format; errors, pagination, auth, versioning.
71
+ - Tests and evidence.
72
+ - Anything `UNVERIFIED`.
73
+
74
+ ## Anti-patterns
75
+
76
+ - Endpoint names that are verbs or mirror database tables.
77
+ - `200 OK` for every outcome.
78
+ - Returning raw exceptions or internal IDs.
79
+ - Offset pagination on a large mutable table.
80
+ - Retrying a POST that creates duplicates.
81
+ - A public API with no contract or versioning plan.
82
+ - Adding an API gateway, portal, or governance board for a solo project.
83
+
84
+ ## Reference
85
+
86
+ `references/api-contract.md` has the checklists, status table, error shape,
87
+ pagination and idempotency patterns, and the review list.
@@ -0,0 +1,131 @@
1
+ # API contract reference
2
+
3
+ Use this after `ks-api` has identified consumers and style. Keep the contract
4
+ smaller than the implementation, not larger.
5
+
6
+ ## Style choice
7
+
8
+ | Need | Default | Use something else when |
9
+ |---|---|---|
10
+ | CRUD over business resources | REST/JSON | The client needs flexible graph queries (GraphQL) or a typed RPC contract (gRPC) |
11
+ | Server-to-server command | REST or RPC | Low latency and streaming justify gRPC |
12
+ | Events, queues, streams | AsyncAPI contract | The transport is a simple webhook with no consumers beyond one |
13
+ | Solo full-stack app | Typed schema/shared type | A second app/team consumes it, then add OpenAPI |
14
+
15
+ ## Resource and URL rules
16
+
17
+ - Collections are plural nouns: `/orders`, `/orders/{id}`, `/orders/{id}/items`.
18
+ - Do not put verbs in paths when HTTP already has the verb.
19
+ - Keep nesting to about two levels; link to deeper resources.
20
+ - Model business resources, not tables. Do not expose join tables or internal IDs.
21
+ - Use lowercase kebab-case for path segments; be consistent.
22
+ - Use UUID/opaque string IDs unless the domain has a safe natural key.
23
+
24
+ ## Methods and status
25
+
26
+ | Method | Meaning | Success |
27
+ |---|---|---|
28
+ | GET | Read, no side effect | 200 |
29
+ | POST | Create or submit; may be non-idempotent | 201 + Location, or 202 |
30
+ | PUT | Full replace, idempotent | 200/204 |
31
+ | PATCH | Partial update | 200/204 |
32
+ | DELETE | Remove, idempotent | 204, or 404 if it never existed |
33
+
34
+ Errors: 400 malformed/invalid, 401 unauthenticated, 403 forbidden, 404 missing,
35
+ 409 conflict, 412 precondition failed, 413 too large, 422 semantic validation,
36
+ 429 rate limited, 5xx server. Do not return 200 for failures.
37
+
38
+ ## Problem details
39
+
40
+ Use RFC 9457 `application/problem+json`:
41
+
42
+ ```json
43
+ {
44
+ "type": "https://example.com/problems/insufficient-funds",
45
+ "title": "Insufficient funds",
46
+ "status": 422,
47
+ "detail": "The account has R$ 10,00; the transfer needs R$ 25,00.",
48
+ "instance": "/transfers/01J...",
49
+ "errors": [
50
+ { "field": "amount", "code": "gt_balance", "message": "Amount exceeds balance." }
51
+ ]
52
+ }
53
+ ```
54
+
55
+ Never expose stacks, SQL, secrets, internal hostnames, or another user's data.
56
+
57
+ ## Collections
58
+
59
+ - Small, stable sets: `limit` + `offset`, cap `limit` (for example 100).
60
+ - Large or mutable sets: cursor pagination. Return `nextCursor` and an opaque
61
+ cursor; do not use offset on a changing table.
62
+ - Allowlist filters and sort fields. Reject unknown fields.
63
+ - Return a stable total only when cheap; otherwise omit it.
64
+ - Empty page is a normal 200, not 404.
65
+
66
+ ## Idempotency and concurrency
67
+
68
+ - Unsafe retryable writes (payments, orders, transfers) accept an
69
+ `Idempotency-Key`; store the key and the response for a defined window.
70
+ - Duplicate key returns the original result, not a second side effect.
71
+ - Use `ETag` + `If-Match` for lost-update protection; return 412 on mismatch.
72
+ - Do not make every POST idempotent with a database table unless retries are a
73
+ real risk; start with money and external side effects.
74
+
75
+ ## Auth and limits
76
+
77
+ - HTTPS everywhere.
78
+ - User-facing apps: OAuth2/OIDC or the framework session; do not build custom
79
+ login/token crypto.
80
+ - Server-to-server: short-lived tokens or API keys in headers, never URLs.
81
+ - Authorize each object: a valid token is not permission to read another user's
82
+ record. Check ownership/tenant on every read and write.
83
+ - Rate limit by token/IP/tenant; return 429 with `Retry-After`.
84
+ - Cap payload size, array length, string length, and upload size.
85
+ - Validate input against the schema; reject unknown fields or ignore them
86
+ explicitly.
87
+
88
+ ## Versioning
89
+
90
+ - Add optional fields compatibly.
91
+ - Version public/consumed APIs; URL prefix (`/v1`) or a documented header.
92
+ - Announce deprecation, keep a migration window, and document the replacement.
93
+ - Internal APIs can move with the app; do not create version ceremony for a solo
94
+ app with one consumer.
95
+ - Check breaking changes in CI when an OpenAPI contract exists.
96
+
97
+ ## Observability
98
+
99
+ - Log request ID, route, status, latency, and tenant/user ID where safe.
100
+ - Do not log tokens, passwords, full PII, or request bodies with secrets.
101
+ - Emit latency and error counts per endpoint; add tracing when there are multiple
102
+ services, not by default for a monolith.
103
+
104
+ ## Tests
105
+
106
+ - Integration test each endpoint against a realistic database or container.
107
+ - Contract test when a separate consumer exists; otherwise validate the OpenAPI
108
+ schema and examples in CI.
109
+ - Test authz for another user's object, validation errors, empty pages, duplicate
110
+ idempotency keys, rate limit, and 5xx masking.
111
+ - Keep E2E for critical flows only.
112
+
113
+ ## Review checklist
114
+
115
+ - [ ] Consumers and style are named.
116
+ - [ ] Resources are business nouns, not tables.
117
+ - [ ] Methods and status codes are correct.
118
+ - [ ] Error shape is consistent and leaks nothing.
119
+ - [ ] Pagination/filter/sort are bounded.
120
+ - [ ] Retryable writes are safe; concurrency is handled.
121
+ - [ ] Authn, object-level authz, rate limits, payload limits are present.
122
+ - [ ] Versioning/deprecation is defined only where needed.
123
+ - [ ] Contract and implementation agree; tests cover failure paths.
124
+ - [ ] Reference docs are generated or linked from one source.
125
+
126
+ ## Small-project defaults
127
+
128
+ REST/JSON, one problem-details shape, cursor only for large sets, idempotency for
129
+ money, framework auth, basic logs/metrics, OpenAPI when another consumer exists.
130
+ Skip guilds, portals, API catalogs, service mesh, and mandatory Pact for a solo
131
+ project.
@@ -0,0 +1,92 @@
1
+ ---
2
+ name: ks-build
3
+ description: "Implement or debug a change with behavior-first tests and the smallest correct diff. Use for business logic, APIs, refactors, and bugs; reproduce first when the cause is unknown."
4
+ license: MIT
5
+ ---
6
+
7
+ # ks-build
8
+
9
+ Implement the agreed change without widening its scope.
10
+
11
+ ## When to use
12
+
13
+ - Planned or Structural work with acceptance criteria.
14
+ - A bug fix; prove the root cause first when it is not already established.
15
+ - A refactor that must preserve behavior.
16
+
17
+ Skip for unclear requirements (use `ks-plan`). If the cause is unknown, reproduce
18
+ and prove it before editing; see Debugging.
19
+
20
+ ## Before editing
21
+
22
+ 1. Read the target code, its callers, its tests, and the relevant contracts.
23
+ 2. Confirm the acceptance criteria and the mode.
24
+ 3. Find the closest existing pattern and reuse it instead of inventing a new one.
25
+ 4. If the change alters a public contract, state the impact before editing.
26
+
27
+ ## Procedure
28
+
29
+ 1. Write a failing test for the next behavior. Run it and confirm it fails for the
30
+ intended reason.
31
+ 2. Make the smallest change that passes.
32
+ 3. Run only the tests related to the touched files.
33
+ 4. Refactor only what the change touched; keep behavior fixed.
34
+ 5. Repeat for each acceptance criterion.
35
+ 6. Full suite at close for Planned/Structural; for Direct, focused tests plus
36
+ affected callers.
37
+
38
+ ## Test rules
39
+
40
+ - Test behavior and contracts, never private internals.
41
+ - A mock must match the real dependency's signature and failure modes.
42
+ - Do not assert on details a refactor may change.
43
+ - Every bug fix gets a regression test.
44
+ - Keep tests independent and fast.
45
+
46
+ ## Change rules
47
+
48
+ - No unrelated refactors, formatting sweeps, or dependency upgrades.
49
+ - No premature abstraction for a single use.
50
+ - No duplicated utility when the project already has one.
51
+ - Preserve existing error handling and logging conventions.
52
+ - Keep the diff reviewable: one concern per change.
53
+
54
+ ## Output
55
+
56
+ - What changed and why.
57
+ - Tests added or updated, with the command run.
58
+ - Anything left `UNVERIFIED`.
59
+
60
+ ## Exit criteria
61
+
62
+ - Acceptance criteria are covered by tests or evidence.
63
+ - Focused tests pass; the full suite passes or the failure is explained.
64
+ - No unrelated files changed.
65
+ - Public contract changes are documented.
66
+
67
+ ## Anti-patterns
68
+
69
+ - Writing code before a failing test.
70
+ - Mocking away the behavior under test.
71
+ - Fixing a symptom instead of the proven cause.
72
+ - Hiding a failure by skipping or weakening a test.
73
+
74
+ ## Debugging
75
+
76
+ Use this when the cause is unknown.
77
+
78
+ 1. Reproduce with the exact command, input, environment, and observed result. If
79
+ you cannot reproduce, say so and gather more evidence.
80
+ 2. Preserve the failing output; do not truncate the part that proves the failure.
81
+ 3. List hypotheses and rank them by evidence, not by convenience.
82
+ 4. Investigate one at a time; add temporary instrumentation and remove it.
83
+ 5. Prove the root cause: show why this input produces this result. Correlation is
84
+ not causation.
85
+ 6. Fix the cause, not the symptom.
86
+ 7. Add a regression test that fails without the fix.
87
+ 8. Rerun the reproducer, the focused tests, and the related suite.
88
+
89
+ No shotgun debugging; no disabling, skipping, or loosening a test; no speculative
90
+ dependency upgrades. If the evidence points outside the code (data, config,
91
+ environment), verify there. If two causes remain possible, report that instead of
92
+ guessing.
@@ -0,0 +1,81 @@
1
+ ---
2
+ name: ks-data
3
+ description: "Design or change a data model, schema, migration, backfill, index, or retention policy. Use when persistence, query patterns, data safety, or zero-downtime changes matter."
4
+ license: MIT
5
+ ---
6
+
7
+ # ks-data
8
+
9
+ Change the data layer without losing data, locking production, or guessing at
10
+ query patterns.
11
+
12
+ ## When to use
13
+
14
+ - A new data model, table, collection, relationship, or index.
15
+ - A schema migration, backfill, reshard, retention change, or restore.
16
+ - Data correctness, privacy, or query-performance work.
17
+
18
+ Skip for a read-only query with no schema or persistence change.
19
+
20
+ ## Procedure
21
+
22
+ 1. **Name the access patterns and constraints.** Reads, writes, volume, growth,
23
+ consistency, latency, retention, PII, and deployment target.
24
+ 2. **Choose the store.** SQL first (PostgreSQL or SQLite for small projects) when
25
+ relations and transactions matter. Use NoSQL only for a concrete access
26
+ pattern; do not add a second store without a measured reason.
27
+ 3. **Model the data.** Conceptual → logical → physical. Use correct types
28
+ (decimal for money, timestamptz for time), primary/foreign keys, constraints,
29
+ and explicit ownership. Model business entities; not every API shape needs a
30
+ table.
31
+ 4. **Plan the migration.** Versioned scripts, deterministic order, no manual
32
+ production DDL. Prefer additive changes; use expand-contract when the app must
33
+ run old and new code at the same time. Test on empty and realistic data.
34
+ 5. **Plan the backfill.** Idempotent, batched, checkpointed, throttled, and
35
+ validated by counts/checksums. Keep it separate from the schema migration and
36
+ resumable after failure.
37
+ 6. **Index by measurement.** Use `EXPLAIN`/query plans first. Index selective
38
+ filters, joins, and order; avoid indexing everything. Create large indexes
39
+ concurrently or online when the engine supports it.
40
+ 7. **Plan recovery.** Backup before destructive work; test restore. Prefer
41
+ roll-forward or a compensating migration over destructive down-migrations.
42
+ Define the abort signal and the runbook.
43
+ 8. **Test the data.** Constraints, empty/representative data, migration on a
44
+ fresh database, backfill idempotency, query plans, and restore.
45
+ 9. **Protect the data.** Least privilege, TLS, encryption at rest, PII
46
+ classification, retention, masked test data, and audit of destructive
47
+ operations.
48
+ 10. **Operate it.** Monitor locks, migration duration, replication lag, disk,
49
+ query latency, and failed jobs. Record the owner and the recovery steps.
50
+
51
+ ## Small-project defaults
52
+
53
+ - One SQL database; PostgreSQL or SQLite.
54
+ - Simple versioned migrations; expand-contract only when zero-downtime matters.
55
+ - Backfill in batches with a checkpoint; no parallel backfills on the same table.
56
+ - Indexes only for measured queries; no speculative index set.
57
+ - Daily backup + tested restore; no sharding, data lake, or streaming pipeline
58
+ unless the product needs it.
59
+
60
+ ## Output
61
+
62
+ - Store choice and data model.
63
+ - Migration order, backfill, indexes, and rollback/recovery.
64
+ - Tests and evidence.
65
+ - Anything `UNVERIFIED`.
66
+
67
+ ## Anti-patterns
68
+
69
+ - Manual production DDL or a migration without a backup.
70
+ - Renaming/dropping a column before old code is gone.
71
+ - Offset pagination/backfill over a changing table.
72
+ - `FLOAT` for money or local time without a zone.
73
+ - Creating many indexes without query plans.
74
+ - Treating cache as the source of truth.
75
+ - Adding NoSQL, sharding, or a data lake for a small CRUD app.
76
+ - Assuming a local migration will be fast on production data.
77
+
78
+ ## Reference
79
+
80
+ `references/data-migrations.md` has store selection, type rules, expand-contract,
81
+ backfill, index, backup, and review checklists.