[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M78Z83KZXF6CCB4SBCY6V5CK":3,"skill-same:01M78Z83KZXF6CCB4SBCY6V5CK":63},{"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":43,"commitSha":44,"skillDirectory":45,"forksCount":14,"repositoryHtmlUrl":46,"repositoryHomepageUrl":6,"ownerHtmlUrl":47,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":48,"install":49,"resources":62},"01M78Z83KZXF6CCB4SBCY6V5CK","complexity-cuts",null,"Lower Big-O on existing code via a one-transformation-at-a-time playbook with verify-revert-stop. For new code use lemmaly; for math-level wins escalate to mathguard.","Elogic360\u002Fsoftware-factory","Elogic360","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F156535519?v=4","01M74NH3F0RB13PWB7JZDE2V80","elogic360","01M74NH3FPC65082MDZVMFHDM3",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fantigravity-skills\u002Fplugins\u002Fantigravity-awesome-skills\u002Fskills\u002Fcomplexity-cuts\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: complexity-cuts\ndescription: \"Lower Big-O on existing code via a one-transformation-at-a-time playbook with verify-revert-stop. For new code use lemmaly; for math-level wins escalate to mathguard.\"\nrisk: safe\nsource: community\nsource_repo: morsechimwai\u002Flemmaly\nsource_type: community\ndate_added: \"2026-05-26\"\nauthor: morsechimwai\ntags: [algorithms, big-o, refactoring, optimization, performance, n-plus-one]\ntools: [claude-code, antigravity, cursor, gemini-cli, codex-cli]\nlicense: \"Apache-2.0\"\nlicense_source: \"https:\u002F\u002Fgithub.com\u002Fmorsechimwai\u002Flemmaly\u002Fblob\u002Fmain\u002FLICENSE\"\n---\n\n# complexity-cuts — Lower Big-O on Existing Code\n\n`lemmaly` prevents bad complexity before code is written. **complexity-cuts** fixes it after the fact: code already exists, it works, but its time or space complexity is worse than necessary.\n\n**Violating the letter of these rules is violating the spirit of the skill.** Adapting \"just a little\" is how a faster-but-wrong rewrite ships.\n\n## When to Use This Skill\n\nUse **complexity-cuts** when refactoring existing code that has poor Big-O:\n\n- Nested loops, `O(n²)` or worse scans, repeated work, redundant allocations, blown memory.\n- Stated symptoms: \"this is slow on large inputs\", \"times out\", \"OOM\", \"too much memory\", \"reduce complexity\", \"optimize this algorithm\".\n- N+1 query patterns in ORMs (Prisma, Drizzle, SQLAlchemy, Django, ActiveRecord).\n- `await` inside `for` over independent items causing serial latency.\n\nFor *preventing* bad complexity before code is written, use **`lemmaly`**. For math-level optimizations (Bloom, HLL, FFT, JL projection), escalate to **`mathguard`**.\n\n## The Iron Law\n\n```text\nNO TRANSFORMATION WITHOUT EXISTING TESTS GREEN BEFORE AND AFTER\n```\n\nIf the code has no tests, you write a characterization test first (golden input → current output). Then transform. Then verify the test still passes. If you skip this, the optimization can silently break callers — and faster-but-wrong is worse than slow-and-right.\n\n## Non-negotiable rules\n\n1. **State current and target Big-O before touching code.** In one line:\n   - Current: `time = O(?)`, `space = O(?)`\n   - Target: `time = O(?)`, `space = O(?)`\n   - Dominant input dimension (n = what, how large in practice)\n\n   If you cannot state current Big-O, you do not yet understand the code. Read more.\n\n2. **Identify the bottleneck, do not guess.** Point to the exact line(s) responsible for the dominant term. Nested loop? Repeated linear scan? Recomputation? Allocation inside a hot loop? The fix lives there, not elsewhere.\n\n3. **One transformation at a time, with a verify-revert-stop loop.** The loop is:\n\n   1. Apply exactly one transformation from the playbook.\n   2. Run the existing test suite (or the characterization test you wrote per the Iron Law).\n   3. If any test breaks: **revert immediately.** Do not patch the test. Do not patch around the failure. Revert.\n   4. Count reverts on this piece of code. If **3 reverts in a row**, STOP optimizing. The bottleneck is wrong, the transformation is wrong, or the code has invariants you have not modeled. Escalate to `invariant-guard` and write the missing contract — do not try a fourth transformation.\n   5. Only after a transformation lands green: pick the next one.\n\n   Stacked changes hide regressions. Patched tests hide regressions louder.\n\n4. **Preserve semantics exactly.** Lower complexity must not change outputs, ordering guarantees, stability, or error behavior. If the optimization requires a semantic change (e.g. unordered output), call it out explicitly and confirm it is acceptable.\n\n5. **No invented numbers.** Never write \"10x faster\" or \"saves 200MB\" without measuring. Write `\u003Cmeasured: TBD>` and move on, or actually measure with a representative input.\n\n6. **Always report the measured speedup ratio after a transformation lands.** Once the new code is green, run a representative benchmark (same input, same machine, warm cache) and report `before → after` plus the ratio as `N× faster` (or `N× less memory`). One line, attached to the diff:\n\n   ```text\n   p50:  186 ms → 1.1 ms   (169× faster, n=20,000, 200 samples)\n   ```\n\n   If you cannot measure (e.g. the win is purely asymptotic on inputs you don't have), say so explicitly: `asymptotic only, no measurement — O(n²) → O(n)`. Never silently skip this step.\n\n## The transformation playbook\n\nThe vast majority of real-world Big-O wins come from a small set of moves. Try them in this order:\n\n### Time-complexity reductions\n\n| Smell | Fix | Typical win |\n|---|---|---|\n| `for x in A: if x in B` where B is list\u002Farray | Convert B to `Set`\u002F`Map` once | O(n·m) → O(n+m) |\n| Nested loop computing pairs\u002Fjoins | Hash-join on the key; index by lookup field | O(n·m) → O(n+m) |\n| Repeated `.find` \u002F `.indexOf` \u002F `.includes` inside a loop | Precompute index `Map\u003Ckey, item>` outside loop | O(n^2) → O(n) |\n| Repeated recomputation of same value | Memoize \u002F cache by input key | O(n·f(n)) → O(n + f(n)) |\n| Sort inside a loop | Sort once outside | O(n^2 log n) → O(n log n) |\n| Linear scan for min\u002Fmax\u002Fmedian repeatedly | Heap \u002F sorted structure | O(n·k) → O(n log k) |\n| Recursive recomputation (naive Fibonacci shape) | Memoize, or convert to iterative DP | exponential → O(n) |\n| String concatenation in a loop (some langs) | Use builder \u002F `join` \u002F `array.push` then join | O(n^2) → O(n) |\n| Repeated regex compile in loop | Compile once outside | constant-factor, large |\n| Counting \u002F grouping via nested loop | Single pass with `Counter` \u002F `Map\u003Ck, count>` | O(n^2) → O(n) |\n| Sliding-window written as nested loop | Two-pointer \u002F windowed sum | O(n^2) → O(n) |\n| Repeated prefix sums | Precompute prefix array, O(1) range queries | O(n·q) → O(n+q) |\n| Pairwise distance \u002F containment checks on intervals | Sort + sweep line | O(n^2) → O(n log n) |\n| Top-K via full sort | Heap of size K | O(n log n) → O(n log k) |\n| Repeated set membership in loop body | `Set` once, reuse | O(n·m) → O(n) |\n| `await` inside a `for` over independent items | `Promise.all` \u002F batched concurrency | wall-clock O(n·latency) → O(latency) |\n| ORM query inside a loop (N+1) | `IN (...)` \u002F `select_related` \u002F bulk fetch | O(n) round-trips → O(1) |\n\n### Space-complexity reductions\n\n| Smell | Fix | Typical win |\n|---|---|---|\n| Materializing whole list\u002Farray just to iterate | Generator \u002F iterator \u002F stream | O(n) → O(1) |\n| Building intermediate arrays via chained `.map().filter().map()` on huge data | Single-pass loop or lazy pipeline | k·O(n) → O(n) (often O(1) extra) |\n| Caching every intermediate result of a recursion | Rolling window (keep last k states) | O(n) → O(k) |\n| Storing parents\u002Fvisited for graph traversal when only count needed | Bitset \u002F counter only | O(n) → O(1) |\n| Copying input to mutate | In-place mutation when caller allows | O(n) → O(1) |\n| Reading entire file before processing | Stream line-by-line \u002F chunked | O(file) → O(chunk) |\n| Deep-clone for safety in a loop | Clone once, or use structural sharing \u002F immutables | O(n·m) → O(n+m) |\n| Holding references that prevent GC (closures, listeners, caches) | Bound the cache (LRU), remove listeners, scope closures tightly | unbounded → bounded |\n| Loading full result set from DB | Cursor \u002F pagination \u002F streaming query | O(rows) → O(page) |\n| `JSON.parse(JSON.stringify(x))` for cloning | `structuredClone` or targeted copy | O(n) work and allocation removed |\n\n### When you cannot lower asymptotic Big-O\n\nSometimes O(n log n) really is the floor. Then move to constant-factor wins:\n\n- Replace pointer-chasing structures with contiguous arrays (cache locality).\n- Hoist invariants out of loops.\n- Avoid allocation in the hot loop (reuse buffers).\n- Prefer typed arrays \u002F native containers over boxed objects for numeric work.\n- Batch syscalls \u002F I\u002FO.\n\nState explicitly: \"Asymptotic floor is O(n log n); applying constant-factor optimizations only.\"\n\n## Required workflow\n\nFor each piece of code you optimize:\n\n1. **Measure or estimate current Big-O.** Write it down.\n2. **Identify the bottleneck line(s).** Point at them.\n3. **Pick one transformation from the playbook.** Name it.\n4. **Apply it.** One change.\n5. **Verify behavior.** Tests pass, or outputs match on a representative input.\n6. **State new Big-O.** Time and space.\n7. **Repeat if more wins exist and are worth the complexity cost.**\n\n## Canonical example — workflow vs no-workflow\n\nThe same optimization with and without the verify-revert-stop loop.\n\n**Bottleneck.** `getOrdersWithUsers()` runs 10s on 10k orders. Cause: `users.find(u => u.id === o.userId)` inside the map → O(n·m).\n\n### Without the workflow — changes semantics AND patches the test\n\n```ts\n\u002F\u002F No workflow: change semantics + the optimization in one go\nexport function getOrdersWithUsers(orders, users) {\n  const userById = Object.fromEntries(users.map(u => [u.id, u]));\n  return orders\n    .map(o => ({ ...o, user: userById[o.userId] }))\n    .filter(o => o.user); \u002F\u002F silently drops orders whose user was deleted\n}\n```\n\nFaster, *and* changes the result set. Existing tests catch it — but the diff also \"fixes\" a flaky test by removing the assertion that checked the old behavior. Ships green. Breaks the billing report two weeks later.\n\n### With the workflow — one transformation, semantics preserved\n\n```ts\n\u002F\u002F Workflow applied:\n\u002F\u002F   Bottleneck: orders.map → users.find  (line 14)\n\u002F\u002F   Current: time = O(n·m), space = O(1)\n\u002F\u002F   Target:  time = O(n+m), space = O(m)\n\u002F\u002F   Transformation: precompute index Map\u003CuserId, User> outside the loop\n\u002F\u002F   Semantic risk: None — orders with missing users still emit `user: undefined` exactly as before\n\u002F\u002F   Reverts so far: 0\n\nexport function getOrdersWithUsers(orders, users) {\n  const userById = new Map(users.map(u => [u.id, u]));\n  return orders.map(o => ({ ...o, user: userById.get(o.userId) }));\n}\n```\n\nOne transformation. Existing tests stay untouched. Run them. If green, ship. If red, revert (don't patch). After 3 reverts, stop and load `invariant-guard` — the bottleneck is wrong, or the function has a contract no one wrote down.\n\n## Output discipline\n\nWhen proposing or applying an optimization, your message must contain — in this order:\n\n1. **Bottleneck** — file:line and one-sentence reason.\n2. **Current complexity** — `time = O(?)`, `space = O(?)`.\n3. **Transformation** — name from the playbook (or describe it if novel).\n4. **New complexity** — `time = O(?)`, `space = O(?)`.\n5. **Semantic risk** — anything callers might notice (ordering, stability, error timing). \"None\" is a valid answer if true.\n6. **Measured speedup** — `before → after` with the ratio as `N× faster` (or `asymptotic only` if not measured). One line, honest numbers.\n7. **The diff.**\n\nIf any of 1–6 is missing, the optimization is not ready to apply.\n\n## Stop conditions — do not optimize further when\n\n- Asymptotic Big-O already matches a known lower bound for the problem.\n- The input is provably small and bounded (n \u003C ~100 and not on a hot path).\n- The optimization would obscure correctness or harm readability without a measured win.\n- The bottleneck is I\u002FO or external service latency, not CPU\u002Fmemory — go fix that instead.\n\nPremature optimization past these points adds risk without payoff.\n\n## Rationalizations to watch for\n\n| Excuse | Reality |\n| --- | --- |\n| \"I already solved this in my head — just paste the diff and add labels after.\" | Retrofitted labels lie about the reasoning order. Write bottleneck → complexity → transformation → diff in that order, or you are writing fiction. |\n| \"Stating the current Big-O is busywork — everyone can see the nested loop.\" | If everyone can see it, writing one line costs nothing. If only you can see it, you just saved the reviewer's time. |\n| \"Semantic risk is None, skip that step.\" | \"None\" is a valid answer — but write it. The next reader does not know which guarantees you considered. |\n| \"I'll do all three transformations in one diff.\" | Stacked transformations hide regressions. One transformation, verify, repeat. |\n| \"It's just a small refactor, the workflow is overkill.\" | Then it takes 30 seconds. The cases where you skip the workflow are the ones where you miss the optimization next to the obvious one. |\n| \"I'll measure later.\" | Later is `\u003Cmeasured: TBD>` forever. Either measure now or accept the asymptotic argument as the only claim. |\n\n## Red flags — STOP\n\n- Optimizing without stating current Big-O.\n- \"This should be faster\" without identifying a specific bottleneck line.\n- Stacking multiple transformations before verifying any one of them.\n- Claiming a speedup without measuring or without an asymptotic argument.\n- Lowering complexity by silently changing output semantics.\n- Rewriting code that runs once at startup with n = 12.\n\n## Verification checklist\n\nBefore claiming an optimization is complete:\n\n- [ ] Existing tests (or a written characterization test) were green BEFORE the transformation.\n- [ ] Exactly one transformation was applied.\n- [ ] Tests are green AFTER the transformation.\n- [ ] No test was modified, weakened, or skipped to make it pass.\n- [ ] Current Big-O and target Big-O are stated in the diff or PR description.\n- [ ] Semantic risk is written down (\"None\" is valid if true).\n- [ ] Measured speedup ratio is reported as `before → after · N× faster` (or explicitly marked `asymptotic only` if no measurement was possible).\n- [ ] If a measured claim was made (e.g. \"3x faster\"), the measurement command is included.\n- [ ] Revert count on this code is \u003C 3.\n\nCannot check every box? The optimization is not done. Either revert or finish the gap — do not ship a half-verified speedup.\n\n## Limitations\n\n- **Requires existing tests or a written characterization test.** Without one, you cannot detect silent semantic regressions; the Iron Law refuses to skip this.\n- **Asymptotic wins only; constant-factor work is a separate mode** (clearly labeled). The playbook will not improve cache locality or SIMD utilization on its own.\n- **Single-process scope.** Distributed-system bottlenecks (consensus latency, replication lag, queue backpressure) are out of scope.\n- **3-revert rule is firm.** If three transformations failed, the skill explicitly forces escalation to `invariant-guard`; it does not let you try a fourth.\n- **Measurement is on the author.** complexity-cuts requires the ratio to be reported but does not run the benchmark for you — you must produce a representative input.\n- **Won't help I\u002FO-bound code.** If the dominant term is network latency or disk, the playbook will not move the needle — fix the I\u002FO pattern instead.\n\n## The thesis, in one line\n\n> **Existing code earned its slowness one shortcut at a time. complexity-cuts removes them one transformation at a time — and refuses to ship the optimization without a green test.**\n\n## Related Skills\n\n- `lemmaly` — prevention gateway; use when writing new code instead of refactoring existing.\n- `invariant-guard` — escalation target when 3+ transformations have failed tests — the missing piece is a contract, not an optimization.\n- `mathguard` — escalation when the classical floor is reached and an approximate or math-heavy structure could win.\n","# complexity-cuts — Lower Big-O on Existing Code\n\n`lemmaly` prevents bad complexity before code is written. **complexity-cuts** fixes it after the fact: code already exists, it works, but its time or space complexity is worse than necessary.\n\n**Violating the letter of these rules is violating the spirit of the skill.** Adapting \"just a little\" is how a faster-but-wrong rewrite ships.\n\n## When to Use This Skill\n\nUse **complexity-cuts** when refactoring existing code that has poor Big-O:\n\n- Nested loops, `O(n²)` or worse scans, repeated work, redundant allocations, blown memory.\n- Stated symptoms: \"this is slow on large inputs\", \"times out\", \"OOM\", \"too much memory\", \"reduce complexity\", \"optimize this algorithm\".\n- N+1 query patterns in ORMs (Prisma, Drizzle, SQLAlchemy, Django, ActiveRecord).\n- `await` inside `for` over independent items causing serial latency.\n\nFor *preventing* bad complexity before code is written, use **`lemmaly`**. For math-level optimizations (Bloom, HLL, FFT, JL projection), escalate to **`mathguard`**.\n\n## The Iron Law\n\n```text\nNO TRANSFORMATION WITHOUT EXISTING TESTS GREEN BEFORE AND AFTER\n```\n\nIf the code has no tests, you write a characterization test first (golden input → current output). Then transform. Then verify the test still passes. If you skip this, the optimization can silently break callers — and faster-but-wrong is worse than slow-and-right.\n\n## Non-negotiable rules\n\n1. **State current and target Big-O before touching code.** In one line:\n   - Current: `time = O(?)`, `space = O(?)`\n   - Target: `time = O(?)`, `space = O(?)`\n   - Dominant input dimension (n = what, how large in practice)\n\n   If you cannot state current Big-O, you do not yet understand the code. Read more.\n\n2. **Identify the bottleneck, do not guess.** Point to the exact line(s) responsible for the dominant term. Nested loop? Repeated linear scan? Recomputation? Allocation inside a hot loop? The fix lives there, not elsewhere.\n\n3. **One transformation at a time, with a verify-revert-stop loop.** The loop is:\n\n   1. Apply exactly one transformation from the playbook.\n   2. Run the existing test suite (or the characterization test you wrote per the Iron Law).\n   3. If any test breaks: **revert immediately.** Do not patch the test. Do not patch around the failure. Revert.\n   4. Count reverts on this piece of code. If **3 reverts in a row**, STOP optimizing. The bottleneck is wrong, the transformation is wrong, or the code has invariants you have not modeled. Escalate to `invariant-guard` and write the missing contract — do not try a fourth transformation.\n   5. Only after a transformation lands green: pick the next one.\n\n   Stacked changes hide regressions. Patched tests hide regressions louder.\n\n4. **Preserve semantics exactly.** Lower complexity must not change outputs, ordering guarantees, stability, or error behavior. If the optimization requires a semantic change (e.g. unordered output), call it out explicitly and confirm it is acceptable.\n\n5. **No invented numbers.** Never write \"10x faster\" or \"saves 200MB\" without measuring. Write `\u003Cmeasured: TBD>` and move on, or actually measure with a representative input.\n\n6. **Always report the measured speedup ratio after a transformation lands.** Once the new code is green, run a representative benchmark (same input, same machine, warm cache) and report `before → after` plus the ratio as `N× faster` (or `N× less memory`). One line, attached to the diff:\n\n   ```text\n   p50:  186 ms → 1.1 ms   (169× faster, n=20,000, 200 samples)\n   ```\n\n   If you cannot measure (e.g. the win is purely asymptotic on inputs you don't have), say so explicitly: `asymptotic only, no measurement — O(n²) → O(n)`. Never silently skip this step.\n\n## The transformation playbook\n\nThe vast majority of real-world Big-O wins come from a small set of moves. Try them in this order:\n\n### Time-complexity reductions\n\n| Smell | Fix | Typical win |\n|---|---|---|\n| `for x in A: if x in B` where B is list\u002Farray | Convert B to `Set`\u002F`Map` once | O(n·m) → O(n+m) |\n| Nested loop computing pairs\u002Fjoins | Hash-join on the key; index by lookup field | O(n·m) → O(n+m) |\n| Repeated `.find` \u002F `.indexOf` \u002F `.includes` inside a loop | Precompute index `Map\u003Ckey, item>` outside loop | O(n^2) → O(n) |\n| Repeated recomputation of same value | Memoize \u002F cache by input key | O(n·f(n)) → O(n + f(n)) |\n| Sort inside a loop | Sort once outside | O(n^2 log n) → O(n log n) |\n| Linear scan for min\u002Fmax\u002Fmedian repeatedly | Heap \u002F sorted structure | O(n·k) → O(n log k) |\n| Recursive recomputation (naive Fibonacci shape) | Memoize, or convert to iterative DP | exponential → O(n) |\n| String concatenation in a loop (some langs) | Use builder \u002F `join` \u002F `array.push` then join | O(n^2) → O(n) |\n| Repeated regex compile in loop | Compile once outside | constant-factor, large |\n| Counting \u002F grouping via nested loop | Single pass with `Counter` \u002F `Map\u003Ck, count>` | O(n^2) → O(n) |\n| Sliding-window written as nested loop | Two-pointer \u002F windowed sum | O(n^2) → O(n) |\n| Repeated prefix sums | Precompute prefix array, O(1) range queries | O(n·q) → O(n+q) |\n| Pairwise distance \u002F containment checks on intervals | Sort + sweep line | O(n^2) → O(n log n) |\n| Top-K via full sort | Heap of size K | O(n log n) → O(n log k) |\n| Repeated set membership in loop body | `Set` once, reuse | O(n·m) → O(n) |\n| `await` inside a `for` over independent items | `Promise.all` \u002F batched concurrency | wall-clock O(n·latency) → O(latency) |\n| ORM query inside a loop (N+1) | `IN (...)` \u002F `select_related` \u002F bulk fetch | O(n) round-trips → O(1) |\n\n### Space-complexity reductions\n\n| Smell | Fix | Typical win |\n|---|---|---|\n| Materializing whole list\u002Farray just to iterate | Generator \u002F iterator \u002F stream | O(n) → O(1) |\n| Building intermediate arrays via chained `.map().filter().map()` on huge data | Single-pass loop or lazy pipeline | k·O(n) → O(n) (often O(1) extra) |\n| Caching every intermediate result of a recursion | Rolling window (keep last k states) | O(n) → O(k) |\n| Storing parents\u002Fvisited for graph traversal when only count needed | Bitset \u002F counter only | O(n) → O(1) |\n| Copying input to mutate | In-place mutation when caller allows | O(n) → O(1) |\n| Reading entire file before processing | Stream line-by-line \u002F chunked | O(file) → O(chunk) |\n| Deep-clone for safety in a loop | Clone once, or use structural sharing \u002F immutables | O(n·m) → O(n+m) |\n| Holding references that prevent GC (closures, listeners, caches) | Bound the cache (LRU), remove listeners, scope closures tightly | unbounded → bounded |\n| Loading full result set from DB | Cursor \u002F pagination \u002F streaming query | O(rows) → O(page) |\n| `JSON.parse(JSON.stringify(x))` for cloning | `structuredClone` or targeted copy | O(n) work and allocation removed |\n\n### When you cannot lower asymptotic Big-O\n\nSometimes O(n log n) really is the floor. Then move to constant-factor wins:\n\n- Replace pointer-chasing structures with contiguous arrays (cache locality).\n- Hoist invariants out of loops.\n- Avoid allocation in the hot loop (reuse buffers).\n- Prefer typed arrays \u002F native containers over boxed objects for numeric work.\n- Batch syscalls \u002F I\u002FO.\n\nState explicitly: \"Asymptotic floor is O(n log n); applying constant-factor optimizations only.\"\n\n## Required workflow\n\nFor each piece of code you optimize:\n\n1. **Measure or estimate current Big-O.** Write it down.\n2. **Identify the bottleneck line(s).** Point at them.\n3. **Pick one transformation from the playbook.** Name it.\n4. **Apply it.** One change.\n5. **Verify behavior.** Tests pass, or outputs match on a representative input.\n6. **State new Big-O.** Time and space.\n7. **Repeat if more wins exist and are worth the complexity cost.**\n\n## Canonical example — workflow vs no-workflow\n\nThe same optimization with and without the verify-revert-stop loop.\n\n**Bottleneck.** `getOrdersWithUsers()` runs 10s on 10k orders. Cause: `users.find(u => u.id === o.userId)` inside the map → O(n·m).\n\n### Without the workflow — changes semantics AND patches the test\n\n```ts\n\u002F\u002F No workflow: change semantics + the optimization in one go\nexport function getOrdersWithUsers(orders, users) {\n  const userById = Object.fromEntries(users.map(u => [u.id, u]));\n  return orders\n    .map(o => ({ ...o, user: userById[o.userId] }))\n    .filter(o => o.user); \u002F\u002F silently drops orders whose user was deleted\n}\n```\n\nFaster, *and* changes the result set. Existing tests catch it — but the diff also \"fixes\" a flaky test by removing the assertion that checked the old behavior. Ships green. Breaks the billing report two weeks later.\n\n### With the workflow — one transformation, semantics preserved\n\n```ts\n\u002F\u002F Workflow applied:\n\u002F\u002F   Bottleneck: orders.map → users.find  (line 14)\n\u002F\u002F   Current: time = O(n·m), space = O(1)\n\u002F\u002F   Target:  time = O(n+m), space = O(m)\n\u002F\u002F   Transformation: precompute index Map\u003CuserId, User> outside the loop\n\u002F\u002F   Semantic risk: None — orders with missing users still emit `user: undefined` exactly as before\n\u002F\u002F   Reverts so far: 0\n\nexport function getOrdersWithUsers(orders, users) {\n  const userById = new Map(users.map(u => [u.id, u]));\n  return orders.map(o => ({ ...o, user: userById.get(o.userId) }));\n}\n```\n\nOne transformation. Existing tests stay untouched. Run them. If green, ship. If red, revert (don't patch). After 3 reverts, stop and load `invariant-guard` — the bottleneck is wrong, or the function has a contract no one wrote down.\n\n## Output discipline\n\nWhen proposing or applying an optimization, your message must contain — in this order:\n\n1. **Bottleneck** — file:line and one-sentence reason.\n2. **Current complexity** — `time = O(?)`, `space = O(?)`.\n3. **Transformation** — name from the playbook (or describe it if novel).\n4. **New complexity** — `time = O(?)`, `space = O(?)`.\n5. **Semantic risk** — anything callers might notice (ordering, stability, error timing). \"None\" is a valid answer if true.\n6. **Measured speedup** — `before → after` with the ratio as `N× faster` (or `asymptotic only` if not measured). One line, honest numbers.\n7. **The diff.**\n\nIf any of 1–6 is missing, the optimization is not ready to apply.\n\n## Stop conditions — do not optimize further when\n\n- Asymptotic Big-O already matches a known lower bound for the problem.\n- The input is provably small and bounded (n \u003C ~100 and not on a hot path).\n- The optimization would obscure correctness or harm readability without a measured win.\n- The bottleneck is I\u002FO or external service latency, not CPU\u002Fmemory — go fix that instead.\n\nPremature optimization past these points adds risk without payoff.\n\n## Rationalizations to watch for\n\n| Excuse | Reality |\n| --- | --- |\n| \"I already solved this in my head — just paste the diff and add labels after.\" | Retrofitted labels lie about the reasoning order. Write bottleneck → complexity → transformation → diff in that order, or you are writing fiction. |\n| \"Stating the current Big-O is busywork — everyone can see the nested loop.\" | If everyone can see it, writing one line costs nothing. If only you can see it, you just saved the reviewer's time. |\n| \"Semantic risk is None, skip that step.\" | \"None\" is a valid answer — but write it. The next reader does not know which guarantees you considered. |\n| \"I'll do all three transformations in one diff.\" | Stacked transformations hide regressions. One transformation, verify, repeat. |\n| \"It's just a small refactor, the workflow is overkill.\" | Then it takes 30 seconds. The cases where you skip the workflow are the ones where you miss the optimization next to the obvious one. |\n| \"I'll measure later.\" | Later is `\u003Cmeasured: TBD>` forever. Either measure now or accept the asymptotic argument as the only claim. |\n\n## Red flags — STOP\n\n- Optimizing without stating current Big-O.\n- \"This should be faster\" without identifying a specific bottleneck line.\n- Stacking multiple transformations before verifying any one of them.\n- Claiming a speedup without measuring or without an asymptotic argument.\n- Lowering complexity by silently changing output semantics.\n- Rewriting code that runs once at startup with n = 12.\n\n## Verification checklist\n\nBefore claiming an optimization is complete:\n\n- [ ] Existing tests (or a written characterization test) were green BEFORE the transformation.\n- [ ] Exactly one transformation was applied.\n- [ ] Tests are green AFTER the transformation.\n- [ ] No test was modified, weakened, or skipped to make it pass.\n- [ ] Current Big-O and target Big-O are stated in the diff or PR description.\n- [ ] Semantic risk is written down (\"None\" is valid if true).\n- [ ] Measured speedup ratio is reported as `before → after · N× faster` (or explicitly marked `asymptotic only` if no measurement was possible).\n- [ ] If a measured claim was made (e.g. \"3x faster\"), the measurement command is included.\n- [ ] Revert count on this code is \u003C 3.\n\nCannot check every box? The optimization is not done. Either revert or finish the gap — do not ship a half-verified speedup.\n\n## Limitations\n\n- **Requires existing tests or a written characterization test.** Without one, you cannot detect silent semantic regressions; the Iron Law refuses to skip this.\n- **Asymptotic wins only; constant-factor work is a separate mode** (clearly labeled). The playbook will not improve cache locality or SIMD utilization on its own.\n- **Single-process scope.** Distributed-system bottlenecks (consensus latency, replication lag, queue backpressure) are out of scope.\n- **3-revert rule is firm.** If three transformations failed, the skill explicitly forces escalation to `invariant-guard`; it does not let you try a fourth.\n- **Measurement is on the author.** complexity-cuts requires the ratio to be reported but does not run the benchmark for you — you must produce a representative input.\n- **Won't help I\u002FO-bound code.** If the dominant term is network latency or disk, the playbook will not move the needle — fix the I\u002FO pattern instead.\n\n## The thesis, in one line\n\n> **Existing code earned its slowness one shortcut at a time. complexity-cuts removes them one transformation at a time — and refuses to ship the optimization without a green test.**\n\n## Related Skills\n\n- `lemmaly` — prevention gateway; use when writing new code instead of refactoring existing.\n- `invariant-guard` — escalation target when 3+ transformations have failed tests — the missing piece is a contract, not an optimization.\n- `mathguard` — escalation when the classical floor is reached and an approximate or math-heavy structure could win.\n",{"name":5,"risk":24,"tags":25,"tools":32,"author":38,"source":39,"license":15,"date_added":40,"description":7,"source_repo":41,"source_type":39,"license_source":42},"safe",[26,27,28,29,30,31],"algorithms","big-o","refactoring","optimization","performance","n-plus-one",[33,34,35,36,37],"claude-code","antigravity","cursor","gemini-cli","codex-cli","morsechimwai","community","2026-05-26","morsechimwai\u002Flemmaly","https:\u002F\u002Fgithub.com\u002Fmorsechimwai\u002Flemmaly\u002Fblob\u002Fmain\u002FLICENSE","main","c475fc64e94e803b50d14a791dfee8853fbb2c5c","integrations\u002Fantigravity-skills\u002Fplugins\u002Fantigravity-awesome-skills\u002Fskills\u002Fcomplexity-cuts","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory","https:\u002F\u002Fgithub.com\u002FElogic360","2026-11-08 22:21:22",{"source":8,"skillName":5,"commands":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add Elogic360\u002Fsoftware-factory --skill complexity-cuts",{"tool":55,"command":56},"bunx","bunx skills add Elogic360\u002Fsoftware-factory --skill complexity-cuts",{"tool":58,"command":59},"pnpm","pnpm dlx skills add Elogic360\u002Fsoftware-factory --skill complexity-cuts","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fintegrations\u002Fantigravity-skills\u002Fplugins\u002Fantigravity-awesome-skills\u002Fskills\u002Fcomplexity-cuts\u002FSKILL.md",true,[],[64,71,78,85,92,99],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M79G206MT3J6S0GY3C45P2KV","vss-summarize-video","Use to summarize a recorded video via the LVS summarization microservice (HITL-gated) with a VLM fallback. Not for report generation or live RTSP captioning.","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-summarize-video\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":19},"01M79G1WN63PGRE8CKD47WEBQ5","vss-setup-video-analytics-api","Use to deploy the vss-video-analytics-api REST service standalone (config-source, data-log bind, Elasticsearch, optional Kafka). Not for full warehouse deploy.","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-setup-video-analytics-api\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":19},"01M79G1S9F7VY3EF6H53PRP5AN","vss-setup-behavior-analytics","Use to deploy the vss-behavior-analytics service standalone (entrypoint, config-source, optional calibration). Not for the full warehouse deploy.","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-setup-behavior-analytics\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":19},"01M79G1N1S1Y27PFZPYMNK1MTQ","vss-search-archive","Use this skill to run top-level VSS fusion search on archived video, or to ingest video files \u002F RTSP streams for search. Do NOT use for ad-hoc visual Q&A (use vss-ask-video), live captioning (use vss-deploy-dense-captioning), or video summarization and reports (use vss-summarize-video).","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-search-archive\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M79G1H6WN0Q6C0VCAXCZX6B7","vss-query-analytics","Use this skill when reading video-analytics metrics, incidents, alerts, and sensor data via the VA-MCP server (port 9901). Not for live VLM or incident-range narrative reports.","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-query-analytics\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":19},"01M79G1DYPNXQS7QHZ0AAF5FX5","vss-manage-video-io-storage","Use to call the VIOS REST API (sensor list, timelines, clip extraction, snapshots, add\u002Fdelete sensors and streams). Not for VLM inference or search.","https:\u002F\u002Fgithub.com\u002FElogic360\u002Fsoftware-factory\u002Fblob\u002Fmain\u002Fskills\u002Fnvidia\u002Fvss-manage-video-io-storage\u002FSKILL.md",[],[]]