[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79GK1VZXTVT3X0W4V0EYW9F":3,"skill-same:01M79GK1VZXTVT3X0W4V0EYW9F":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M79GK1VZXTVT3X0W4V0EYW9F","saasaloy-feature-flags",null,"Runbook for the feature-flags module — typed flags with per-tenant overrides and percentage rollouts, resolved through an isolate cache over a published kv document with the database as the source of truth, plus maintenance mode and per-integration kill switches. Use when adding a flag key, toggling a flag, rolling one out to a share of users, overriding a flag for one tenant, closing the site for maintenance, switching off payments or AI or email, or working out why a toggle has not taken effect yet.","mimukit\u002Fsaasaloy","mimukit","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F11677026?v=4","01M79GFSERAQQ77QPQMC1N0Y6M","Mukitul Islam Mukit","01M79GFSFA4WMGEEBHA68N59WV",4,"MIT","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Ffeature-flags\u002Fskills\u002Fsaasaloy-feature-flags\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: saasaloy-feature-flags\ndescription: Runbook for the feature-flags module — typed flags with per-tenant overrides and percentage rollouts, resolved through an isolate cache over a published kv document with the database as the source of truth, plus maintenance mode and per-integration kill switches. Use when adding a flag key, toggling a flag, rolling one out to a share of users, overriding a flag for one tenant, closing the site for maintenance, switching off payments or AI or email, or working out why a toggle has not taken effect yet.\n---\n\n# feature-flags — typed flags, rollouts, maintenance mode and kill switches\n\n`feature-flags` ships one package and eight files:\n\n| File | What it holds |\n|---|---|\n| `packages\u002Ffeature-flags\u002F` | the registry, the resolver, the isolate cache and the bucketing |\n| `apps\u002Fapi\u002Fsrc\u002Froutes\u002Ffeature-flags.ts` | the admin API at `\u002Fadmin\u002Fflags`; every route lists `adminGate` before `validateValue`, and every write runs through `adminWrite` |\n| `apps\u002Fapi\u002Fsrc\u002Faudit\u002Ffeature-flags.ts` | the three audit actions of those writes |\n| `apps\u002Fapi\u002Fsrc\u002Flib\u002Fflags.ts` | `flagsFor(c)`, the database source, and `sessionIsAdmin` |\n| `apps\u002Fapi\u002Fsrc\u002Fmiddleware\u002Fmaintenance.ts` | the 503 page middleware |\n| `packages\u002Fdb\u002Fsrc\u002Fschema\u002Ffeature-flags.ts` | `feature_flags` and `feature_flag_overrides` |\n| `packages\u002Fdb\u002Fsrc\u002Frepositories\u002Ffeature-flags.ts` | every query those tables need |\n| `packages\u002Fvalidators\u002Fsrc\u002Ffeature-flags.ts` | the write body schema, shared by the route and `hc` |\n| `packages\u002Fui\u002Fsrc\u002Fblocks\u002Fadmin\u002Ffeature-flags.tsx` + `apps\u002Fadmin\u002Fsrc\u002Froutes\u002Fflags.tsx` | the Flags screen |\n\n## Where a value comes from\n\nThe database is the source of truth. `kv` is a **published read cache**, and the isolate cache in front of it is a plain `Map`.\n\nA read walks three levels, cheapest first:\n\n1. the isolate's `Map`, for `FLAGS_ISOLATE_TTL_SECONDS` (default 10),\n2. the published kv document for the scope — `flags:v1:global`, or `flags:v1:t:\u003CtenantId>`,\n3. the database, which also publishes the missing document.\n\nA *value* then resolves in this order: the tenant override, the global row, the code default.\n\n**A reader never writes on a hit.** The only write a read can do is publishing a document that was missing entirely, which happens once per scope per location (a colo reading inside the up-to-60-second window after a publish republishes the same content), not once per colo per request. Write-back on every read would scale KV writes with traffic, and the free plan allows 1,000 writes a day. Published this way, KV writes equal toggles.\n\n## Reading a flag\n\n```ts\nimport { flagsFor } from \"..\u002Flib\u002Fflags\";\n\nexport const checkout = new Hono().post(\"\u002F\", async (c) => {\n  const flags = flagsFor(c);\n\n  if (await flags.flag(\"subscription.new-checkout\", { subjectId: user.id, tenantId: org.id })) {\n    return newCheckout(c);\n  }\n  return oldCheckout(c);\n});\n```\n\n`subjectId` and `tenantId` are both optional and both passed in by you. A missing `tenantId` resolves the global value, which is right for a single-tenant project. A missing `subjectId` makes a percentage flag resolve **false** — there is nothing to bucket, and guessing would make a retry of the same request answer differently.\n\n## Adding a flag\n\nTwo steps, and the first one needs a deploy:\n\n```ts\n\u002F\u002F packages\u002Ffeature-flags\u002Fsrc\u002Fflags\u002Fapp.ts — your file, beside the module's system.ts\nimport { defineFlag } from \"..\u002Fdefine\";\n\nexport function newCheckout() {\n  return defineFlag({\n    key: \"subscription.new-checkout\",\n    type: \"percentage\",\n    default: false,\n    description: \"Route checkout through the new provider.\",\n  });\n}\n```\n\n```ts\n\u002F\u002F packages\u002Ffeature-flags\u002Fsrc\u002Findex.ts\nexport const flags = defineFlags({\n  flags: [maintenanceFlag(), killPayments(), killAi(), killEmail(), newCheckout()],\n});\n```\n\n`flag()`'s key set is inferred from that array, so a call with an unregistered key fails `pnpm typecheck` rather than resolving to a default at runtime. That is the trade: **a new key needs a deploy, a new value does not.**\n\nPut your own flags in your own file. `src\u002Fflags\u002Fsystem.ts` belongs to the module and `saasaloy update` may rewrite it.\n\n## The 70 seconds\n\nA toggle in the admin app reaches every location in **about 70 seconds**, and the two numbers that add up to it are:\n\n| Layer | Delay | Why |\n|---|---|---|\n| Workers KV propagation | up to ~60 s | KV is eventually consistent between locations |\n| the isolate `Map` | up to `FLAGS_ISOLATE_TTL_SECONDS`, default 10 s | expiry with no invalidation — nothing can reach into another colo's isolate |\n\nThe isolate that served the toggle drops its own copy immediately, so *you* see the change on your next request. Everyone else waits.\n\nRaise `FLAGS_ISOLATE_TTL_SECONDS` to spend fewer KV reads and wait longer; set it to `0` to skip that layer and pay a KV read per request. At the default a warm isolate costs about 8,640 reads a day, well inside the free plan's 100,000. A value that is not a whole number throws while the Worker initializes rather than falling back to 10.\n\n**The published document has no TTL.** The admin routes republish on every change, so there is nothing an expiry would fix.\n\n## The admin screen reads the database, never the cache\n\n`GET \u002Fadmin\u002Fflags` queries the tables directly. That is deliberate: the published document is up to a minute behind, and showing an operator a stale copy of the switch they just moved is the failure the split exists to prevent. The cost is the other way round — the screen can be *ahead* of what a live request sees, for about a minute after a toggle.\n\nEvery write route writes the row, then republishes. The republish is queued with `afterCommit`, so it runs only after the row commits, and a kv document never shows a value whose write rolled back. It runs on `waitUntil`, so the write answers `{ ok: true }` without waiting for kv, and a failed publish is logged at `error` rather than failing the write. A tenant write republishes the global document too, so the two documents a tenant request reads were built from the same database state.\n\n## Admin routes and their audit rows\n\nThe `chained-route` patch mounts `apps\u002Fapi\u002Fsrc\u002Froutes\u002Ffeature-flags.ts` at `\u002Fadmin\u002Fflags`, so the admin app calls it as `api.admin.flags`. It sits under `\u002Fadmin\u002F` so the `admin` module's gate test and audit coverage test see every route.\n\nA project made before the move to `\u002Fadmin\u002Fflags` keeps the old `.route(\"\u002Fflags\", featureFlags)` link after `saasaloy update`, because update never reverses a patch the new revision dropped. The update note `feature-flags\u002F0001-admin-flags-mount` tells you to delete that line. Until you do, both paths serve the same handlers, and the gate and coverage tests cannot see the `\u002Fflags` copy.\n\n| Route | Audit action | Label |\n| --- | --- | --- |\n| `GET \u002Fadmin\u002Fflags` | none, a read | |\n| `GET \u002Fadmin\u002Fflags\u002F:key` | none, a read | |\n| `PUT \u002Fadmin\u002Fflags\u002F:key` | `flag.value.set` | the flag key |\n| `PUT \u002Fadmin\u002Fflags\u002F:key\u002Ftenants\u002F:tenantId` | `flag.tenant.set` | `\u003Ckey> · tenant \u003CtenantId>` |\n| `DELETE \u002Fadmin\u002Fflags\u002F:key\u002Ftenants\u002F:tenantId` | `flag.tenant.clear` | `\u003Ckey> · tenant \u003CtenantId>` |\n\nEach write runs through `adminWrite` from `apps\u002Fapi\u002Fsrc\u002Flib\u002Fadmin-write.ts`. The area is `flags`, the target type is `flag`, and the target id is the flag key, so a filter by target finds the global value and every tenant override of one flag. A row records `before` and `after` for `enabled` and `percentage`. A first write has no `before`. Clearing an override that does not exist changes nothing and writes no row. The actions live in `apps\u002Fapi\u002Fsrc\u002Faudit\u002Ffeature-flags.ts`, which this module's `plugin-array` patch registers in `apps\u002Fapi\u002Fsrc\u002Flib\u002Faudit-actions.ts`. A new write route here needs an entry there, or the audit coverage test fails.\n\n## Percentage rollouts\n\nBucketing is FNV-1a 32-bit over `\"\u003CflagKey>:\u003CsubjectId>\"`, modulo 100. It is synchronous, has no dependencies, and is stable: one subject gets the same answer on every request, in every colo, for as long as the share does not move.\n\nThe flag key is in the hash, not just the subject. Two flags at 10% therefore reach different tenths of the audience — bucketing on the subject alone would make the second rollout a subset of the first, and the second experiment would measure the first.\n\nWeb Crypto was rejected for this. `crypto.subtle.digest` is async, so every `flag()` call would await a digest even for a boolean flag that never buckets.\n\nRaising a share keeps everyone who was already in it: a subject's bucket does not move, so 10% → 20% adds subjects and removes none. **Lowering it removes people who had the feature.**\n\n## Maintenance mode\n\n`system.maintenance` is an ordinary boolean flag. The middleware is not patched in anywhere, because which paths stay reachable is your decision:\n\n```ts\n\u002F\u002F apps\u002Fapi\u002Fsrc\u002Findex.ts\nimport { maintenance } from \".\u002Fmiddleware\u002Fmaintenance\";\nimport { flagsFor, sessionIsAdmin } from \".\u002Flib\u002Fflags\";\n\napp.use(\n  maintenance({\n    flags: flagsFor,\n    isAdmin: sessionIsAdmin,\n    bypassPaths: [\"\u002Fhealth\", \"\u002Fauth\", \"\u002Fadmin\u002Fauth\", \"\u002Fadmin\u002Fflags\"],\n  })\n);\n```\n\nThree ways past the page, checked in this order: the path is on the bypass list, the flag is off, or the caller is an admin. The path check runs first because it costs no flag read. `sessionIsAdmin` reads the admin session through `getAdminSession`, whatever `x-auth-audience` says, and passes any role in `ADMIN_ROLES` (`admin` and `superadmin`). A client session never counts, even one that belongs to a superadmin.\n\nPut `\u002Fhealth` on the bypass list. A load balancer that gets a 503 may pull the Worker out of rotation. Put `\u002Fadmin\u002Fauth` there too, or an admin cannot sign in on the admin app to turn maintenance back off, and `\u002Fadmin\u002Fflags`, or they cannot reach the switch once signed in. `\u002Fauth` is the client sign-in; leave it on the list only if clients may sign in while the site is closed. A prefix matches whole segments, so `\u002Fauth` does not cover `\u002Fadmin\u002Fauth`.\n\nIf the flag cannot be resolved at all, the request goes through. A store outage should not take an api down on the assumption that somebody meant to close it.\n\n## Kill switches\n\n`kill.\u003Cintegration>` keys drive `assertEnabled`:\n\n```ts\nimport { KillSwitchError } from \"@repo\u002Ffeature-flags\";\nimport { flagsFor } from \"..\u002Flib\u002Fflags\";\n\nawait flagsFor(c).assertEnabled(\"payments\"); \u002F\u002F throws KillSwitchError while kill.payments is off\n```\n\nThree ship: `kill.payments`, `kill.ai`, `kill.email`. All three **default to on**, because a kill switch is off-by-exception and a flag store that has never been published must not stop a project charging its customers. `system.maintenance` defaults off for the same reason read the other way.\n\n`assertEnabled` takes the name without the prefix, and the name is typed: `assertEnabled(\"paymnets\")` fails `pnpm typecheck`.\n\n## Settings\n\n| Key | Default | What it does |\n|---|---|---|\n| `FLAGS_ISOLATE_TTL_SECONDS` | `10` | Seconds an isolate serves its cached document. `0` disables the layer. |\n\nThe kv settings apply too: `KV_PROVIDER` selects the store and `KV_KEY_PREFIX` prefixes the document keys. Two environments sharing one namespace need different prefixes, or they share their flags.\n\n## Troubleshooting\n\n| Symptom | Cause |\n|---|---|\n| A toggle has not taken effect after 20 seconds | Normal. Wait ~70 s. Check again from a different location before you go looking for a bug. |\n| Every flag reads as its code default | The document has never been published and the database has no rows. That is the correct state for a fresh install — toggle something. |\n| A percentage flag is off for everyone | No `subjectId` is being passed. There is nothing to bucket, so it resolves false. |\n| A tenant sees the global value | No override row exists for that tenant, or `tenantId` is not being passed to `flag()`. |\n| `Flag \"x.y\" is not registered` | The key is not in the `flags` array in `packages\u002Ffeature-flags\u002Fsrc\u002Findex.ts`. A new key needs a deploy. |\n| `FLAGS_ISOLATE_TTL_SECONDS is \"10s\"` at startup | Whole seconds, no unit. Use `10`. |\n| The admin screen shows a value a live route does not | Expected for about a minute after a toggle. The screen reads the database; the route reads the published document. |\n\n## Upgrading from singular table names\n\nThis module used to name its tables `feature_flag` and `feature_flag_override`. It now names them `feature_flags` and `feature_flag_overrides`. A project that installed the old names upgrades them with one migration:\n\n1. Run `saasaloy update feature-flags` to take the new schema file.\n2. Run `pnpm --filter @repo\u002Fdb db:generate`.\n3. drizzle-kit asks, for each new table, whether it is created or renamed from an existing table. Pick the rename from the old name: `feature_flag` → `feature_flags`, and `feature_flag_override` → `feature_flag_overrides`.\n4. Read the generated SQL before you apply it. It must rename the tables and the `feature_flag_override_key_tenant_idx` index (`ALTER TABLE ... RENAME TO ...`), and contain no `DROP TABLE` or `CREATE TABLE` for a table that holds data.\n5. If it drops a table, delete that migration file and run `pnpm --filter @repo\u002Fdb db:generate` again.\n6. Apply the migration with your driver's command, then open the admin Flags screen to confirm that it lists your flags.\n\n## What `remove` leaves behind\n\nThe `feature_flags` and `feature_flag_overrides` tables survive removal — run `db:generate` and read the drop migration before applying it. The published documents survive too: they have no TTL, so `flags:v1:global` and every `flags:v1:t:\u003CtenantId>` stay in the namespace until `wrangler kv key delete` removes them.\n\nIf you wired `maintenance()` into `apps\u002Fapi\u002Fsrc\u002Findex.ts` by hand, remove that line yourself. `saasaloy remove` does not undo an edit you made.\n\n## Wire-up\n\n`add feature-flags` writes the block and the screen that renders it, so no page needs a manual import. The block lands at `packages\u002Fui\u002Fsrc\u002Fblocks\u002Fadmin\u002Ffeature-flags.tsx`, the route at `apps\u002Fadmin\u002Fsrc\u002Froutes\u002Fflags.tsx`, and a `nav-entry` patch adds Flags to `NAV_AREAS` in `apps\u002Fadmin\u002Fsrc\u002Fcomponents\u002Fnav.ts`.\n\n1. Run `pnpm db:generate` and apply the migration with your driver's command, so the two flag tables exist.\n2. Run `pnpm dev`, sign in to `admin` as an admin, and open `\u002Fflags`. The router plugin regenerates `routeTree.gen.ts` on the first start.\n3. When the screen is missing from the nav, check that `NAV_AREAS` still holds the Flags entry. A hand edit to `nav.ts` can drop it.\n\n## Next\n\nRun `saasaloy-admin` to change the Flags screen or add a staff screen beside it.\n","# feature-flags — typed flags, rollouts, maintenance mode and kill switches\n\n`feature-flags` ships one package and eight files:\n\n| File | What it holds |\n|---|---|\n| `packages\u002Ffeature-flags\u002F` | the registry, the resolver, the isolate cache and the bucketing |\n| `apps\u002Fapi\u002Fsrc\u002Froutes\u002Ffeature-flags.ts` | the admin API at `\u002Fadmin\u002Fflags`; every route lists `adminGate` before `validateValue`, and every write runs through `adminWrite` |\n| `apps\u002Fapi\u002Fsrc\u002Faudit\u002Ffeature-flags.ts` | the three audit actions of those writes |\n| `apps\u002Fapi\u002Fsrc\u002Flib\u002Fflags.ts` | `flagsFor(c)`, the database source, and `sessionIsAdmin` |\n| `apps\u002Fapi\u002Fsrc\u002Fmiddleware\u002Fmaintenance.ts` | the 503 page middleware |\n| `packages\u002Fdb\u002Fsrc\u002Fschema\u002Ffeature-flags.ts` | `feature_flags` and `feature_flag_overrides` |\n| `packages\u002Fdb\u002Fsrc\u002Frepositories\u002Ffeature-flags.ts` | every query those tables need |\n| `packages\u002Fvalidators\u002Fsrc\u002Ffeature-flags.ts` | the write body schema, shared by the route and `hc` |\n| `packages\u002Fui\u002Fsrc\u002Fblocks\u002Fadmin\u002Ffeature-flags.tsx` + `apps\u002Fadmin\u002Fsrc\u002Froutes\u002Fflags.tsx` | the Flags screen |\n\n## Where a value comes from\n\nThe database is the source of truth. `kv` is a **published read cache**, and the isolate cache in front of it is a plain `Map`.\n\nA read walks three levels, cheapest first:\n\n1. the isolate's `Map`, for `FLAGS_ISOLATE_TTL_SECONDS` (default 10),\n2. the published kv document for the scope — `flags:v1:global`, or `flags:v1:t:\u003CtenantId>`,\n3. the database, which also publishes the missing document.\n\nA *value* then resolves in this order: the tenant override, the global row, the code default.\n\n**A reader never writes on a hit.** The only write a read can do is publishing a document that was missing entirely, which happens once per scope per location (a colo reading inside the up-to-60-second window after a publish republishes the same content), not once per colo per request. Write-back on every read would scale KV writes with traffic, and the free plan allows 1,000 writes a day. Published this way, KV writes equal toggles.\n\n## Reading a flag\n\n```ts\nimport { flagsFor } from \"..\u002Flib\u002Fflags\";\n\nexport const checkout = new Hono().post(\"\u002F\", async (c) => {\n  const flags = flagsFor(c);\n\n  if (await flags.flag(\"subscription.new-checkout\", { subjectId: user.id, tenantId: org.id })) {\n    return newCheckout(c);\n  }\n  return oldCheckout(c);\n});\n```\n\n`subjectId` and `tenantId` are both optional and both passed in by you. A missing `tenantId` resolves the global value, which is right for a single-tenant project. A missing `subjectId` makes a percentage flag resolve **false** — there is nothing to bucket, and guessing would make a retry of the same request answer differently.\n\n## Adding a flag\n\nTwo steps, and the first one needs a deploy:\n\n```ts\n\u002F\u002F packages\u002Ffeature-flags\u002Fsrc\u002Fflags\u002Fapp.ts — your file, beside the module's system.ts\nimport { defineFlag } from \"..\u002Fdefine\";\n\nexport function newCheckout() {\n  return defineFlag({\n    key: \"subscription.new-checkout\",\n    type: \"percentage\",\n    default: false,\n    description: \"Route checkout through the new provider.\",\n  });\n}\n```\n\n```ts\n\u002F\u002F packages\u002Ffeature-flags\u002Fsrc\u002Findex.ts\nexport const flags = defineFlags({\n  flags: [maintenanceFlag(), killPayments(), killAi(), killEmail(), newCheckout()],\n});\n```\n\n`flag()`'s key set is inferred from that array, so a call with an unregistered key fails `pnpm typecheck` rather than resolving to a default at runtime. That is the trade: **a new key needs a deploy, a new value does not.**\n\nPut your own flags in your own file. `src\u002Fflags\u002Fsystem.ts` belongs to the module and `saasaloy update` may rewrite it.\n\n## The 70 seconds\n\nA toggle in the admin app reaches every location in **about 70 seconds**, and the two numbers that add up to it are:\n\n| Layer | Delay | Why |\n|---|---|---|\n| Workers KV propagation | up to ~60 s | KV is eventually consistent between locations |\n| the isolate `Map` | up to `FLAGS_ISOLATE_TTL_SECONDS`, default 10 s | expiry with no invalidation — nothing can reach into another colo's isolate |\n\nThe isolate that served the toggle drops its own copy immediately, so *you* see the change on your next request. Everyone else waits.\n\nRaise `FLAGS_ISOLATE_TTL_SECONDS` to spend fewer KV reads and wait longer; set it to `0` to skip that layer and pay a KV read per request. At the default a warm isolate costs about 8,640 reads a day, well inside the free plan's 100,000. A value that is not a whole number throws while the Worker initializes rather than falling back to 10.\n\n**The published document has no TTL.** The admin routes republish on every change, so there is nothing an expiry would fix.\n\n## The admin screen reads the database, never the cache\n\n`GET \u002Fadmin\u002Fflags` queries the tables directly. That is deliberate: the published document is up to a minute behind, and showing an operator a stale copy of the switch they just moved is the failure the split exists to prevent. The cost is the other way round — the screen can be *ahead* of what a live request sees, for about a minute after a toggle.\n\nEvery write route writes the row, then republishes. The republish is queued with `afterCommit`, so it runs only after the row commits, and a kv document never shows a value whose write rolled back. It runs on `waitUntil`, so the write answers `{ ok: true }` without waiting for kv, and a failed publish is logged at `error` rather than failing the write. A tenant write republishes the global document too, so the two documents a tenant request reads were built from the same database state.\n\n## Admin routes and their audit rows\n\nThe `chained-route` patch mounts `apps\u002Fapi\u002Fsrc\u002Froutes\u002Ffeature-flags.ts` at `\u002Fadmin\u002Fflags`, so the admin app calls it as `api.admin.flags`. It sits under `\u002Fadmin\u002F` so the `admin` module's gate test and audit coverage test see every route.\n\nA project made before the move to `\u002Fadmin\u002Fflags` keeps the old `.route(\"\u002Fflags\", featureFlags)` link after `saasaloy update`, because update never reverses a patch the new revision dropped. The update note `feature-flags\u002F0001-admin-flags-mount` tells you to delete that line. Until you do, both paths serve the same handlers, and the gate and coverage tests cannot see the `\u002Fflags` copy.\n\n| Route | Audit action | Label |\n| --- | --- | --- |\n| `GET \u002Fadmin\u002Fflags` | none, a read | |\n| `GET \u002Fadmin\u002Fflags\u002F:key` | none, a read | |\n| `PUT \u002Fadmin\u002Fflags\u002F:key` | `flag.value.set` | the flag key |\n| `PUT \u002Fadmin\u002Fflags\u002F:key\u002Ftenants\u002F:tenantId` | `flag.tenant.set` | `\u003Ckey> · tenant \u003CtenantId>` |\n| `DELETE \u002Fadmin\u002Fflags\u002F:key\u002Ftenants\u002F:tenantId` | `flag.tenant.clear` | `\u003Ckey> · tenant \u003CtenantId>` |\n\nEach write runs through `adminWrite` from `apps\u002Fapi\u002Fsrc\u002Flib\u002Fadmin-write.ts`. The area is `flags`, the target type is `flag`, and the target id is the flag key, so a filter by target finds the global value and every tenant override of one flag. A row records `before` and `after` for `enabled` and `percentage`. A first write has no `before`. Clearing an override that does not exist changes nothing and writes no row. The actions live in `apps\u002Fapi\u002Fsrc\u002Faudit\u002Ffeature-flags.ts`, which this module's `plugin-array` patch registers in `apps\u002Fapi\u002Fsrc\u002Flib\u002Faudit-actions.ts`. A new write route here needs an entry there, or the audit coverage test fails.\n\n## Percentage rollouts\n\nBucketing is FNV-1a 32-bit over `\"\u003CflagKey>:\u003CsubjectId>\"`, modulo 100. It is synchronous, has no dependencies, and is stable: one subject gets the same answer on every request, in every colo, for as long as the share does not move.\n\nThe flag key is in the hash, not just the subject. Two flags at 10% therefore reach different tenths of the audience — bucketing on the subject alone would make the second rollout a subset of the first, and the second experiment would measure the first.\n\nWeb Crypto was rejected for this. `crypto.subtle.digest` is async, so every `flag()` call would await a digest even for a boolean flag that never buckets.\n\nRaising a share keeps everyone who was already in it: a subject's bucket does not move, so 10% → 20% adds subjects and removes none. **Lowering it removes people who had the feature.**\n\n## Maintenance mode\n\n`system.maintenance` is an ordinary boolean flag. The middleware is not patched in anywhere, because which paths stay reachable is your decision:\n\n```ts\n\u002F\u002F apps\u002Fapi\u002Fsrc\u002Findex.ts\nimport { maintenance } from \".\u002Fmiddleware\u002Fmaintenance\";\nimport { flagsFor, sessionIsAdmin } from \".\u002Flib\u002Fflags\";\n\napp.use(\n  maintenance({\n    flags: flagsFor,\n    isAdmin: sessionIsAdmin,\n    bypassPaths: [\"\u002Fhealth\", \"\u002Fauth\", \"\u002Fadmin\u002Fauth\", \"\u002Fadmin\u002Fflags\"],\n  })\n);\n```\n\nThree ways past the page, checked in this order: the path is on the bypass list, the flag is off, or the caller is an admin. The path check runs first because it costs no flag read. `sessionIsAdmin` reads the admin session through `getAdminSession`, whatever `x-auth-audience` says, and passes any role in `ADMIN_ROLES` (`admin` and `superadmin`). A client session never counts, even one that belongs to a superadmin.\n\nPut `\u002Fhealth` on the bypass list. A load balancer that gets a 503 may pull the Worker out of rotation. Put `\u002Fadmin\u002Fauth` there too, or an admin cannot sign in on the admin app to turn maintenance back off, and `\u002Fadmin\u002Fflags`, or they cannot reach the switch once signed in. `\u002Fauth` is the client sign-in; leave it on the list only if clients may sign in while the site is closed. A prefix matches whole segments, so `\u002Fauth` does not cover `\u002Fadmin\u002Fauth`.\n\nIf the flag cannot be resolved at all, the request goes through. A store outage should not take an api down on the assumption that somebody meant to close it.\n\n## Kill switches\n\n`kill.\u003Cintegration>` keys drive `assertEnabled`:\n\n```ts\nimport { KillSwitchError } from \"@repo\u002Ffeature-flags\";\nimport { flagsFor } from \"..\u002Flib\u002Fflags\";\n\nawait flagsFor(c).assertEnabled(\"payments\"); \u002F\u002F throws KillSwitchError while kill.payments is off\n```\n\nThree ship: `kill.payments`, `kill.ai`, `kill.email`. All three **default to on**, because a kill switch is off-by-exception and a flag store that has never been published must not stop a project charging its customers. `system.maintenance` defaults off for the same reason read the other way.\n\n`assertEnabled` takes the name without the prefix, and the name is typed: `assertEnabled(\"paymnets\")` fails `pnpm typecheck`.\n\n## Settings\n\n| Key | Default | What it does |\n|---|---|---|\n| `FLAGS_ISOLATE_TTL_SECONDS` | `10` | Seconds an isolate serves its cached document. `0` disables the layer. |\n\nThe kv settings apply too: `KV_PROVIDER` selects the store and `KV_KEY_PREFIX` prefixes the document keys. Two environments sharing one namespace need different prefixes, or they share their flags.\n\n## Troubleshooting\n\n| Symptom | Cause |\n|---|---|\n| A toggle has not taken effect after 20 seconds | Normal. Wait ~70 s. Check again from a different location before you go looking for a bug. |\n| Every flag reads as its code default | The document has never been published and the database has no rows. That is the correct state for a fresh install — toggle something. |\n| A percentage flag is off for everyone | No `subjectId` is being passed. There is nothing to bucket, so it resolves false. |\n| A tenant sees the global value | No override row exists for that tenant, or `tenantId` is not being passed to `flag()`. |\n| `Flag \"x.y\" is not registered` | The key is not in the `flags` array in `packages\u002Ffeature-flags\u002Fsrc\u002Findex.ts`. A new key needs a deploy. |\n| `FLAGS_ISOLATE_TTL_SECONDS is \"10s\"` at startup | Whole seconds, no unit. Use `10`. |\n| The admin screen shows a value a live route does not | Expected for about a minute after a toggle. The screen reads the database; the route reads the published document. |\n\n## Upgrading from singular table names\n\nThis module used to name its tables `feature_flag` and `feature_flag_override`. It now names them `feature_flags` and `feature_flag_overrides`. A project that installed the old names upgrades them with one migration:\n\n1. Run `saasaloy update feature-flags` to take the new schema file.\n2. Run `pnpm --filter @repo\u002Fdb db:generate`.\n3. drizzle-kit asks, for each new table, whether it is created or renamed from an existing table. Pick the rename from the old name: `feature_flag` → `feature_flags`, and `feature_flag_override` → `feature_flag_overrides`.\n4. Read the generated SQL before you apply it. It must rename the tables and the `feature_flag_override_key_tenant_idx` index (`ALTER TABLE ... RENAME TO ...`), and contain no `DROP TABLE` or `CREATE TABLE` for a table that holds data.\n5. If it drops a table, delete that migration file and run `pnpm --filter @repo\u002Fdb db:generate` again.\n6. Apply the migration with your driver's command, then open the admin Flags screen to confirm that it lists your flags.\n\n## What `remove` leaves behind\n\nThe `feature_flags` and `feature_flag_overrides` tables survive removal — run `db:generate` and read the drop migration before applying it. The published documents survive too: they have no TTL, so `flags:v1:global` and every `flags:v1:t:\u003CtenantId>` stay in the namespace until `wrangler kv key delete` removes them.\n\nIf you wired `maintenance()` into `apps\u002Fapi\u002Fsrc\u002Findex.ts` by hand, remove that line yourself. `saasaloy remove` does not undo an edit you made.\n\n## Wire-up\n\n`add feature-flags` writes the block and the screen that renders it, so no page needs a manual import. The block lands at `packages\u002Fui\u002Fsrc\u002Fblocks\u002Fadmin\u002Ffeature-flags.tsx`, the route at `apps\u002Fadmin\u002Fsrc\u002Froutes\u002Fflags.tsx`, and a `nav-entry` patch adds Flags to `NAV_AREAS` in `apps\u002Fadmin\u002Fsrc\u002Fcomponents\u002Fnav.ts`.\n\n1. Run `pnpm db:generate` and apply the migration with your driver's command, so the two flag tables exist.\n2. Run `pnpm dev`, sign in to `admin` as an admin, and open `\u002Fflags`. The router plugin regenerates `routeTree.gen.ts` on the first start.\n3. When the screen is missing from the nav, check that `NAV_AREAS` still holds the Flags entry. A hand edit to `nav.ts` can drop it.\n\n## Next\n\nRun `saasaloy-admin` to change the Flags screen or add a staff screen beside it.\n",{"name":5,"description":7},"main","5ecf3d110b216ef678e06a1630f6b63a8e730bb5","modules\u002Ffeature-flags\u002Fskills\u002Fsaasaloy-feature-flags",0,"https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy","https:\u002F\u002Fsaasaloy.com","https:\u002F\u002Fgithub.com\u002Fmimukit","https:\u002F\u002Fmimukit.com","Senior Software Engineer · 9+ yrs Fullstack (TS\u002FNode\u002FReact) · AI integrations, distributed systems · Building @saasaloy & @codealoy · Bangladesh 🇧🇩 \u002F Remote","2026-11-13 20:39:28",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add mimukit\u002Fsaasaloy --skill saasaloy-feature-flags",{"tool":40,"command":41},"bunx","bunx skills add mimukit\u002Fsaasaloy --skill saasaloy-feature-flags",{"tool":43,"command":44},"pnpm","pnpm dlx skills add mimukit\u002Fsaasaloy --skill saasaloy-feature-flags","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Ffeature-flags\u002Fskills\u002Fsaasaloy-feature-flags\u002FSKILL.md",true,[],[49,56,63,70,77,83],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7BE75C34XHSPVJNQC8FY4Q0","saasaloy-subscription","Runbook for the subscription capability — provider-agnostic subscriptions in packages\u002Fsubscription, with a plan file, a projection table, a billable-subject file, plan entitlements and per-provider modules. Use when adding a plan, adding a plan feature or a numeric limit, gating an API route with requireFeature or requireWithinLimit, reading the 402 it returns, working out why a subject resolves to the free plan, wiring a checkout or portal route, reading a SubscriptionError, choosing or switching SUBSCRIPTION_PROVIDER, registering a webhook in the vendor's dashboard, writing a third subscription provider, or upgrading a project that still has `billing` installed.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fsubscription\u002Fskills\u002Fsaasaloy-subscription\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7BE68MJ8H47JZKTBDFYR6JD","saasaloy-notification","Runbook for the notification module, in-app notifications for apps\u002Fapp. It owns the notifications and notification_opt_outs tables, notify() in apps\u002Fapi\u002Fsrc\u002Flib\u002Fnotify.ts, the \u002Fnotifications api routes, the bell in the app header, the sidebar badge, the \u002Fnotifications page with Inbox and Preferences tabs, the notification config section, and the daily prune. Use when sending a notification from an api route, adding or changing a category, changing retention, debugging a badge or bell count that does not move, or removing the module.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fnotification\u002Fskills\u002Fsaasaloy-notification\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7BE53PDQV0YDPG8RNVGTPEQ","saasaloy-cms","Runbook for the cms module, the in-house CMS behind apps\u002Fadmin. Covers code-defined collections, the Tiptap editor, drafts, revisions and redirects, the publish-time renderer, the public blog on apps\u002Fweb and its 60-second cache. Use when adding a collection or a field, rendering a stored body, reusing the editor, renderer or media field from another module, moving the blog to another path, re-rendering live posts after a renderer upgrade or a STORAGE_PUBLIC_URL change, or working out why a published post is not live yet.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fcms\u002Fskills\u002Fsaasaloy-cms\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M79GQ03M63V5EKSST92B3S5X","saasaloy-beta","The beta module's own procedure.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fpackages\u002Fcli\u002Ftest\u002Ffixtures\u002Fregistry-clean\u002Fbeta\u002Fsaasaloy-beta\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M79GPXV3K8YF3M4VA0KGVE0B","helper","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fpackages\u002Fcli\u002Ftest\u002Ffixtures\u002Fregistry-broken\u002Fbad-skill\u002Fhelper\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M79GPR8EVS1YX0W8X33Q9YD8","saasaloy-update","Runbook for an AI agent that updates this project to a newer Saasaloy CLI and newer module versions with saasaloy update. Use when the owner says \"update saasaloy\", \"upgrade the CLI\", \"pull the latest modules\", \"update the base template\", \"work the merge plan\", \"clear the update notes\", when saasaloy update or saasaloy outdated --check exits 3 or 2, when a merge plan or .saasaloy\u002Fmerge-plan.md is handed to you, or when an adopted project takes its first update. Covers the CLI upgrade, the preview, --out, the file merges, the update notes and \"Notes that may apply\", --resolved and --done, a file deleted locally and --restore, a three-way or two-way base, an update that skips releases, --from, the verify commands, and the exit codes.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fpackages\u002Fcli\u002Ftemplates\u002Fbase\u002F_agents\u002Fskills\u002Fsaasaloy-update\u002FSKILL.md",[],[]]