@nurix/etna 0.18.22 → 0.18.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/harness-index.json +1 -5
- package/data/harnesses/code/CLAUDE.md +16 -27
- package/data/harnesses/code/harness.json +2 -2
- package/data/harnesses/code/rules/testing.md +1 -1
- package/data/harnesses/etna/CLAUDE.md +5 -14
- package/data/harnesses/etna/harness.json +2 -2
- package/data/harnesses/etna/rules/testing.md +1 -1
- package/package.json +1 -1
- package/data/harnesses/mobile/.prettierignore +0 -12
- package/data/harnesses/mobile/.prettierrc.json +0 -3
- package/data/harnesses/mobile/.vscode/settings.json +0 -10
- package/data/harnesses/mobile/CLAUDE.md +0 -151
- package/data/harnesses/mobile/agents/brainstorm.md +0 -35
- package/data/harnesses/mobile/agents/change-review.md +0 -251
- package/data/harnesses/mobile/agents/lld-mode.md +0 -56
- package/data/harnesses/mobile/agents/maintenance.md +0 -216
- package/data/harnesses/mobile/agents/performance-review.md +0 -223
- package/data/harnesses/mobile/harness.json +0 -11
- package/data/harnesses/mobile/hooks/generate-ownership-index.mjs +0 -148
- package/data/harnesses/mobile/hooks/hooks.json +0 -16
- package/data/harnesses/mobile/rules/database.md +0 -38
- package/data/harnesses/mobile/rules/general.md +0 -49
- package/data/harnesses/mobile/rules/nomenclature.md +0 -34
- package/data/harnesses/mobile/rules/nustack.md +0 -150
- package/data/harnesses/mobile/rules/react-native.md +0 -132
- package/data/harnesses/mobile/rules/testing.md +0 -25
- package/data/harnesses/mobile/rules/typescript.md +0 -40
- package/data/harnesses/mobile/skills/boundary/SKILL.md +0 -69
- package/data/harnesses/mobile/skills/boundary/references/index.md +0 -16
- package/data/harnesses/mobile/skills/boundary/references/mechanisms.md +0 -99
- package/data/harnesses/mobile/skills/boundary/references/packs/async-messaging.md +0 -81
- package/data/harnesses/mobile/skills/boundary/references/packs/auth.md +0 -93
- package/data/harnesses/mobile/skills/boundary/references/packs/build-config-runtime.md +0 -93
- package/data/harnesses/mobile/skills/boundary/references/packs/cloudflare.md +0 -93
- package/data/harnesses/mobile/skills/boundary/references/packs/frontend.md +0 -93
- package/data/harnesses/mobile/skills/boundary/references/packs/generic-tail.md +0 -55
- package/data/harnesses/mobile/skills/boundary/references/packs/persistence.md +0 -93
- package/data/harnesses/mobile/skills/boundary/references/packs/wire-api.md +0 -87
- package/data/harnesses/mobile/skills/brainstorm/README.md +0 -162
- package/data/harnesses/mobile/skills/brainstorm/SKILL.md +0 -152
- package/data/harnesses/mobile/skills/brainstorm/exit-artifacts.md +0 -66
- package/data/harnesses/mobile/skills/brainstorm/templates/backlog.md +0 -39
- package/data/harnesses/mobile/skills/brainstorm/templates/build.md +0 -37
- package/data/harnesses/mobile/skills/brainstorm/templates/decisions.md +0 -29
- package/data/harnesses/mobile/skills/brainstorm/templates/doctrine.md +0 -31
- package/data/harnesses/mobile/skills/brainstorm/templates/domain-model.md +0 -25
- package/data/harnesses/mobile/skills/brainstorm/templates/evidence.md +0 -24
- package/data/harnesses/mobile/skills/brainstorm/templates/glossary.md +0 -20
- package/data/harnesses/mobile/skills/brainstorm/templates/milestones.md +0 -43
- package/data/harnesses/mobile/skills/brainstorm/templates/non-goals.md +0 -17
- package/data/harnesses/mobile/skills/brainstorm/templates/plan-doc.md +0 -61
- package/data/harnesses/mobile/skills/brainstorm/templates/questions.md +0 -36
- package/data/harnesses/mobile/skills/brainstorm/templates/references.md +0 -28
- package/data/harnesses/mobile/skills/brainstorm/templates/rejected.md +0 -33
- package/data/harnesses/mobile/skills/brainstorm/templates/source-of-truth.md +0 -49
- package/data/harnesses/mobile/skills/brainstorm/templates/state.md +0 -1
- package/data/harnesses/mobile/skills/brainstorm/templates/tech.md +0 -23
- package/data/harnesses/mobile/skills/brainstorm/templates/thesis.md +0 -21
- package/data/harnesses/mobile/skills/documentation/SKILL.md +0 -172
- package/data/harnesses/mobile/skills/documentation/references/examples.md +0 -203
- package/data/harnesses/mobile/skills/documentation/references/style-guide.md +0 -315
- package/data/harnesses/mobile/skills/documentation/references/templates.md +0 -1091
- package/data/harnesses/mobile/skills/workflow-mapper/SKILL.md +0 -451
- package/data/harnesses/mobile/skills/workflow-mapper/references/patterns.md +0 -214
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
# Generic tail — technologies outside the mandated stack
|
|
2
|
-
|
|
3
|
-
Load when: the touched code exhibits one of these technologies and no dedicated pack covers it. Entries here are deliberately thin — one gotcha and the safe-change essence each; diagnose the rest from the mechanism (see `../mechanisms.md`). When the org adopts one of these seriously, promote its section into a full pack.
|
|
4
|
-
|
|
5
|
-
## API styles
|
|
6
|
-
|
|
7
|
-
- **graphql-schema — CRITICAL · serialized-shape.** The SDL is executed by clients you don't redeploy: removing/renaming a field, tightening output nullability, or removing an in-use enum value breaks live queries at execution. Safe: schema-diff check in CI (GraphQL Inspector / `rover graph check`); `@deprecated` + usage metrics before removal; regenerate client types every change. Federation directives (`@key`, `@external`, `@requires`, `@shareable`) add a cross-*team* facet: composition fails or takes down fields other subgraphs own.
|
|
8
|
-
- **graphql-persisted-queries — HIGH · generated-artifact.** The server executes only registered hashes; editing an operation without republishing the manifest → `PersistedQueryNotFound` for all traffic on that operation.
|
|
9
|
-
- **grpc-protobuf — CRITICAL · serialized-shape.** Field numbers identify fields on the wire and can never be reused — a reused number deserializes garbage with no error, across services on different `.proto` versions. Safe: `reserved` removed numbers; add with new numbers only; `buf breaking` in CI; never change wire type or cardinality in place.
|
|
10
|
-
- **trpc — HIGH · generated-artifact.** The exported `AppRouter` type is the contract; it holds only if client and server build from the same version — deploy skew breaks at runtime despite full type safety. Keep tRPC package versions identical on both sides; version procedures via sub-routers.
|
|
11
|
-
- **openapi-spec — HIGH · generated-artifact.** Spec↔server drift makes generated SDKs/mocks send wrong shapes, visible only at runtime. Regenerate spec-from-code (or code-from-spec) in one change; run a breaking-change linter (`oasdiff`) in CI.
|
|
12
|
-
- **cache-headers/cdn — HIGH · config-elsewhere.** The cache obeys the header you already sent: `immutable`/long `max-age` on non-hashed assets means users never update; caching a personalized response in a shared cache leaks it; any header the response branches on must appear in `Vary` (and never `Vary: Authorization` on a shared cache). Deploys need a purge step.
|
|
13
|
-
|
|
14
|
-
## Event/stream platforms
|
|
15
|
-
|
|
16
|
-
- **kafka-consumer-groups — CRITICAL · rendezvous-string + lifecycle-protocol.** The group id owns the committed offset: renaming a group restarts from `auto.offset.reset` — `earliest` reprocesses everything, `latest` skips the backlog, both silently. Rewind via explicit offset reset, never a group rename.
|
|
17
|
-
- **schema-registry — CRITICAL · serialized-shape.** The compatibility mode (BACKWARD/FORWARD/FULL/TRANSITIVE) defines which producer/consumer upgrade orders are safe; Avro fields without defaults and Protobuf number reuse break consumers fleet-wide. CI-enforce a mode; every new Avro field gets a default.
|
|
18
|
-
- **cdc/debezium — CRITICAL · generated-artifact.** The stream's shape derives from a source schema owned by a team that may not know consumers exist — a column rename silently reshapes the stream; a table rename relocates the topic. Treat CDC-source columns as a published contract; pin topic routing and `REPLICA IDENTITY`.
|
|
19
|
-
- **event-sourcing/audit tables — CRITICAL · serialized-shape + lifecycle-protocol.** Events are immutable and replayed: today's projector must read events written years ago. Version event types + upcast; never mutate history; test a full replay.
|
|
20
|
-
- **outbox/saga — HIGH · lifecycle-protocol.** The outbox table schema is co-owned by the writing transaction and the relay (columns additive; keep the relay mapping synced). Every forward saga step needs its compensation wired into the failure path — a mid-saga failure otherwise leaves money reserved and never released.
|
|
21
|
-
- **workflow-engines (Temporal etc.) — CRITICAL · lifecycle-protocol.** Running workflows replay their history through current code: adding/reordering an `await` on a command-producing call diverges replay and bricks in-flight executions while new-workflow tests pass. Gate logic changes with `patched()`/`getVersion()`; keep I/O in Activities; replay production histories in CI.
|
|
22
|
-
|
|
23
|
-
## Postgres deep end
|
|
24
|
-
|
|
25
|
-
- **rls-policies — CRITICAL · trust-invariant.** A new tenant table without a policy, a missing `FORCE`, an owner/`BYPASSRLS` connection, or a forgotten `SET LOCAL` silently returns all rows. Column + policy + `FORCE` land in one migration; app traffic runs under a non-owner role.
|
|
26
|
-
- **pooled-session-state — HIGH · lifecycle-protocol.** Under PgBouncer transaction pooling, session state (`SET`, prepared statements, advisory locks, RLS GUCs) is shared across clients: use `SET LOCAL` only and disable server-side prepared statements, or tenant context leaks across pooled connections.
|
|
27
|
-
- **collation/extensions — HIGH · config-elsewhere.** A schema object needs its extension installed before the migration that uses it (from-scratch deploys fail); a glibc/ICU collation change silently corrupts B-tree index order → wrong results and "duplicate" unique rows. Reindex after any collation-version change.
|
|
28
|
-
- **matviews/read-models — MED · generated-artifact.** Two contracts: the source schema the refresh reads (a source column change breaks it) and the read-model shape consumers query; `REFRESH … CONCURRENTLY` needs a unique index; staleness serves wrong data with no error.
|
|
29
|
-
|
|
30
|
-
## Frontend long tail
|
|
31
|
-
|
|
32
|
-
- **ssr-hydration — HIGH · serialized-shape.** Server markup must byte-match the client's first render (React 19: mismatch is a hard error discarding the server tree) and transferred state must survive serialization (`Date`/`Map`/`Set`/`undefined` don't, by default). Move non-determinism into effects; use superjson/devalue or explicit rehydration.
|
|
33
|
-
- **module-federation — CRITICAL · config-elsewhere.** Host and remotes deploy independently but must agree at runtime on exposed-module names and `shared` singleton versions — drift loads duplicate React and breaks hooks/context silently. `singleton: true` + `strictVersion` for framework libs; coordinate deploys.
|
|
34
|
-
- **i18n-keys — MED · rendezvous-string.** Key renamed in code but not catalogs shows the raw key; missing interpolation vars render literal `{{name}}`. CI-gate with a parser (`i18next-parser --ci`); generate key types.
|
|
35
|
-
- **analytics-tracking-plan — MED · rendezvous-string.** Renaming an event or property silently breaks dashboards/funnels and fragments history, with no app error. Centralize names in a typed module; add, deprecate, never rename.
|
|
36
|
-
- **feature-flags (hosted) — HIGH · rendezvous-string.** A deleted-but-still-referenced flag returns the SDK default (often `false`), silently hiding a shipped feature; off must always mean previous-safe-behavior so disabling is rollback. Two-step removal in distributed systems: make safe unconditionally → deploy everywhere → delete.
|
|
37
|
-
- **deep-links/oauth-callbacks — HIGH · rendezvous-string.** Links already sent in emails/push are irrecoverable, and OAuth providers allowlist exact callback URLs — a path change breaks both. Keep old paths redirecting; update provider allowlists and AASA/assetlinks in lockstep.
|
|
38
|
-
|
|
39
|
-
## Orchestrated runtime (K8s and friends)
|
|
40
|
-
|
|
41
|
-
- **health-probes — HIGH · rendezvous-string + lifecycle-protocol.** The orchestrator polls a path the app owns: rename `/healthz` and K8s CrashLoopBackOffs a healthy pod. Liveness = cheap process-only check (a DB blip in liveness kills the pod); readiness = critical deps and must fail immediately on SIGTERM or rolling deploys 502.
|
|
42
|
-
- **graceful-shutdown — HIGH · lifecycle-protocol.** Shell-form ENTRYPOINT swallows SIGTERM (signals hit the shell, not the app); a `preStop` sleep covers endpoint-propagation lag. On SIGTERM: fail readiness → stop new connections → drain → exit; grace period ≥ max request time.
|
|
43
|
-
- **resource-limits — HIGH · config-elsewhere.** The kernel enforces limits the app never sees: a bigger cache OOMKills (exit 137) with no app error; CPU limits throttle silently. Make heap settings cgroup-aware; re-evaluate limits when adding caches/deps.
|
|
44
|
-
- **service-discovery/ingress/tls — HIGH · rendezvous-string.** Service names, ingress path rules (order- and specificity-sensitive; rewrites must match mounted routes), and cert SANs each bind by exact string — a rename 404s/NXDOMAINs/fails handshake while the app stays healthy. Add hostnames to the cert SAN list before routing traffic.
|
|
45
|
-
- **mesh-resilience-budgets — HIGH · lifecycle-protocol.** Timeouts must nest (caller > callee × retries) or retries storm a recovering service; these configs live in a different repo/layer than the calling code.
|
|
46
|
-
- **iac-outputs — HIGH · rendezvous-string.** A consuming stack reads producer outputs by name (`terraform_remote_state`, `Fn::ImportValue`): rename/remove one and every consumer fails to plan. Outputs are public API — deprecate, don't rename.
|
|
47
|
-
- **trace/metrics/logs naming — MED · rendezvous-string.** Dashboards, alerts, and cross-service queries pin exact metric names, label keys, and log field names — a rename makes the alert go quiet, not fire. Deprecate, don't rename; never put unbounded cardinality in labels.
|
|
48
|
-
|
|
49
|
-
## Misc
|
|
50
|
-
|
|
51
|
-
- **di-containers — HIGH · rendezvous-string.** String/symbol tokens and registrations match at runtime only; a scope change (singleton↔request) silently shares state across requests/tenants. Typed tokens; treat scope as part of the contract.
|
|
52
|
-
- **worker/ipc boundaries — MED · serialized-shape.** Only structured-cloneable values cross `postMessage`/IPC — class instances lose methods, `instanceof` fails; a renamed IPC channel (`ipcMain.handle` vs `ipcRenderer.invoke`) silently no-ops. Version the message envelope; share channel constants.
|
|
53
|
-
- **object-storage keys — MED · rendezvous-string.** The key template is a contract among uploader, downloader, lifecycle rules, and DB pointers — changing it orphans existing objects (no FK between DB and bucket). Store the full key in the DB; migrate by copy/re-point.
|
|
54
|
-
- **saml — HIGH · config-elsewhere.** IdP signing-cert rotation without the SP re-importing metadata fails every assertion; a `NameID` format change re-keys identity and duplicates accounts. Overlap certs during rotation; pin identity on a stable identifier.
|
|
55
|
-
- **lambda-handler-envelopes — HIGH · serialized-shape.** The platform owns the event shape: API Gateway payload v1→v2 moves `event.httpMethod` to `event.requestContext.http.method`, existing parsing reads `undefined`. Pin the payload format version; validate the event at the handler.
|
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
# Pack: persistence & data model
|
|
2
|
-
|
|
3
|
-
Load when: the touch list exhibits Drizzle/D1/SQLite (`schema.ts`, `init.sql`, `sqliteTable(`, `drizzle-kit`), Postgres (`pgTable`, migrations, enums, pgvector), Redis caching, seeds (`*.seed.sql`, generators), or JSON columns.
|
|
4
|
-
|
|
5
|
-
## init-sql-drizzle-mirror-parity — CRITICAL · dual-authority
|
|
6
|
-
**Contract:** Hand-written canonical DDL (`db/seed/init.sql`) and the Drizzle mirror (`db/schema.ts`) independently declare the same tables/columns/indexes and must match byte-for-byte — the string in `sqliteTable("…")` and every index name equal the DDL.
|
|
7
|
-
**Detect:** `db/seed/init.sql`, `db/schema.ts`, `sqliteTable("`, `uniqueIndex("`, `index("`, `_idx`, `_unique`
|
|
8
|
-
**Ships green, breaks:** Each side validates only against itself — local/test DBs are typically built from `schema.ts` (push) while the real D1 is built from `init.sql`, so tests pass and prod 500s (`no such column`). Subtler drift is fully silent: a column present in DDL but missing from the mirror stays NULL forever (Drizzle never writes it); a DEFAULT that differs between the two gives Drizzle-inserted rows and seed rows different values; a drifted index *name* means a later `drizzle-kit push` DROPs the DDL's index and recreates it under the schema name — hand-tuned index definitions vanish.
|
|
9
|
-
**Safe change:** Edit both files in the same commit; run `npx drizzle-kit export --dialect=sqlite --schema=db/schema.ts` and diff the emitted DDL against `init.sql` (names, defaults, index names); alternatively apply `init.sql` to a scratch DB and confirm `drizzle-kit push` proposes zero statements; grep every `_idx`/`_unique` name on both sides.
|
|
10
|
-
|
|
11
|
-
## drizzle-push-vs-migrate-mixing — CRITICAL · generated-artifact
|
|
12
|
-
**Contract:** One database gets exactly one schema-application mechanism — either `drizzle-kit push` (stateless diff, schema.ts is total authority) or `generate`+`migrate` (journaled in `__drizzle_migrations`); the two do not compose.
|
|
13
|
-
**Detect:** `drizzle-kit push` in `package.json`/CI, `drizzle/` migrations folder, `__drizzle_migrations`, `tablesFilter` in `drizzle.config.ts`, `--force`
|
|
14
|
-
**Ships green, breaks:** `push` diffs schema.ts against the *entire* live DB and proposes `DROP TABLE` for anything not in schema.ts — including tables owned by other tools (Better Auth's `user`/`session`/`account`/`verification`, wrangler's `d1_migrations`); `push --force` in CI auto-approves those data-loss statements with no prompt. `push` records nothing in `__drizzle_migrations`, so a later `migrate` replays the whole folder against the already-pushed DB; `generate` diffs against its own snapshot journal, not the pushed DB, so the generated SQL silently disagrees with reality.
|
|
15
|
-
**Safe change:** Pick one workflow per database and enforce it in CI; set `tablesFilter` in `drizzle.config.ts` to only the tables Drizzle owns; never pass `--force` unattended; when converting push→migrate, generate a baseline migration and mark it applied before the first `migrate`.
|
|
16
|
-
|
|
17
|
-
## sqlite-alter-table-recreate — CRITICAL · lifecycle-protocol
|
|
18
|
-
**Contract:** SQLite `ALTER TABLE` only does RENAME TO / RENAME COLUMN / ADD COLUMN / DROP COLUMN — any type/NOT NULL/DEFAULT/constraint change makes drizzle-kit emit the rebuild dance (`PRAGMA foreign_keys=OFF` → `CREATE __new_<t>` → `INSERT INTO __new_ SELECT …` → `DROP TABLE` → `RENAME`), whose safety depends on FK state during execution.
|
|
19
|
-
**Detect:** `__new_` in `drizzle/*.sql`, `PRAGMA foreign_keys=OFF`, `PRAGMA defer_foreign_keys`, `ON DELETE CASCADE`, `__old_push_`
|
|
20
|
-
**Ships green, breaks:** `PRAGMA foreign_keys` is a no-op inside an open transaction — when the migration runs transaction-wrapped, the rebuild's `DROP TABLE` fires `ON DELETE CASCADE` and silently wipes every child table (a single column-default change has deleted all related rows, no error). On D1, `PRAGMA foreign_keys=OFF` is impossible entirely (every query is an implicit transaction); the sanctioned `PRAGMA defer_foreign_keys=on` defers checks but does NOT suppress `ON DELETE CASCADE`. Column-count mismatches in the copy step have left `__old_push_<t>` holding the data and the new table empty.
|
|
21
|
-
**Safe change:** Hand-review any generated migration containing `__new_`; on D1 add `PRAGMA defer_foreign_keys = on` as the first statement; back up (D1 Time Travel bookmark) before applying; assert child-table rowcounts after the rebuild.
|
|
22
|
-
|
|
23
|
-
## seed-regen-upsert-clobber — CRITICAL · dual-authority
|
|
24
|
-
**Contract:** Generated seed files (`db/seed/*.seed.sql`, UUIDv5 of the natural key, idempotent `ON CONFLICT(slug) DO UPDATE`) and the live DB co-own vocabulary rows — the generator owns `slug/label/description`, the runtime owns `count`, admins own `weight`.
|
|
25
|
-
**Detect:** `gen-seeds.mjs`, `gen-product-domains.mjs`, `*.seed.sql`, `ON CONFLICT(slug) DO UPDATE`, `excluded.count`, `excluded.weight`, `excluded.id`
|
|
26
|
-
**Ships green, breaks:** If the generator's `DO UPDATE SET` list ever includes `count`/`weight`/`id`/`created_at`, the next deploy's re-seed silently resets live drift counters and admin-tuned weights to CSV values — no error, data just reverts. Changing the uuid5 namespace or the natural-key string format re-mints every id: the slug-targeted upsert still matches, but `SET id = excluded.id` dangles every external record of the old UUIDs; if the conflict target were `id` instead of `slug`, re-seed duplicates the whole vocabulary. Mixing UUIDv7 (runtime, time-sortable) and UUIDv5 (seed, hash) ids also means `ORDER BY id` ≠ insertion order.
|
|
27
|
-
**Safe change:** Edit the CSV and rerun the generator, never the `.seed.sql`; diff the regenerated file for id churn before committing; keep `DO UPDATE SET` restricted to label/description/status and always exclude `count`, `weight`, `id`, `created_at`; treat the uuid5 key-format string as frozen API.
|
|
28
|
-
|
|
29
|
-
## pg-on-conflict-arbiter-index — CRITICAL · config-elsewhere
|
|
30
|
-
**Contract:** Every upsert's conflict target is backed by a live unique (or partial-unique) index declared in a migration far from the query; dedupe correctness lives in the index, not the code.
|
|
31
|
-
**Detect:** `onConflictDoUpdate`, `onConflictDoNothing`, `ON CONFLICT`, `INSERT OR IGNORE`, `uniqueIndex(`, `targetWhere`, `_unique`
|
|
32
|
-
**Ships green, breaks:** Targeted `ON CONFLICT (col) DO UPDATE` at least errors loudly if the constraint is dropped — but targetless `ON CONFLICT DO NOTHING` and SQLite `INSERT OR IGNORE` keep returning success and silently insert duplicates once the unique index is gone (e.g. a rebuild migration recreated the table with `_idx` instead of `_unique`). Partial unique indexes need the predicate restated for arbiter inference — in Drizzle, `onConflictDoUpdate({ target, targetWhere })` must repeat the index's `WHERE`; omit it and PG throws `there is no unique or exclusion constraint matching the ON CONFLICT specification` even though "the index exists".
|
|
33
|
-
**Safe change:** Before dropping/renaming any `_unique` index, grep for upserts naming those columns; prefer explicit conflict targets over targetless DO NOTHING; for partial indexes, mirror the predicate in `targetWhere`; after SQLite rebuild migrations, verify uniques survived (`PRAGMA index_list(<table>)`).
|
|
34
|
-
|
|
35
|
-
## d1-batch-not-a-transaction — HIGH · lifecycle-protocol
|
|
36
|
-
**Contract:** Code needing multi-statement atomicity on D1 must use `db.batch([...])` — D1 has no interactive transactions; `BEGIN`/`SAVEPOINT` are rejected and Drizzle's `db.transaction()` fails at runtime on the D1 driver.
|
|
37
|
-
**Detect:** `db.transaction(`, `BEGIN TRANSACTION`, sequential `await db.insert(…).run()` chains, `env.DB.batch`, `db.batch(`
|
|
38
|
-
**Ships green, breaks:** Sequential awaited writes read as transactional in review but each auto-commits — a mid-sequence failure leaves permanent partial writes with no rollback. `batch()` is atomic (a failing statement rolls back the sequence) but non-interactive: a later statement cannot branch on an earlier statement's result, so read-modify-write logic ported into a "batch transaction" carries a TOCTOU race between the pre-read and the batch. Code sharing a service layer with a Node/Postgres path (where `db.transaction` works) compiles and unit-tests green, then throws `D1_ERROR` only on the Workers runtime.
|
|
39
|
-
**Safe change:** Express each multi-write invariant as one `db.batch([...])`; hoist all reads before the batch and encode invariants as SQL conditions (`WHERE`-guarded UPDATE) instead of JS branches; never let `db.transaction` reach a D1 code path.
|
|
40
|
-
|
|
41
|
-
## d1-foreign-keys-always-on — HIGH · config-elsewhere
|
|
42
|
-
**Contract:** D1 enforces `PRAGMA foreign_keys = on` for every query and migration and does not allow turning it off (only `PRAGMA defer_foreign_keys` within a transaction), while local SQLite harnesses (better-sqlite3 et al.) default foreign_keys OFF.
|
|
43
|
-
**Detect:** `better-sqlite3`, `new Database(`, missing `pragma('foreign_keys = ON')` in test setup, `PRAGMA foreign_keys = OFF` in `migrations/*.sql`, `defer_foreign_keys`
|
|
44
|
-
**Ships green, breaks:** Tests that insert children before parents, delete referenced parents, or import fixtures out of order pass locally (orphans silently accepted) and then throw `FOREIGN KEY constraint failed` only on production D1. Conversely, orphan rows accumulated under local FK-off dev later block a table-rebuild migration on D1. A migration file containing `PRAGMA foreign_keys = OFF` is silently ineffective on D1 — and the sanctioned `defer_foreign_keys = on` still lets `ON DELETE CASCADE` fire.
|
|
45
|
-
**Safe change:** Enable `foreign_keys = ON` in every local SQLite test/dev harness; order seed and migration statements parent-first; use `PRAGMA defer_foreign_keys = on` (not `foreign_keys = OFF`) in D1 migrations that transiently violate FKs.
|
|
46
|
-
|
|
47
|
-
## d1-session-bookmark-consistency — HIGH · lifecycle-protocol
|
|
48
|
-
**Contract:** With D1 read replication enabled, cross-request read-your-writes holds only if `session.getBookmark()` is round-tripped (cookie/header) into the next request's `env.DB.withSession(bookmark)`; the constant `"first-unconstrained"` permits arbitrarily stale replica reads.
|
|
49
|
-
**Detect:** `withSession(`, `getBookmark(`, `first-primary`, `first-unconstrained`, `read_replication` in `wrangler.jsonc`/dashboard
|
|
50
|
-
**Ships green, breaks:** Enabling replication and adopting `withSession("first-unconstrained")` makes POST-then-redirect-GET flows intermittently render pre-write state — only for users near a lagging replica, never reproducible in local dev (no replicas exist there). Sessions guarantee *sequential* consistency within one session object; two independent sessions with no bookmark hand-off share no ordering at all. Non-session `env.DB.prepare()` calls still route to the primary — a partial migration to Sessions creates mixed-consistency paths inside one handler.
|
|
51
|
-
**Safe change:** Return the bookmark to the client after every write and feed it into the next request's `withSession()`; default to `"first-primary"` for flows that read after writing; keep a write and its dependent reads on the same session object.
|
|
52
|
-
|
|
53
|
-
## slug-rendezvous-vocabulary-drift — HIGH · rendezvous-string
|
|
54
|
-
**Contract:** `slug` is the org's cross-reference key — enforced refs are real FKs `REFERENCES <table>(slug)`, but drift-tolerant vocabulary columns deliberately have NO FK (paired with a `<thing>_in_taxonomy` boolean), and the vocabulary's source of truth is the taxonomy package, not the D1 snapshot table.
|
|
55
|
-
**Detect:** `REFERENCES sources(slug)`, `_slug` columns without `FOREIGN KEY`, `_in_taxonomy`, `taxonomy/seed/*.csv`
|
|
56
|
-
**Ships green, breaks:** Renaming a slug in the taxonomy CSV regenerates the seed, and the `ON CONFLICT(slug)` upsert *inserts a new row* under the new slug instead of renaming — the old row survives, every existing `_slug` value still points at the now-deprecated slug, joins quietly return empty sets, and `_in_taxonomy` flags go stale. Nothing errors: the columns have no FK by design. FK-enforced references fail loudly instead — but only at write time, long after the rename shipped.
|
|
57
|
-
**Safe change:** Treat slugs as immutable once referenced — change `label`, never `slug`; if a rename is unavoidable, ship an `UPDATE` of every referencing `_slug` column plus old-row retirement in the same migration; recompute `_in_taxonomy` flags afterward.
|
|
58
|
-
|
|
59
|
-
## sqlite-text-timestamp-format — HIGH · serialized-shape
|
|
60
|
-
**Contract:** Every writer of `created_at`/`updated_at` (`TEXT NOT NULL DEFAULT (datetime('now'))`) agrees on the format that default emits: `YYYY-MM-DD HH:MM:SS`, UTC, space separator, no `T`/`Z`/milliseconds.
|
|
61
|
-
**Detect:** `datetime('now')`, `toISOString()`, `$onUpdate`, `text("created_at")`, `new Date(` on timestamp columns
|
|
62
|
-
**Ships green, breaks:** App code writing `new Date().toISOString()` (`2026-07-04T09:00:00.000Z`) into the same column creates mixed formats: TEXT comparison is bytewise, `' '` < `'T'`, so `ORDER BY created_at` and range filters silently drop or misorder rows across the two formats. Reading back, `new Date("2026-07-04 09:00:00")` parses as *local* time in JS while the stored value is UTC — silent per-timezone offsets. And SQLite has no `ON UPDATE`: Drizzle's `$onUpdate` fires only on Drizzle-issued updates, so seed upserts and raw SQL leave `updated_at` stale unless they SET it explicitly.
|
|
63
|
-
**Safe change:** Standardize on the DDL default's format via one shared formatter for app-side writes; when parsing, restore `T`/`Z` (`s.replace(' ','T') + 'Z'`); include `updated_at = datetime('now')` in every raw UPDATE and every seed `DO UPDATE SET`.
|
|
64
|
-
|
|
65
|
-
## sqlite-affinity-boolean-mapping — HIGH · serialized-shape
|
|
66
|
-
**Contract:** All writers store literal `0`/`1` in `is_*`/`has_*` INTEGER columns, because Drizzle's `integer(…, { mode: "boolean" })` deserializes with exactly `Number(value) === 1`.
|
|
67
|
-
**Detect:** `{ mode: "boolean" }`, `is_` / `has_` columns in `init.sql`, quoted booleans `'true'`/`'TRUE'` in seed SQL, `typeof(` audits
|
|
68
|
-
**Ships green, breaks:** SQLite INTEGER affinity rejects nothing — a seed or raw SQL writing `'true'` (quoted) stores the TEXT `'true'` inside the INTEGER column; `Number('true')` is `NaN`, so Drizzle silently reads the row as `false`. Any stored value other than exactly `1` (a `2`, a `-1`, `'yes'`) also reads as `false`. Unquoted `TRUE`/`FALSE` keywords are safe (they are 1/0), which makes the quoted variant an easy copy-paste landmine; D1 tables aren't STRICT, so nothing validates at write time.
|
|
69
|
-
**Safe change:** Write literal `1`/`0` in all hand-written SQL; audit with `SELECT typeof(is_col), is_col, COUNT(*) FROM t GROUP BY 1,2`; ensure every `is_*`/`has_*` column carries `{ mode: "boolean" }` in `schema.ts`.
|
|
70
|
-
|
|
71
|
-
## json-column-shape-versioning — HIGH · serialized-shape
|
|
72
|
-
**Contract:** Readers of a JSON column (`TEXT` holding JSON in SQLite — `design_tokens`, `bbox`, `scorecard`, `meta` — or `jsonb` in PG) must parse every shape ever written; old rows keep their old shape forever, and Drizzle's `{ mode: 'json' }` + `.$type<T>()` is a compile-time assertion never validated at read.
|
|
73
|
-
**Detect:** `mode: 'json'`, `.$type<`, `jsonb(`, `JSON.parse(` on column values
|
|
74
|
-
**Ships green, breaks:** Adding a required field to `T` type-checks green while every pre-existing row lacks it — `undefined` propagates into arithmetic (NaN scores) and skipped branches with no exception; renaming a field silently orphans all historical data under the old key; during a rolling deploy, new-shape writes crash still-running old readers. Tests pass because fixtures are always written by the current code.
|
|
75
|
-
**Safe change:** Make every added field optional with a read-time default, or embed a `v` version field and branch on it; backfill a migration before making a field required; validate at the boundary with a zod schema instead of trusting `$type`.
|
|
76
|
-
|
|
77
|
-
## pg17-enum-lifecycle — HIGH · lifecycle-protocol
|
|
78
|
-
**Contract:** A Postgres enum's value list and declaration order are shared DDL across all writers, readers, and in-flight migrations; PG (through 17) has no `ALTER TYPE … DROP VALUE` — removal requires a full rebuild (columns→text, drop type, recreate, cast back).
|
|
79
|
-
**Detect:** `pgEnum(`, `ALTER TYPE`, `ADD VALUE`, `USING (`…`::text::`, exhaustive `switch` on enum unions
|
|
80
|
-
**Ships green, breaks:** `ADD VALUE` runs fine inside a transaction (since PG12) but *using* the value in the same transaction throws `unsafe use of new value … of enum type` (55P04) — this bites exactly the migration that adds a value and then seeds rows with it, and only at deploy time. Enum `ORDER BY` follows declaration order, so appending without `BEFORE`/`AFTER` silently reorders sorted output. Mixed-version deploys: new pods write the new value while old pods' exhaustive switches receive an unknown variant. The removal rebuild fails mid-migration if any row still holds the removed value.
|
|
81
|
-
**Safe change:** Split ADD VALUE and its first use into separate migrations (separate transactions); use `BEFORE`/`AFTER` when sort order matters; deploy readers tolerant of the new value before writers emit it; before removal, count rows holding the value and review the generated rebuild SQL.
|
|
82
|
-
|
|
83
|
-
## pgvector-opclass-operator-match — HIGH · rendezvous-string
|
|
84
|
-
**Contract:** The query's distance operator, the index's operator class, and the embedding model/dimension must agree: `<->`↔`vector_l2_ops`, `<=>`↔`vector_cosine_ops`, `<#>`↔`vector_ip_ops`, column `vector(N)` fixed to the model's output size.
|
|
85
|
-
**Detect:** `vector_cosine_ops`, `vector_l2_ops`, `vector_ip_ops`, `<=>`, `<->`, `<#>`, `vector({ dimensions:`, `.op('vector_`, `USING hnsw`, `USING ivfflat`
|
|
86
|
-
**Ships green, breaks:** Operator/opclass mismatch produces no error or warning — Postgres just seq-scans (≈5ms indexed → 30s at 1M rows); the only tell is `EXPLAIN` showing Seq Scan. In Drizzle the rendezvous is the literal `.op('vector_cosine_ops')` string on the index vs the `sql`-template operator in a query file that never imports it. Swapping embedding models at the *same* dimension inserts cleanly and returns confidently wrong neighbors — cross-model similarity is meaningless; a different dimension at least errors.
|
|
87
|
-
**Safe change:** Grep every distance operator and match it to an index opclass; `EXPLAIN` the hot query after any index or query change; record the embedding model per row (or per table) and re-embed the entire table on model change — never mix.
|
|
88
|
-
|
|
89
|
-
## redis-key-ttl-serialization-versioning — HIGH · serialized-shape
|
|
90
|
-
**Contract:** Cache writers and readers across deploys rendezvous on literal key strings and an agreed value encoding; Redis outlives every deploy, so pre-deploy keys, shapes, and TTLs keep serving after the code changes.
|
|
91
|
-
**Detect:** key-template literals (`` `user:${id}` ``), `JSON.parse(` on `GET` results, `set(` without `EX`/`KEEPTTL`, `maxmemory-policy`, hardcoded prefixes in more than one module
|
|
92
|
-
**Ships green, breaks:** Renaming a key schema without invalidation leaves old keys serving stale data to any code path still reading the old name — both paths "work". Changing the value shape breaks only on cache *hits*: cold-cache tests and fresh staging pass, production readers throw or mis-parse on surviving pre-deploy entries. Plain `SET key val` (Redis ≥6) silently *removes* an existing TTL unless `KEEPTTL` or `EX` is given — a refresh path without `EX` turns expiring keys immortal. Default `maxmemory-policy noeviction` means a full instance rejects writes (`OOM command not allowed`) instead of evicting.
|
|
93
|
-
**Safe change:** Embed a schema version in the key prefix (`v2:user:{id}`) and bump it with any shape change — old entries expire naturally; always pass `EX`/`PX` (or `KEEPTTL`) on every SET; treat deserialization failure as a cache miss, never an error; set `allkeys-lru` (or similar) for cache workloads.
|
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
# Pack: HTTP wire / API
|
|
2
|
-
|
|
3
|
-
Load when: the touch list exhibits Express routes/middleware (`app.use(`, `router.get(`), the response envelope (`res.json({ status`), zod request validation, axios clients/interceptors, CORS config, webhooks received, or rate limiting.
|
|
4
|
-
|
|
5
|
-
## express5-route-string-syntax — HIGH · rendezvous-string
|
|
6
|
-
**Contract:** Express route strings are compiled by path-to-regexp v8 in Express 5; route authors and every URL caller meet on a path-string dialect that changed from Express 4.
|
|
7
|
-
**Detect:** `app\.(get|post|put|patch|delete|all|use)\(['"]`, `['"]\*['"]`, `:[a-zA-Z]+\?`, `:\w+\(`, `/\*splat`, `\{/:`, `req\.params\[0\]`, `req\.params\.splat`
|
|
8
|
-
**Ships green, breaks:** Old syntax `*`, `:id?`, `:id(\d+)` throws `TypeError: Missing parameter name` at boot — but the silent ones: `/*splat` no longer matches the mount root (`/files/*splat` misses `GET /files/`; only `/{*splat}` matches root); wildcard params are now ARRAYS of segments (`req.params.splat === ['a','b']`, not the string `'a/b'`; `req.params[0]` is gone → undefined); unmatched optional params are OMITTED from `req.params` instead of present-as-undefined; regex sub-patterns are unsupported, so numeric-only constraints once enforced by `(\d+)` silently stop filtering if approximated wrong.
|
|
9
|
-
**Safe change:** Use `/{*splat}` when root must match; treat splat as array (`req.params.splat.join('/')` where a string was expected); `:p?` → `{/:p}`, `:file.:ext?` → `/:file{.:ext}`; move regex constraints into handler/zod validation; run the Express v5 migration codemod and re-test every wildcard/optional route with real URLs.
|
|
10
|
-
|
|
11
|
-
## express5-query-parser-flip — HIGH · serialized-shape
|
|
12
|
-
**Contract:** Clients serialize query strings (qs brackets, axios `params`) and the server parses them per `app.set('query parser', ...)` — Express 5 flipped the default from `'extended'` to `'simple'`.
|
|
13
|
-
**Detect:** `app.set('query parser'`, `req\.query`, `\[\w+\]=` in client URL builders, `qs.stringify`, `paramsSerializer`, `express.urlencoded()`
|
|
14
|
-
**Ships green, breaks:** `?filter[status]=open` now parses to the flat key `"filter[status]"` instead of `{filter:{status:'open'}}` — loose schemas pass it through and filters silently no-op (endpoint returns unfiltered data); strict schemas start 400ing only for clients that send brackets. `req.query` is now a getter: sanitizer middleware doing `req.query = cleaned` silently no-ops (sloppy mode) or throws TypeError (strict). `express.urlencoded()` `extended` also now defaults to `false`.
|
|
15
|
-
**Safe change:** Pin `app.set('query parser', 'extended')` on migration (or convert clients to flat params); mutate `req.query` properties in place, never reassign; validate `req.query` with a strict zod schema so shape drift fails loudly.
|
|
16
|
-
|
|
17
|
-
## express5-removed-response-apis — HIGH · rendezvous-string
|
|
18
|
-
**Contract:** Handler code meets the Express request/response API by literal method name at runtime — nothing static links plain-JS call sites to Express 5's removed/changed methods.
|
|
19
|
-
**Detect:** `res.sendfile(`, `app.del(`, `res.redirect('back')`, `res.location('back')`, `req.param(`, `res\.(send|json|jsonp)\([^)]+,\s*\d{3}\)`, `res\.send\(\d{3}\)`, `clearCookie\(.+maxAge|expires`
|
|
20
|
-
**Ships green, breaks:** `res.redirect('back')` no longer resolves the Referrer — it redirects to the literal relative URL `back` (no error; users land on a 404). `res.clearCookie(name, {maxAge, expires})` silently ignores those options. `res.sendfile`, `app.del`, `req.param()`, `res.send(body, status)`, `res.send(404)` are removed → per-request TypeError → 500s only when the route is exercised. `res.status()` now throws for non-integers outside 100–999. `req.body` is `undefined` (not `{}`) when no parser ran, so `req.body.x` throws where v4 returned undefined.
|
|
21
|
-
**Safe change:** Replace `'back'` with `req.get('Referrer') || '/'`; `res.sendStatus(n)` / `res.status(n).json(obj)`; guard trust edges with `req.body ?? {}`; grep the whole detect list before touching any Express-4-era file.
|
|
22
|
-
|
|
23
|
-
## express-error-handler-arity — HIGH · lifecycle-protocol
|
|
24
|
-
**Contract:** Express identifies an error handler SOLELY by `fn.length === 4`; Express 5 additionally forwards every rejected async handler/middleware promise to that chain as `next(err)`.
|
|
25
|
-
**Detect:** `app.use((err,`, `(err, req, res, next)`, `express-async-errors`, `.catch(next)`, `next(err)`
|
|
26
|
-
**Ships green, breaks:** Deleting the "unused" fourth `next` param (a common lint autofix) silently turns the centralized error handler into ordinary middleware — it now runs on EVERY request and never on errors; errors fall through to Express's default handler, which emits HTML instead of the JSON envelope, and envelope-unwrapping clients break. With Express 5's native rejection forwarding, legacy `catch (e) { next(e) }` plus a rethrow (or a lingering `express-async-errors` shim) double-invokes the error chain → `Cannot set headers after they are sent`. Throws inside `setTimeout`/event callbacks are NOT forwarded and still crash the process.
|
|
27
|
-
**Safe change:** Always declare 4 params on error middleware (void the unused one); one terminal error handler emitting the envelope; in async handlers throw OR `next(e)`, never both; keep non-request-path callbacks in their own try/catch.
|
|
28
|
-
|
|
29
|
-
## api-response-envelope — HIGH · serialized-shape
|
|
30
|
-
**Contract:** Every response body is `{"status": 1, "message": "...", "data": {...}}` (errors: `{"status": 0, "message": "...", "data": null}`); axios interceptors unwrap `response.data.data` and branch on NUMERIC `status`.
|
|
31
|
-
**Detect:** `status: 1`, `status: 0`, `"status": 1`, `.data.data`, `interceptors.response.use`, `res.json({ status`, `data: null`
|
|
32
|
-
**Ships green, breaks:** Server emitting `status: true` breaks client `=== 1` / `=== 0` strict checks — responses classify as neither success nor error and fall through silently. A new endpoint returning a bare payload makes the unwrapper's `.data.data` yield `undefined` — spreads/destructures render empty state, no error thrown. If error envelopes move to non-2xx HTTP codes, axios's default `validateStatus` routes them into the REJECTED interceptor arm where the success unwrapper never runs — code must read `err.response.data.message`, not `res.data.message`. `data: null` on errors breaks optimistic `data.items.map`.
|
|
33
|
-
**Safe change:** Emit the envelope only via one `sendSuccess`/`sendError` helper (no inline literals); unwrap in one axios interceptor handling BOTH fulfilled and rejected arms; zod-parse the envelope at the client edge (`z.union([z.literal(0), z.literal(1)])` for `status`) so drift throws instead of undefined-ing.
|
|
34
|
-
|
|
35
|
-
## http-status-code-convention — HIGH · rendezvous-string
|
|
36
|
-
**Contract:** Server code choices and client interceptor branching meet on exact numeric codes: 200, 201 created, 400, 401 not-authenticated, 403 not-authorized, 404, 500 (plus 429/503 for backoff) — literals on both sides, no static link.
|
|
37
|
-
**Detect:** `res.status(4`, `sendStatus(`, `err.response?.status`, `=== 401`, `=== 403`, `Retry-After`, `status === 429`
|
|
38
|
-
**Ships green, breaks:** Returning 403 (or 200 + envelope `status: 0`) for an EXPIRED token means the client's 401→refresh-token interceptor never fires — sessions die silently or error-toast forever. Returning 401 for a pure permissions failure triggers refresh→retry loops that hammer the auth service and can force logouts. Backoff interceptors keyed to 429/503 don't engage if throttling ships as 400/500. 201-vs-200 breaks clients that branch on `status === 201` to read a created id.
|
|
39
|
-
**Safe change:** 401 strictly = not authenticated (bad/expired credential), 403 strictly = authenticated but not allowed; auth failures always ride HTTP codes, never 200+envelope-0; grep client interceptors for the exact literal before changing any handler's code; include `Retry-After` with 429.
|
|
40
|
-
|
|
41
|
-
## middleware-mount-order — HIGH · lifecycle-protocol
|
|
42
|
-
**Contract:** The `app.use` sequence is the contract: security/CORS → body parsers → auth/rate-limit middleware → routes → 404 → 4-arg error handler LAST.
|
|
43
|
-
**Detect:** ordering in `server.js`/`app.js`/`index.js`, `app.use(express.json`, `app.use(router`, `app.use(errorHandler`, `express.json({ limit`
|
|
44
|
-
**Ships green, breaks:** A router mounted above `express.json()` sees `req.body === undefined` in Express 5 → every POST 500s, or `req.body?.flag` goes falsy and the default branch runs for all users with no error. Routes registered AFTER the error handler still serve, but their errors bypass it → default HTML error responses that envelope clients can't parse. Auth or rate-limit mounted after routes is fail-open — unit tests that call handlers directly stay green. `express.json` only parses `Content-Type: application/json` — `navigator.sendBeacon` (text/plain) and pre-stringified axios posts arrive with `req.body` undefined.
|
|
45
|
-
**Safe change:** Keep one composition file owning the order above; never register routes in two places; when adding a parser-dependent route, confirm it's below the parser; smoke-test one POST through real HTTP per deploy, not just handler units.
|
|
46
|
-
|
|
47
|
-
## webhook-hmac-raw-body — CRITICAL · trust-invariant
|
|
48
|
-
**Contract:** The provider signs the exact raw request bytes; the server must verify the HMAC over those SAME bytes before trusting the event (often payment/provisioning events).
|
|
49
|
-
**Detect:** `express.raw(`, `rawBody`, `createHmac`, `timingSafeEqual`, `verify: (req, res, buf`, headers `stripe-signature`/`x-hub-signature-256`/`x-signature`
|
|
50
|
-
**Ships green, breaks:** Computing the HMAC over `JSON.stringify(req.body)` after `express.json()` produces different bytes (whitespace, unicode escaping, number formatting) → every signature mismatches → all deliveries rejected; the provider retries, then disables the endpoint — events silently lost. The common "fix" (skipping verification) fails OPEN to forged payment events. If `app.use(express.json())` runs globally, a route-level `express.raw()` gets an already-consumed stream → empty buffer → same permanent mismatch. `crypto.timingSafeEqual` THROWS RangeError on unequal lengths (length-check first), and `sig === expected` is a timing oracle. Providers redeliver on timeout/non-2xx → duplicate side effects.
|
|
51
|
-
**Safe change:** Mount `express.raw({ type: 'application/json' })` for the webhook path (or global `express.json({ verify: (req, res, buf) => { req.rawBody = buf } })`); length-check then `timingSafeEqual` on hex-digest Buffers; respond 2xx fast and process async; dedupe on the provider's delivery-id header persisted atomically with the side effect.
|
|
52
|
-
|
|
53
|
-
## zod4-silent-semantics — HIGH · serialized-shape
|
|
54
|
-
**Contract:** Request-validation schemas written with zod 3 idioms meet the zod 4 runtime, which silently ignores or re-interprets several idioms instead of erroring.
|
|
55
|
-
**Detect:** `required_error`, `invalid_type_error`, `errorMap`, `z.record(` with one arg, `.default(`, `.errors`, `.flatten()`, `.format()`, `.strict()`, `.passthrough()`
|
|
56
|
-
**Ships green, breaks:** `required_error`/`invalid_type_error` params were DROPPED — plain-JS call sites are silently ignored, custom messages vanish and clients string-matching them break (`errorMap` is renamed to the unified `error` param). Single-arg `z.record(z.string())` constructs fine and parses EMPTY objects fine, then throws on the first non-empty input; `z.record(z.enum([...]), v)` is now EXHAUSTIVE (missing enum keys fail — v3 was partial; use `z.partialRecord`). `.default(v)` now short-circuits on undefined and returns `v` as-is WITHOUT running transforms/coercions — use `.prefault()` for v3 behavior. `ZodError.errors` alias is removed → `err.errors.map` TypeErrors inside catch blocks (use `.issues`); `.format()`/`.flatten()` are deprecated for `z.treeifyError()`/`z.flattenError()`.
|
|
57
|
-
**Safe change:** On any zod-touching edit, grep for dropped params and one-arg `z.record`; audit enum-keyed records for intended partiality; re-test every `.default()` whose value relied on transforms (switch to `.prefault()`); replace `.errors` with `.issues` in all error handlers.
|
|
58
|
-
|
|
59
|
-
## zod-query-param-coercion — HIGH · serialized-shape
|
|
60
|
-
**Contract:** Query and path params arrive as strings (or string arrays); the schema's coercion layer is where wire strings become the types handlers assume.
|
|
61
|
-
**Detect:** `safeParse(req.query`, `parse(req.query`, `z.coerce.`, `z.coerce.boolean`, `req.query.` feeding numeric/boolean logic
|
|
62
|
-
**Ships green, breaks:** `z.coerce.boolean()` is `Boolean(x)` — `?active=false` and `?active=0` coerce to TRUE (any non-empty string is truthy). `z.coerce.number()` turns `?page=` (empty string) into `0`. Duplicate keys `?id=1&id=2` arrive as `string[]` and fail `z.string()` only for requests that actually send duplicates. Uncoerced `z.number()`/`z.boolean()` on query rejects every real request while handler unit tests (fed real numbers/booleans) stay green. Combined with Express 5's `'simple'` parser, nested-object query schemas never match at all.
|
|
63
|
-
**Safe change:** Use `z.stringbool()` (zod 4) or an explicit `z.enum(['true','false']).transform(...)` for flags — never `z.coerce.boolean()` on query strings; wrap repeatable params in `z.union([T, z.array(T)])`; design query schemas so their INPUT type is string, and test through real URLs.
|
|
64
|
-
|
|
65
|
-
## axios-error-and-timeout-contract — HIGH · rendezvous-string
|
|
66
|
-
**Contract:** Client catch-blocks and retry logic branch on axios 1.x's error taxonomy — `err.response` vs `err.request` vs config error, and literal `err.code` strings — plus its `validateStatus`/`timeout` defaults.
|
|
67
|
-
**Detect:** `err.response`, `err.request`, `err.code ===`, `'ECONNABORTED'`, `'ETIMEDOUT'`, `validateStatus`, `timeout:`, `transitional`, `isAxiosError`
|
|
68
|
-
**Ships green, breaks:** Default `timeout: 0` — axios NEVER times out; a hung upstream pins the request forever and retry logic never fires. When a timeout is set, it rejects with `code: 'ECONNABORTED'` (not ETIMEDOUT) unless `transitional: { clarifyTimeoutError: true }` flips it to `'ETIMEDOUT'` — retry code matching the other literal silently never retries. The timeout is socket-inactivity based, NOT a whole-request deadline: a slowly trickling response can run far past it. Default `validateStatus` rejects 3xx/304 as errors, and overriding it to `() => true` reroutes 4xx/5xx into the SUCCESS interceptor, bypassing envelope error handling. Response headers are lowercase-normalized: `err.response.headers['Retry-After']` is undefined; use `'retry-after'`.
|
|
69
|
-
**Safe change:** Set an explicit `timeout` and decide the code literal via `transitional.clarifyTimeoutError`, matching retry logic to it; use `signal: AbortSignal.timeout(ms)` for a hard deadline; branch `err.response` → server replied, `err.request` → no reply, else config bug; never touch `validateStatus` without auditing both interceptor arms.
|
|
70
|
-
|
|
71
|
-
## cors-allowlist-mirror — HIGH · config-elsewhere
|
|
72
|
-
**Contract:** `cors({ origin: process.env.FRONTEND_URL, credentials, allowedHeaders, exposedHeaders })` must mirror exactly what browser code sends and reads — enforcement happens only in the browser, never in server tests.
|
|
73
|
-
**Detect:** `cors({`, `FRONTEND_URL`, `allowedHeaders`, `exposedHeaders`, `credentials: true`, `withCredentials`, `Access-Control-`
|
|
74
|
-
**Ships green, breaks:** `FRONTEND_URL` unset → `origin: undefined` → the cors package falls back to `*`: silently allows EVERY origin AND breaks all credentialed requests (browsers reject `Access-Control-Allow-Origin: *` with credentials). A comma-joined multi-origin string matches nothing — must be an array or function. If `allowedHeaders` is omitted, cors reflects the request's headers (permissive); once it's explicitly set, adding a new client header without updating it fails ONLY the browser preflight — curl, Postman, and server-to-server all pass. Custom response headers are invisible to client JS without `exposedHeaders`. Errors thrown before the cors middleware produce responses without CORS headers — the browser shows "CORS error", masking the real 500. Cookies need BOTH server `credentials: true` and axios `withCredentials: true`; each alone ships green.
|
|
75
|
-
**Safe change:** Fail boot if `FRONTEND_URL` is unset; origins as array/function; treat `allowedHeaders`/`exposedHeaders` as part of every header-adding change on either side; mount cors first; verify with a real browser preflight, not curl.
|
|
76
|
-
|
|
77
|
-
## rate-limit-trust-proxy — HIGH · trust-invariant
|
|
78
|
-
**Contract:** express-rate-limit buckets by `req.ip`, which Express computes from `X-Forwarded-For` according to `app.set('trust proxy', ...)` — the limiter key is only as honest as the declared proxy-hop count.
|
|
79
|
-
**Detect:** `app.set('trust proxy'`, `rateLimit(`, `keyGenerator`, `X-Forwarded-For`, `ipKeyGenerator`
|
|
80
|
-
**Ships green, breaks:** `trust proxy: true` → `req.ip` is the LEFTMOST `X-Forwarded-For` entry, fully attacker-controlled — every request can present a fresh IP, bypassing the limiter (fail-open on login brute force); express-rate-limit v7 only console-logs `ERR_ERL_PERMISSIVE_TRUST_PROXY` and keeps serving. Unset behind nginx/Cloudflare → `req.ip` is the proxy's IP → the entire userbase shares ONE bucket → production-wide 429s that dev never reproduces (`ERR_ERL_UNEXPECTED_X_FORWARDED_FOR`). A custom `keyGenerator: (req) => req.ip` without IPv6 masking lets one user rotate a /64 for fresh buckets (use the exported `ipKeyGenerator` helper).
|
|
81
|
-
**Safe change:** Set `app.set('trust proxy', 1)` with the exact hop count — never `true`; re-count hops whenever proxy topology changes; treat ERL console errors as failures, not noise; smoke-test `req.ip` from outside the proxy after deploy.
|
|
82
|
-
|
|
83
|
-
## route-path-client-rendezvous — MED · rendezvous-string
|
|
84
|
-
**Contract:** axios/fetch URL strings in the client and Express mount + route strings on the server meet only at runtime — no compiler or test links them.
|
|
85
|
-
**Detect:** `axios.(get|post|put|delete)('/`, `baseURL`, `fetch('/api`, `app.use('/api`, `router.(get|post)('/`, SPA catch-all `app.get('/{*splat}'`
|
|
86
|
-
**Ships green, breaks:** Renaming a mount (`/api/v1` → `/api/v2`) or route segment 404s every call site — and when an envelope-unwrapping interceptor swallows instead of rethrowing, callers get `undefined` and render empty states with no error. An SPA catch-all serving index.html turns API-path typos into 200 `text/html` responses that fail JSON parsing far from the cause. Express defaults are case-insensitive and trailing-slash-tolerant — enabling `strict routing`/`case sensitive routing` changes which existing client strings still match.
|
|
87
|
-
**Safe change:** Centralize client paths in one api module (no inline URL literals); grep both repos for the old path before any rename; mount an API-scoped 404 (JSON envelope) before the SPA catch-all so `/api/*` never falls into index.html; prefer additive versioned mounts over in-place renames.
|
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
# brainstorm
|
|
2
|
-
|
|
3
|
-
A Claude Code skill that is a **thinking partner for designing software** — not a form to fill in. It runs one constant loop (distill → abstract → sync → record) over a conversation, files the thinking into a small set of substance-first pillars, and treats _coherence_ as a measurable target rather than a vibe.
|
|
4
|
-
|
|
5
|
-
Two principles: **the conversation is the work; the artifacts serve it.** And — because conversations are mortal (context compacts, sessions end) — **the session folder is the only memory**: everything the session produces is captured there, distilled, or it doesn't survive.
|
|
6
|
-
|
|
7
|
-
> Spec (single source of truth): `docs/features/brainstorm-skill.md` in the etna repo. The etna copy of this skill (`skills/brainstorm/`) is canonical; the user-level path `~/.claude/skills/brainstorm/` is a symlink to it.
|
|
8
|
-
|
|
9
|
-
---
|
|
10
|
-
|
|
11
|
-
## The loop (the only constant)
|
|
12
|
-
|
|
13
|
-
Every turn, in every mode:
|
|
14
|
-
|
|
15
|
-
1. **Distill** — fold what the user said into the pillars, in their framing, this turn.
|
|
16
|
-
2. **Abstract** — name the latent structure they implied but didn't state (an entity relationship, an invariant, a principle). One offer per exchange.
|
|
17
|
-
3. **Sync** — keep the pillars consistent with each other and with the basis (the sync agent, below).
|
|
18
|
-
4. **Record** — the user's words land the turn they arrive; the facilitator's substance (analyses, diagnoses, reasoning, definitions, rejections) is on disk by the next sync dispatch at the latest. Nothing is hoarded for a session-end dump.
|
|
19
|
-
|
|
20
|
-
Everything else — pillar count, ceremony, harvest — scales with the idea. The loop does not.
|
|
21
|
-
|
|
22
|
-
---
|
|
23
|
-
|
|
24
|
-
## The memory contract
|
|
25
|
-
|
|
26
|
-
v1's leak, measured in a full-session audit (2026-07-03): conclusions survived in the folder, but the facilitator's reasoning — causal diagnoses, informed rejections, definitions of cited terms — lived only in the transcript, and transcripts die at compaction. v2 plugs it with five rules and a recovery rule:
|
|
27
|
-
|
|
28
|
-
1. **Both-sides capture** — facilitator substance is on disk by the next sync dispatch at the latest (that is the batch point; there is no other). Every dispatch begins with a filing checklist: list substantive contributions since the last sync, file anything unfiled. Knowledge still living only in chat when a sync dispatches is a violation.
|
|
29
|
-
2. **Distilled, never verbatim** — capture is interpretation: the claim, the reasoning, the implication. General point recorded; examples cited as examples. (Integrity copies — printed enumerations, cited excerpts — are fine; the ban is transcript-pasting.)
|
|
30
|
-
3. **Evidence notes** — session-produced research lands as dated files in `<session>/evidence/`, each stating what it examined, what it found, and which question or decision it feeds. `basis/` holds frozen inputs only.
|
|
31
|
-
4. **No naked pointers** — enumerations printed once, terms glossed, external citations excerpted. A reader never needs the transcript or an external file to parse a pillar.
|
|
32
|
-
5. **Eager rejections** — a knowingly-declined option materializes `rejected.md` immediately, with the evidence it was declined against.
|
|
33
|
-
|
|
34
|
-
**Recovery:** after any compaction, re-enter from the folder alone; anything still "remembered" but not on disk is a leak — file it immediately.
|
|
35
|
-
|
|
36
|
-
---
|
|
37
|
-
|
|
38
|
-
## Lifecycle
|
|
39
|
-
|
|
40
|
-
Two subcommands, nothing else. The skill never auto-invokes on natural language.
|
|
41
|
-
|
|
42
|
-
```
|
|
43
|
-
/brainstorm start # open a session (requires a basis)
|
|
44
|
-
/brainstorm stop # close a session
|
|
45
|
-
```
|
|
46
|
-
|
|
47
|
-
### The entry gate
|
|
48
|
-
|
|
49
|
-
A session needs substance before it opens. `start` asks for a **basis**: a reference document, or a one-shot brain dump of the whole idea. If the user drip-feeds small action items (a bug fix, a single button), the skill says it's the wrong tool and **does not open** unless overridden. The basis _is_ the first dump — the skill distills it into the initial thesis and questions, so the first questions come from the user's own material, never from an empty template.
|
|
50
|
-
|
|
51
|
-
### Intake frame
|
|
52
|
-
|
|
53
|
-
After distilling the basis, one `AskUserQuestion` batch sets three dials:
|
|
54
|
-
|
|
55
|
-
- **Complexity** (low / medium / high) — sets the default pillar surface.
|
|
56
|
-
- **Build mode** (greenfield / brownfield / hybrid) — lands in `build.md`; opens or closes the execution sections and sets the writing posture.
|
|
57
|
-
- **Mode** — where the idea lives right now (see below).
|
|
58
|
-
|
|
59
|
-
Then the skill proposes an **aspect map** — the thinking dimensions for _this_ idea — which the user edits. The map drives the sync's coverage audit.
|
|
60
|
-
|
|
61
|
-
### Modes (who drives)
|
|
62
|
-
|
|
63
|
-
| Mode | Driver | When | Behavior |
|
|
64
|
-
| --- | --- | --- | --- |
|
|
65
|
-
| **dump** | user | idea is in their head | No questions mid-stream. Distill live, reflect back shape + contradictions + implications. |
|
|
66
|
-
| **interview** | skill | idea is fuzzy | Question batches of 2–3, one aspect at a time, each answer distilled immediately. |
|
|
67
|
-
| **probe** | skill | idea is drafted | Adversarial pass — flaws, edge cases, conflicts. Each finding becomes a question. |
|
|
68
|
-
| **converge** | shared | closing | Burn down open questions into decisions or explicit parks; ends with a mandatory sync. |
|
|
69
|
-
|
|
70
|
-
Mode switches on an explicit user word. On a strong signal the skill _offers_ a switch in one line; it never seizes it.
|
|
71
|
-
|
|
72
|
-
---
|
|
73
|
-
|
|
74
|
-
## Coherence (the doneness function)
|
|
75
|
-
|
|
76
|
-
```
|
|
77
|
-
coherent ⇔ open_questions == 0 ∧ last sync ran after the last pillar write
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
`questions.md` is the **single convergence currency**: flaws, gaps, contradictions, and uncovered aspects all funnel into it, whoever raised them. Convergence is one number going to zero. Zero means _"audited against the five sources and clean,"_ never _"nothing came to mind"_ — which is why the sync agent's audit contract is mandatory.
|
|
81
|
-
|
|
82
|
-
---
|
|
83
|
-
|
|
84
|
-
## The sync agent
|
|
85
|
-
|
|
86
|
-
The background reconciler. One sync in flight at a time; at most one queued behind it. It runs after substantive writes, mandatorily on entering converge and at `stop`, and on demand. Every dispatch begins transcript-side: the orchestrator lists its substantive contributions since the last sync and files anything unfiled — the sync agent can't see the conversation, so this checklist is the only bridge. Then it audits exactly five sources:
|
|
87
|
-
|
|
88
|
-
1. **Cross-pillar contradiction** — thesis vs domain model vs decisions vs doctrine vs build.
|
|
89
|
-
2. **Aspect coverage** — any mapped aspect with no content → a question.
|
|
90
|
-
3. **Basis drift** — does the thesis still agree with the basis? Accidental divergence → a question.
|
|
91
|
-
4. **Tech conflicts** — anything violating `tech.md` without a recorded deviation.
|
|
92
|
-
5. **Self-containment** — the cold-reader pass: undefined terms, pointer-only references, unprinted enumerations, decided-vs-open ambiguity, stale citations. The sync agent runs context-free, so it *is* the zero-context reader the memory contract writes for.
|
|
93
|
-
|
|
94
|
-
It applies **scribe-calls** (edits that don't change the design — including printing a missing enumeration or glossing a term) directly and notes them; it files **design-calls** (edits that change the idea) as questions and moves on — never interrupting to ask "apply now or defer?" Its one-line report ("4 edits · 2 new questions · 6 open · untouched: risks") is the only ambient convergence pressure the skill applies.
|
|
95
|
-
|
|
96
|
-
---
|
|
97
|
-
|
|
98
|
-
## Pillars (substance first, lazy by default)
|
|
99
|
-
|
|
100
|
-
Always present: `thesis.md`, `questions.md`, `decisions.md`, `build.md`. Materialized at medium+ complexity: `domain-model.md`, `tech.md`. Lazy (materialize on first real content at any complexity): `doctrine`, `glossary`, `non-goals`, `backlog`, `references`, `milestones` — and `rejected`, which is **eager**: it materializes the moment an option is knowingly declined.
|
|
101
|
-
|
|
102
|
-
| File | Role |
|
|
103
|
-
| --- | --- |
|
|
104
|
-
| `thesis.md` | Running narrative of what we're designing + the aspect map. |
|
|
105
|
-
| `questions.md` | Single convergence currency — every unresolved design call. |
|
|
106
|
-
| `decisions.md` | Resolved calls with **Why** + **How to apply**. Append-only, no state machine. |
|
|
107
|
-
| `build.md` | How the work executes: build mode, migration strategy, gotchas, rollout. |
|
|
108
|
-
| `domain-model.md` | Information architecture — entities, relationships, cardinalities, state ownership. |
|
|
109
|
-
| `tech.md` | Stack choices, seeded from harness rules; deviations recorded with whys. |
|
|
110
|
-
| `evidence/` | Session-produced analyses as dated notes (`templates/evidence.md`) — each states what it examined and which question/decision it feeds. |
|
|
111
|
-
| `doctrine` / `glossary` / `non-goals` / `backlog` / `rejected` / `references` / `milestones` | As their templates describe. |
|
|
112
|
-
|
|
113
|
-
The complexity dial sets _defaults_, not a cage — any lazy pillar materializes the moment the conversation produces content for it.
|
|
114
|
-
|
|
115
|
-
---
|
|
116
|
-
|
|
117
|
-
## Build modes
|
|
118
|
-
|
|
119
|
-
The writing posture is a **mode** chosen at intake, folded into `build.md`:
|
|
120
|
-
|
|
121
|
-
- **greenfield** (default) — present-tense everywhere, no phantom history. Execution sections closed.
|
|
122
|
-
- **brownfield** — migration vocabulary is legitimate in `build.md`; other pillars still describe the target.
|
|
123
|
-
- **hybrid** — new surface on a live system; execution sections apply to the seams only.
|
|
124
|
-
|
|
125
|
-
`build.md` also captures **gotchas** — execution hazards known now, before plan mode, because surfacing them in plan mode is too late.
|
|
126
|
-
|
|
127
|
-
---
|
|
128
|
-
|
|
129
|
-
## Exit artifacts
|
|
130
|
-
|
|
131
|
-
The session writes a design record at `docs/research/{topic}-brainstorming/` (one folder per topic), moved to `docs/history/brainstorms/{topic}/` on harvest. At `stop`, after the final five-source sync (self-containment included — the record is verified standalone-readable exactly when it's about to become the only survivor of the session), the skill _offers_ what to **publish** from it (`AskUserQuestion`, multi-select — a session can emit more than one):
|
|
132
|
-
|
|
133
|
-
- **Source of truth** — one consolidated, README-style canonical doc for the thing designed (`templates/source-of-truth.md`); lands in the repo's feature/architecture doc home, else a topic `Readme.md`.
|
|
134
|
-
- **Plans** — one or more executable plan docs → `docs/history/plans/` (Status: Draft).
|
|
135
|
-
- **Harvest into the living docs** — conclusions dispersed by scope into ADs (architecture decisions), the domain model, and the backlog.
|
|
136
|
-
|
|
137
|
-
The session record is **kept** whichever you pick — never deleted; on harvest it moves to `docs/history/brainstorms/{topic}/` as the provenance every artifact traces back to. See `exit-artifacts.md`.
|
|
138
|
-
|
|
139
|
-
---
|
|
140
|
-
|
|
141
|
-
## Hard rules
|
|
142
|
-
|
|
143
|
-
1. **No production code outside the session folder.** Illustrative snippets are fine inside it.
|
|
144
|
-
2. **Speak English to the user; codes (`Q3`, `D7`) live in the files.**
|
|
145
|
-
3. **`AskUserQuestion` appears in exactly four places:** the intake frame, interview mode, converge picks, the `stop` exit-artifact pick.
|
|
146
|
-
4. **Suggested, never seized** — mode shifts, abstractions, probes are offered once.
|
|
147
|
-
5. **Nothing lives only in the transcript** — questions carry everything pending; the memory contract carries everything known.
|
|
148
|
-
6. **No auto-invocation** — only `/brainstorm start` and `/brainstorm stop`.
|
|
149
|
-
|
|
150
|
-
---
|
|
151
|
-
|
|
152
|
-
## Files
|
|
153
|
-
|
|
154
|
-
```
|
|
155
|
-
brainstorm/ # the skill (in .claude/skills/)
|
|
156
|
-
├── SKILL.md # the skill definition Claude Code loads (~2.2k words)
|
|
157
|
-
├── README.md # this file
|
|
158
|
-
├── exit-artifacts.md # what /brainstorm stop publishes: source-of-truth / plans / harvest
|
|
159
|
-
└── templates/ # pillar templates + evidence.md + source-of-truth.md, used in the record and at stop
|
|
160
|
-
```
|
|
161
|
-
|
|
162
|
-
The session itself is written to `docs/research/{topic}-brainstorming/` (committed; moved to `docs/history/brainstorms/{topic}/` on harvest) — not here.
|