[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CZC552K92VAJKSPZ4BV4ZW":3,"skill-same:01M7CZC552K92VAJKSPZ4BV4ZW":60},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":32,"commitSha":33,"skillDirectory":34,"forksCount":35,"repositoryHtmlUrl":30,"repositoryHomepageUrl":6,"ownerHtmlUrl":36,"ownerBlogUrl":37,"ownerDescription":38,"updatedAt":39,"install":40,"resources":53},"01M7CZC552K92VAJKSPZ4BV4ZW","padosoft-hono-api-conventions",null,"Use this skill when writing or reviewing code in a Hono API on Bun — a new endpoint, a middleware, a repository or a SQL query — and whenever the user works on a controller\u002Frepository\u002Fquery layer, types a Hono context, adds a paginated or localized list, or hits a symptom like \"the type of c.get is any\", \"it returns null instead of an empty list\", \"page 1 skips records\", \"sometimes the translation is missing\" or \"the middleware types don't line up\": it applies the three-layer architecture, the typed-context and middleware-factory patterns, and the recurring mistakes that cost the most. Do not use it for the security review of an endpoint (padosoft-api-security-review) nor for OpenAPI spec changes.","padosoft\u002Fskills","padosoft","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F10467753?v=4","01M7CZ3FRSM851DK225E3KK2VF","01M7CZ3FSY016E21VS6EABM21V",1,"MIT","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fpadosoft-hono-api-conventions\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: padosoft-hono-api-conventions\ndescription: >-\n  Use this skill when writing or reviewing code in a Hono API on Bun — a new endpoint, a middleware, a\n  repository or a SQL query — and whenever the user works on a controller\u002Frepository\u002Fquery layer, types a\n  Hono context, adds a paginated or localized list, or hits a symptom like \"the type of c.get is any\", \"it\n  returns null instead of an empty list\", \"page 1 skips records\", \"sometimes the translation is missing\" or\n  \"the middleware types don't line up\": it applies the three-layer architecture, the typed-context and\n  middleware-factory patterns, and the recurring mistakes that cost the most. Do not use it for the security\n  review of an endpoint (padosoft-api-security-review) nor for OpenAPI spec changes.\nlicense: MIT\ncompatibility: >-\n  Hono on Bun with TypeScript. The database patterns assume a driver with named placeholders (mysql2 style);\n  the layering and typing rules hold with any driver.\nmetadata:\n  version: 0.2.0\n  author: Padosoft\n  summary: Three layers one direction, typed context, bound SQL, and the mistakes that keep returning.\n  profiles: node, api\n  scope: project\n  repository: https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\n  keywords: hono, bun, typescript, api, architecture, repository, sql, middleware, zod\n---\n\n# Hono API conventions\n\nThe conventions that a Hono\u002FBun API needs applied consistently, and the mistakes that keep coming back. The\ngoal: an endpoint that goes through review without the same five comments every time.\n\n---\n\n## 1. Three layers, one direction\n\n**Controller → Repository → Query.** Each layer has exactly one job, and the dependency only ever points\ndownwards.\n\n| Layer | Does | Never does |\n|---|---|---|\n| **Controller** (`src\u002Fcontrollers\u002F`) | Reads the validated input (`c.req.valid(\"query\"\\|\"json\"\\|\"param\")`), calls the repository, maps relations, returns `c.json(data, status)`, throws `ApiError` | SQL, business transformations |\n| **Repository** (`src\u002Frepositories\u002F`) | Calls the query, executes it, **transforms** the data, handles caching and transactions | Builds SQL strings, touches the HTTP context |\n| **Query** (`src\u002Fquery\u002F`) | **Only** SQL building. Returns `[sql, params] as const` | Business logic, execution, transformation |\n\n```ts\n\u002F\u002F src\u002Fquery\u002Floyalty\u002Fquery.ts — returns the tuple, executes nothing\nexport function queryGetLevels(lang: string) {\n    const sql = `SELECT id, COALESCE(t.descr, b.descr) AS descr\n                 FROM levels b\n                 LEFT JOIN languages l ON l.code = :lang\n                 LEFT JOIN level_languages t ON t.level_ID = b.id AND t.languages_ID = l.id\n                 ORDER BY b.id`;\n    return [sql, { lang }] as const;\n}\n\n\u002F\u002F src\u002Frepositories\u002Floyalty\u002Frepository.ts — executes and transforms\nexport async function getLevelsRepo(lang: string) {\n    const [sql, params] = queryGetLevels(lang);\n    const [rows] = await client.execute\u003C(RowDataPacket & Level)[]>(sql, params);\n    return rows;                   \u002F\u002F empty result → [], never null\n}\n```\n\nReturning the tuple `as const` is what keeps the query layer pure and testable: a query test asserts on the\nSQL string and the params, with no database.\n\n## 2. Typed context, no assertions\n\nDefine **every** context variable in one central `Env` type, and let inference do the rest.\n\n```ts\n\u002F\u002F src\u002Ftypes\u002Fenv.ts\nexport interface AuthContext { customerId: number }\nexport interface Variables { auth?: AuthContext }\nexport interface Env { Variables: Variables }\n```\n\n```ts\n\u002F\u002F ❌ a hand-rolled shape, and a cast at every read\nexport function getCustomerId(c: { get: (k: string) => any }) { … }\nreturn c.get(\"auth\") as AuthContext | undefined;\n\n\u002F\u002F ✅ the real Context type, and the value is already typed\nimport type { Context } from \"hono\";\nexport function getCustomerId(c: Context\u003CEnv>) { return getAuth(c)?.customerId; }\nreturn c.get(\"auth\");\n```\n\nEvery `as` on a context read means the `Variables` type is missing an entry. Fix the type, not the call site.\n\n## 3. Middleware through the factory\n\n```ts\n\u002F\u002F ❌ hand-typed handler: the Env generic is lost downstream\nimport type { MiddlewareHandler } from \"hono\";\nexport const authMiddleware = (): MiddlewareHandler\u003CEnv> => async (c, next) => { … };\n\n\u002F\u002F ✅ factory: the context stays typed inside the middleware and after it\nimport { createFactory } from \"hono\u002Ffactory\";\nconst factory = createFactory\u003CEnv>();\nexport const authMiddleware = () => factory.createMiddleware(async (c, next) => {\n    c.set(\"auth\", { customerId });     \u002F\u002F no assertion needed\n    await next();\n});\n```\n\n## 4. Environment variables through one module\n\n```ts\nimport { env } from \"bun\";        \u002F\u002F ❌ unvalidated, no types, fails at runtime\nimport { env } from \"@\u002Flib\u002Fenv\";  \u002F\u002F ✅ schema-validated, fails fast at startup\n```\n\nThe env module parses with a schema and **aborts on startup** when something is missing or inconsistent. A\nmissing variable has to break the boot, not the first request that needs it.\n\n## 5. SQL: named placeholders and dynamic building\n\nNamed placeholders (`:name`) everywhere, never string interpolation — a SELECT literal is injection too\n(`padosoft-api-security-review`, `API-SEC-SQL-001`).\n\n```ts\n\u002F\u002F IN (…) — build the placeholders, and MERGE the params back\nlet params: Record\u003Cstring, unknown> = { lang };\nconst [placeholders, arrayParams] = buildArrayPlaceholders(\"id\", ids);   \u002F\u002F ids is an ARRAY\nsql += ` WHERE id IN (${placeholders})`;\nparams = { ...params, ...arrayParams };   \u002F\u002F forget this → \"Unknown parameter :id_0\"\n```\n\n**Localize in SQL, not in the application.** `COALESCE(t.descr, b.descr)` beats\n`row.descr_translated || row.descr`: one round trip, and the fallback is the same for everyone.\n\n**Constrain the translation join inside its own `ON`** — the language filter on a second `LEFT JOIN` cannot\nreduce rows, so you get N rows per source row: inflated pagination, and `rows[0]` picking a random row when\nthere is no `ORDER BY`. That is the \"sometimes it doesn't translate\" bug. Full explanation in\n`padosoft-api-security-review` (`API-SEC-SQL-001`).\n\n\n**Keep the placeholders contiguous.** A statement that binds `$1, $2, $5` and never uses `$3` and `$4` is\nrejected by the server with a parameter-type error, not by the type system and not by an in-memory double.\nThe same class of defect hides behind every store that is not the real engine: run the provider contract\nwhenever a new durable path is added.\n\n**Decode at the durable boundary, not at the call site.** A driver can return a JSON column as a *string* —\nincluding the literal `\"null\"` for a nullable field — so a cached response read back inside a transaction\ncan be shaped differently from the same read outside it. Select the column as text at transaction\nboundaries, pass everything through one decoder, and guard an absent row explicitly. A type assertion at a\nJSON boundary does not strip unknown properties either: an allowlist has to run at runtime, before\npersistence and before serialisation.\n\n## 6. Transactions on multi-write\n\n**A repository function that performs two or more writes (INSERT\u002FUPDATE\u002FDELETE) wraps them in a transaction\non a single connection.** Without it a partial failure leaves half the operation applied.\n\n```ts\nconst conn = await client.getConnection();\ntry {\n    await conn.beginTransaction();\n    await conn.execute(sqlDelete, p1);\n    await conn.execute(sqlInsert, p2);\n    await conn.commit();\n} catch (e) {\n    await conn.rollback();\n    throw e;\n} finally {\n    conn.release();\n}\n```\n\nPre-screen on the staged diff:\n\n```bash\ngit diff --cached --name-only --diff-filter=ACMR | grep -E '^src\u002Frepositories\u002F.*\\.ts$' | while read f; do\n  execs=$(grep -cE '\\b(client|connection|conn)\\.execute' \"$f\")\n  writes=$(grep -ciE 'INSERT INTO|UPDATE |DELETE FROM|(insert|update|delete|upsert|remove|save)[A-Za-z]*(Sql|Query|Params)\\b' \"$f\")\n  tx=$(grep -cE 'beginTransaction|getConnection' \"$f\")\n  [ \"${execs:-0}\" -ge 2 ] && [ \"${writes:-0}\" -ge 1 ] && [ \"${tx:-0}\" -eq 0 ] \\\n    && echo \"⚠️  $f — $execs execute, $writes write signals, no transaction\"\ndone\n```\n\n⚠️ **Do not grep for `execute(\"INSERT`** — in this architecture the SQL arrives from the query layer as a\n*variable* (`connection.execute(deleteSql, deleteParams)`), so the keyword is never next to the call. A check\nwritten that way reports zero on a codebase full of writes, which is the worst possible outcome: a green\ncheck that never looked. The screen above recognises the write through the query it imports instead.\n\n**The screen is file-level, the rule is per function.** A file with fifteen single-write functions is fine\nand will still be flagged: it narrows all repositories down to a handful worth opening, and then you count\nthe writes *inside the function*. Confirm before reporting anything.\n\nTwo shapes come back as candidates and are **not** violations — recognise them and move on:\n\n- **Upsert branches.** `SELECT` to check existence, then `INSERT` *or* `UPDATE`. Two writes in the text, one\n  per execution path. (Worth a separate look for the check-then-act race, which a unique index closes — but\n  it is not the transaction rule.)\n- **A read function with many executes.** Four `SELECT`s in a loader are four executes and zero writes.\n\nWhat survives is the real shape: **two writes on different rows or tables, in sequence, on the same path.**\n\nA function whose name or docstring promises all-or-nothing semantics (\"atomic\", \"bulk replace\", \"publish\",\n\"transition\") and has no transaction is a **critical** finding, not a warning. If the function only delegates\nto another repository that already opens the transaction, it is fine.\n\n## 7. Caching with a circuit breaker\n\nCache in the **repository**, never in the query or the controller. A cache is an optimization: when the cache\nstore is down the endpoint keeps answering from the database, so the cache client sits behind a circuit\nbreaker and a failed read is a miss, not a 500. Bound every in-memory cache with a size **and** a TTL.\n\n## 8. Validation at the edge\n\nThe schema validates at the route, the controller reads the already-validated value. Never re-validate by\nhand inside the controller, and never read `c.req.query()` raw when a validated schema exists.\n\n**Lenient in the request, strict in the response.** An invalid optional parameter (a bad language code) is\ntreated as *absent* and resolved by the server fallback — never a 422 caused by that field alone. The same\nfield in a response or an entity stays strict: the documented contract does not bend.\n\n## 8b. Concurrent edits: the conditional write is an API contract\n\nAn optimistic editor in the client prevents nothing while the API still accepts an unconditional\nlast-write-wins update. The rule lives on the server:\n\n- **Reads return a version or content identity**; writes require it; a stale write is rejected with a\n  machine-readable precondition failure, and the newer server value is left untouched.\n- **The lifecycle crosses the client boundary**: capture the identity when the editor opens, attach it to\n  the write, and replace it with the response's identity after a successful save. A test that proves the\n  header actually crosses that boundary is the only thing that proves the feature.\n- **A precondition failure without a recovery path is a safe dead end.** The client has to say that another\n  writer won and offer an explicit reload of the authoritative representation together with its new\n  identity — otherwise the operator is stuck holding edits they cannot apply.\n- **An atomic lock does not make two incompatible transitions both valid.** Two concurrent transitions out\n  of the same state are serialised, and the second one *correctly* fails. A concurrency test asserts\n  atomicity **and** explicit conflict handling — never that both writes commit.\n\n## 8c. A stream is transport, and transport does not remember\n\n- **Filter by authenticated tenant before writing to the stream**, emit bounded heartbeats, and clean up the\n  subscription on **both** request abort and response close.\n- **Reconnect restores a socket, not the events lost while it was down.** Refetch the durable projection on\n  the reconnect edge; use individual events only as low-latency invalidation hints.\n- **Event ids alone are not replay.** Persist the event before publishing the notification, subscribe before\n  replaying, deduplicate the overlap, and signal a missing or expired cursor explicitly rather than\n  returning an empty result. See **`padosoft-durable-effects`**.\n- **A passing stream-writer test is not a live journey.** The causal proof is: create the subscriber,\n  publish a tenant-scoped event, parse it in the real client, render the connection state, assert it there.\n\n---\n\n## Gotchas\n\nThese are the ones that come back in review:\n\n**0. An identifier that crosses a trust boundary needs a real random source.** A UUID-shaped string built\nfrom the ordinary pseudo-random generator is not a security identifier, and it looks exactly like one.\nQueue, job and event ids cross tenant and retry boundaries: use the runtime's cryptographic generator.\n\n**1. `null` instead of an empty array.** The controller expects a list.\n\n```ts\nif (!rows.length) return null;   \u002F\u002F ❌ callers crash on .map\nif (!rows.length) return [];     \u002F\u002F ✅\n```\n\n**2. Pagination offset.** `offset = page * perPage` makes page 1 skip the first page.\n\n```ts\nconst offset = (page - 1) * perPage;   \u002F\u002F ✅ page 1 → 0\n```\n\n**3. A CSV string passed where an array is expected.** `\"1,7,9\"` is one element, not three. Split and coerce\nto numbers first.\n\n**4. Params of a dynamic `IN` not merged** — see §5. The symptom is `Unknown parameter :id_0`.\n\n**5. Language fallback in application code** instead of SQL `COALESCE` — see §5.\n\n**6. A type assertion on the context** — see §2. It always means a missing `Variables` entry.\n\n**7. `rows[0]` on a query that can return more than one row with no `ORDER BY`.** Which row arrives first is\nthe engine's choice, so the behaviour changes without the code changing.\n\n**8. `LIMIT`\u002F`OFFSET` are interpolated on purpose.** The driver does not bind them as named placeholders, so\nthe layering gives way here and the values are inlined. Do not \"fix\" one back into `:limit`: the query\nbreaks. Make sure the value is a schema-coerced number and leave it alone.\n\n---\n\n## Checklist before committing\n\n- [ ] Query returns `[sql, params] as const` and contains no business logic\n- [ ] Repository returns `[]` and not `null`; transformations live here\n- [ ] Controller does no SQL and throws `ApiError` instead of returning an error shape\n- [ ] No `as` on a context read; `Variables` updated if one was needed\n- [ ] Middleware built with the factory\n- [ ] Named placeholders only; `IN` params merged; translation join constrained in its own `ON`\n- [ ] Two or more writes in one repository function → transaction\n- [ ] `env` imported from the validated module\n- [ ] Offset computed as `(page - 1) * perPage`\n- [ ] Linter and type check clean\n\n## Final report\n\n```\nEndpoint\u002Fchange: \u003Cwhat>\nLayers: controller \u003Cfile> · repository \u003Cfile> · query \u003Cfile>\nConventions: \u003Cn> respected, \u003Cn> deviations (with reason)\nGotchas checked: null-vs-[] · offset · IN merge · localization · context typing · transactions\nLinter\u002Ftypes: PASS | FAIL \u003Cdetail>\nTo decide: \u003C…>\n```\n","# Hono API conventions\n\nThe conventions that a Hono\u002FBun API needs applied consistently, and the mistakes that keep coming back. The\ngoal: an endpoint that goes through review without the same five comments every time.\n\n---\n\n## 1. Three layers, one direction\n\n**Controller → Repository → Query.** Each layer has exactly one job, and the dependency only ever points\ndownwards.\n\n| Layer | Does | Never does |\n|---|---|---|\n| **Controller** (`src\u002Fcontrollers\u002F`) | Reads the validated input (`c.req.valid(\"query\"\\|\"json\"\\|\"param\")`), calls the repository, maps relations, returns `c.json(data, status)`, throws `ApiError` | SQL, business transformations |\n| **Repository** (`src\u002Frepositories\u002F`) | Calls the query, executes it, **transforms** the data, handles caching and transactions | Builds SQL strings, touches the HTTP context |\n| **Query** (`src\u002Fquery\u002F`) | **Only** SQL building. Returns `[sql, params] as const` | Business logic, execution, transformation |\n\n```ts\n\u002F\u002F src\u002Fquery\u002Floyalty\u002Fquery.ts — returns the tuple, executes nothing\nexport function queryGetLevels(lang: string) {\n    const sql = `SELECT id, COALESCE(t.descr, b.descr) AS descr\n                 FROM levels b\n                 LEFT JOIN languages l ON l.code = :lang\n                 LEFT JOIN level_languages t ON t.level_ID = b.id AND t.languages_ID = l.id\n                 ORDER BY b.id`;\n    return [sql, { lang }] as const;\n}\n\n\u002F\u002F src\u002Frepositories\u002Floyalty\u002Frepository.ts — executes and transforms\nexport async function getLevelsRepo(lang: string) {\n    const [sql, params] = queryGetLevels(lang);\n    const [rows] = await client.execute\u003C(RowDataPacket & Level)[]>(sql, params);\n    return rows;                   \u002F\u002F empty result → [], never null\n}\n```\n\nReturning the tuple `as const` is what keeps the query layer pure and testable: a query test asserts on the\nSQL string and the params, with no database.\n\n## 2. Typed context, no assertions\n\nDefine **every** context variable in one central `Env` type, and let inference do the rest.\n\n```ts\n\u002F\u002F src\u002Ftypes\u002Fenv.ts\nexport interface AuthContext { customerId: number }\nexport interface Variables { auth?: AuthContext }\nexport interface Env { Variables: Variables }\n```\n\n```ts\n\u002F\u002F ❌ a hand-rolled shape, and a cast at every read\nexport function getCustomerId(c: { get: (k: string) => any }) { … }\nreturn c.get(\"auth\") as AuthContext | undefined;\n\n\u002F\u002F ✅ the real Context type, and the value is already typed\nimport type { Context } from \"hono\";\nexport function getCustomerId(c: Context\u003CEnv>) { return getAuth(c)?.customerId; }\nreturn c.get(\"auth\");\n```\n\nEvery `as` on a context read means the `Variables` type is missing an entry. Fix the type, not the call site.\n\n## 3. Middleware through the factory\n\n```ts\n\u002F\u002F ❌ hand-typed handler: the Env generic is lost downstream\nimport type { MiddlewareHandler } from \"hono\";\nexport const authMiddleware = (): MiddlewareHandler\u003CEnv> => async (c, next) => { … };\n\n\u002F\u002F ✅ factory: the context stays typed inside the middleware and after it\nimport { createFactory } from \"hono\u002Ffactory\";\nconst factory = createFactory\u003CEnv>();\nexport const authMiddleware = () => factory.createMiddleware(async (c, next) => {\n    c.set(\"auth\", { customerId });     \u002F\u002F no assertion needed\n    await next();\n});\n```\n\n## 4. Environment variables through one module\n\n```ts\nimport { env } from \"bun\";        \u002F\u002F ❌ unvalidated, no types, fails at runtime\nimport { env } from \"@\u002Flib\u002Fenv\";  \u002F\u002F ✅ schema-validated, fails fast at startup\n```\n\nThe env module parses with a schema and **aborts on startup** when something is missing or inconsistent. A\nmissing variable has to break the boot, not the first request that needs it.\n\n## 5. SQL: named placeholders and dynamic building\n\nNamed placeholders (`:name`) everywhere, never string interpolation — a SELECT literal is injection too\n(`padosoft-api-security-review`, `API-SEC-SQL-001`).\n\n```ts\n\u002F\u002F IN (…) — build the placeholders, and MERGE the params back\nlet params: Record\u003Cstring, unknown> = { lang };\nconst [placeholders, arrayParams] = buildArrayPlaceholders(\"id\", ids);   \u002F\u002F ids is an ARRAY\nsql += ` WHERE id IN (${placeholders})`;\nparams = { ...params, ...arrayParams };   \u002F\u002F forget this → \"Unknown parameter :id_0\"\n```\n\n**Localize in SQL, not in the application.** `COALESCE(t.descr, b.descr)` beats\n`row.descr_translated || row.descr`: one round trip, and the fallback is the same for everyone.\n\n**Constrain the translation join inside its own `ON`** — the language filter on a second `LEFT JOIN` cannot\nreduce rows, so you get N rows per source row: inflated pagination, and `rows[0]` picking a random row when\nthere is no `ORDER BY`. That is the \"sometimes it doesn't translate\" bug. Full explanation in\n`padosoft-api-security-review` (`API-SEC-SQL-001`).\n\n\n**Keep the placeholders contiguous.** A statement that binds `$1, $2, $5` and never uses `$3` and `$4` is\nrejected by the server with a parameter-type error, not by the type system and not by an in-memory double.\nThe same class of defect hides behind every store that is not the real engine: run the provider contract\nwhenever a new durable path is added.\n\n**Decode at the durable boundary, not at the call site.** A driver can return a JSON column as a *string* —\nincluding the literal `\"null\"` for a nullable field — so a cached response read back inside a transaction\ncan be shaped differently from the same read outside it. Select the column as text at transaction\nboundaries, pass everything through one decoder, and guard an absent row explicitly. A type assertion at a\nJSON boundary does not strip unknown properties either: an allowlist has to run at runtime, before\npersistence and before serialisation.\n\n## 6. Transactions on multi-write\n\n**A repository function that performs two or more writes (INSERT\u002FUPDATE\u002FDELETE) wraps them in a transaction\non a single connection.** Without it a partial failure leaves half the operation applied.\n\n```ts\nconst conn = await client.getConnection();\ntry {\n    await conn.beginTransaction();\n    await conn.execute(sqlDelete, p1);\n    await conn.execute(sqlInsert, p2);\n    await conn.commit();\n} catch (e) {\n    await conn.rollback();\n    throw e;\n} finally {\n    conn.release();\n}\n```\n\nPre-screen on the staged diff:\n\n```bash\ngit diff --cached --name-only --diff-filter=ACMR | grep -E '^src\u002Frepositories\u002F.*\\.ts$' | while read f; do\n  execs=$(grep -cE '\\b(client|connection|conn)\\.execute' \"$f\")\n  writes=$(grep -ciE 'INSERT INTO|UPDATE |DELETE FROM|(insert|update|delete|upsert|remove|save)[A-Za-z]*(Sql|Query|Params)\\b' \"$f\")\n  tx=$(grep -cE 'beginTransaction|getConnection' \"$f\")\n  [ \"${execs:-0}\" -ge 2 ] && [ \"${writes:-0}\" -ge 1 ] && [ \"${tx:-0}\" -eq 0 ] \\\n    && echo \"⚠️  $f — $execs execute, $writes write signals, no transaction\"\ndone\n```\n\n⚠️ **Do not grep for `execute(\"INSERT`** — in this architecture the SQL arrives from the query layer as a\n*variable* (`connection.execute(deleteSql, deleteParams)`), so the keyword is never next to the call. A check\nwritten that way reports zero on a codebase full of writes, which is the worst possible outcome: a green\ncheck that never looked. The screen above recognises the write through the query it imports instead.\n\n**The screen is file-level, the rule is per function.** A file with fifteen single-write functions is fine\nand will still be flagged: it narrows all repositories down to a handful worth opening, and then you count\nthe writes *inside the function*. Confirm before reporting anything.\n\nTwo shapes come back as candidates and are **not** violations — recognise them and move on:\n\n- **Upsert branches.** `SELECT` to check existence, then `INSERT` *or* `UPDATE`. Two writes in the text, one\n  per execution path. (Worth a separate look for the check-then-act race, which a unique index closes — but\n  it is not the transaction rule.)\n- **A read function with many executes.** Four `SELECT`s in a loader are four executes and zero writes.\n\nWhat survives is the real shape: **two writes on different rows or tables, in sequence, on the same path.**\n\nA function whose name or docstring promises all-or-nothing semantics (\"atomic\", \"bulk replace\", \"publish\",\n\"transition\") and has no transaction is a **critical** finding, not a warning. If the function only delegates\nto another repository that already opens the transaction, it is fine.\n\n## 7. Caching with a circuit breaker\n\nCache in the **repository**, never in the query or the controller. A cache is an optimization: when the cache\nstore is down the endpoint keeps answering from the database, so the cache client sits behind a circuit\nbreaker and a failed read is a miss, not a 500. Bound every in-memory cache with a size **and** a TTL.\n\n## 8. Validation at the edge\n\nThe schema validates at the route, the controller reads the already-validated value. Never re-validate by\nhand inside the controller, and never read `c.req.query()` raw when a validated schema exists.\n\n**Lenient in the request, strict in the response.** An invalid optional parameter (a bad language code) is\ntreated as *absent* and resolved by the server fallback — never a 422 caused by that field alone. The same\nfield in a response or an entity stays strict: the documented contract does not bend.\n\n## 8b. Concurrent edits: the conditional write is an API contract\n\nAn optimistic editor in the client prevents nothing while the API still accepts an unconditional\nlast-write-wins update. The rule lives on the server:\n\n- **Reads return a version or content identity**; writes require it; a stale write is rejected with a\n  machine-readable precondition failure, and the newer server value is left untouched.\n- **The lifecycle crosses the client boundary**: capture the identity when the editor opens, attach it to\n  the write, and replace it with the response's identity after a successful save. A test that proves the\n  header actually crosses that boundary is the only thing that proves the feature.\n- **A precondition failure without a recovery path is a safe dead end.** The client has to say that another\n  writer won and offer an explicit reload of the authoritative representation together with its new\n  identity — otherwise the operator is stuck holding edits they cannot apply.\n- **An atomic lock does not make two incompatible transitions both valid.** Two concurrent transitions out\n  of the same state are serialised, and the second one *correctly* fails. A concurrency test asserts\n  atomicity **and** explicit conflict handling — never that both writes commit.\n\n## 8c. A stream is transport, and transport does not remember\n\n- **Filter by authenticated tenant before writing to the stream**, emit bounded heartbeats, and clean up the\n  subscription on **both** request abort and response close.\n- **Reconnect restores a socket, not the events lost while it was down.** Refetch the durable projection on\n  the reconnect edge; use individual events only as low-latency invalidation hints.\n- **Event ids alone are not replay.** Persist the event before publishing the notification, subscribe before\n  replaying, deduplicate the overlap, and signal a missing or expired cursor explicitly rather than\n  returning an empty result. See **`padosoft-durable-effects`**.\n- **A passing stream-writer test is not a live journey.** The causal proof is: create the subscriber,\n  publish a tenant-scoped event, parse it in the real client, render the connection state, assert it there.\n\n---\n\n## Gotchas\n\nThese are the ones that come back in review:\n\n**0. An identifier that crosses a trust boundary needs a real random source.** A UUID-shaped string built\nfrom the ordinary pseudo-random generator is not a security identifier, and it looks exactly like one.\nQueue, job and event ids cross tenant and retry boundaries: use the runtime's cryptographic generator.\n\n**1. `null` instead of an empty array.** The controller expects a list.\n\n```ts\nif (!rows.length) return null;   \u002F\u002F ❌ callers crash on .map\nif (!rows.length) return [];     \u002F\u002F ✅\n```\n\n**2. Pagination offset.** `offset = page * perPage` makes page 1 skip the first page.\n\n```ts\nconst offset = (page - 1) * perPage;   \u002F\u002F ✅ page 1 → 0\n```\n\n**3. A CSV string passed where an array is expected.** `\"1,7,9\"` is one element, not three. Split and coerce\nto numbers first.\n\n**4. Params of a dynamic `IN` not merged** — see §5. The symptom is `Unknown parameter :id_0`.\n\n**5. Language fallback in application code** instead of SQL `COALESCE` — see §5.\n\n**6. A type assertion on the context** — see §2. It always means a missing `Variables` entry.\n\n**7. `rows[0]` on a query that can return more than one row with no `ORDER BY`.** Which row arrives first is\nthe engine's choice, so the behaviour changes without the code changing.\n\n**8. `LIMIT`\u002F`OFFSET` are interpolated on purpose.** The driver does not bind them as named placeholders, so\nthe layering gives way here and the values are inlined. Do not \"fix\" one back into `:limit`: the query\nbreaks. Make sure the value is a schema-coerced number and leave it alone.\n\n---\n\n## Checklist before committing\n\n- [ ] Query returns `[sql, params] as const` and contains no business logic\n- [ ] Repository returns `[]` and not `null`; transformations live here\n- [ ] Controller does no SQL and throws `ApiError` instead of returning an error shape\n- [ ] No `as` on a context read; `Variables` updated if one was needed\n- [ ] Middleware built with the factory\n- [ ] Named placeholders only; `IN` params merged; translation join constrained in its own `ON`\n- [ ] Two or more writes in one repository function → transaction\n- [ ] `env` imported from the validated module\n- [ ] Offset computed as `(page - 1) * perPage`\n- [ ] Linter and type check clean\n\n## Final report\n\n```\nEndpoint\u002Fchange: \u003Cwhat>\nLayers: controller \u003Cfile> · repository \u003Cfile> · query \u003Cfile>\nConventions: \u003Cn> respected, \u003Cn> deviations (with reason)\nGotchas checked: null-vs-[] · offset · IN merge · localization · context typing · transactions\nLinter\u002Ftypes: PASS | FAIL \u003Cdetail>\nTo decide: \u003C…>\n```\n",{"name":5,"license":14,"metadata":23,"description":7,"compatibility":31},{"scope":24,"author":25,"summary":26,"version":27,"keywords":28,"profiles":29,"repository":30},"project","Padosoft","Three layers one direction, typed context, bound SQL, and the mistakes that keep returning.","0.2.0","hono, bun, typescript, api, architecture, repository, sql, middleware, zod","node, api","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills","Hono on Bun with TypeScript. The database patterns assume a driver with named placeholders (mysql2 style); the layering and typing rules hold with any driver.","main","8ff266762b08cab7f5be5551fa221309dc9db48b","skills\u002Fpadosoft-hono-api-conventions",0,"https:\u002F\u002Fgithub.com\u002Fpadosoft","https:\u002F\u002Fwww.padosoft.com","Software House","2026-10-19 01:02:17",{"source":8,"skillName":5,"commands":41,"prompt":51,"zipAvailable":52},[42,45,48],{"tool":43,"command":44},"npx","npx skills add padosoft\u002Fskills --skill padosoft-hono-api-conventions",{"tool":46,"command":47},"bunx","bunx skills add padosoft\u002Fskills --skill padosoft-hono-api-conventions",{"tool":49,"command":50},"pnpm","pnpm dlx skills add padosoft\u002Fskills --skill padosoft-hono-api-conventions","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fpadosoft-hono-api-conventions\u002FSKILL.md",true,[54],{"path":55,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":58,"sourceHtmlUrl":59},"evals\u002Fqueries.json","REFERENCE","参考文档",1945,"https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fpadosoft-hono-api-conventions\u002Fevals\u002Fqueries.json",[61,68,74,81,88,94],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7CZNKCTMWK7F2J6KKPAR8YM","report-opus","Writes the weekly status report from the team's tickets. Use when the user asks for the weekly report or a status summary. Do not use it for incident reports.","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-audit\u002Fproject\u002Fdot-claude\u002Fskills\u002Freport-opus\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M7CZNFEN8XK6S8NC6KGREYGS","report-haiku","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-audit\u002Fproject\u002Fdot-claude\u002Fskills\u002Freport-haiku\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":18},"01M7CZND182TKGGM7R4134ND00","kitt-stub","Builds the guided-tour reference for an admin page. Use when the user asks for the tour reference. Trigger \"tour\", \"reference\", \"guided tour\".","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-audit\u002Fproject\u002Fdot-claude\u002Fskills\u002Fkitt-stub\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":18},"01M7CZN9F2A6BFTFW5RSRNAGB1","good-skill","Generates the release notes of a project from its merged pull requests. Use this skill when the user asks for release notes, a changelog entry or a summary of what shipped since the last tag. Do not use it to write commit messages, that is the job of a commit skill.","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-audit\u002Fproject\u002Fdot-claude\u002Fskills\u002Fgood-skill\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":18},"01M7CZN6BJASPD4DH8DFR63GQF","broken-frontmatter","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-audit\u002Fproject\u002Fdot-claude\u002Fskills\u002Fbroken-frontmatter\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":18},"01M7CZN498TRNC30GSYMMAZNXM","Bad_Skill","I can help you with reports.","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-audit\u002Fproject\u002Fdot-claude\u002Fskills\u002Fbad-skill\u002FSKILL.md",[],[]]