levi-gear 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +13 -8
  2. package/agents/_team-protocol.md +15 -6
  3. package/agents/designer.md +2 -2
  4. package/agents/developer.md +1 -1
  5. package/agents/pm.md +4 -1
  6. package/agents/qa.md +1 -1
  7. package/agents/teamlead.md +1 -1
  8. package/package.json +4 -1
  9. package/src/commands/list.js +2 -1
  10. package/src/lib/agents.js +9 -2
  11. package/src/lib/desired-state.js +38 -11
  12. package/src/lib/role-skills.js +23 -0
  13. package/src/lib/tools.js +6 -1
  14. package/src/lib/usecases.js +44 -2
  15. package/src/runtime/codex-run-state.mjs +156 -0
  16. package/src/runtime/quota-check.mjs +195 -0
  17. package/usecases/_run-rules.md +38 -0
  18. package/usecases/brainstorming/SKILL.md +60 -14
  19. package/usecases/brainstorming/references/codex-runner.md +28 -0
  20. package/usecases/code-review/SKILL.md +86 -0
  21. package/usecases/code-review/references/codex-runner.md +5 -0
  22. package/usecases/code-review/references/large-changes.md +37 -0
  23. package/usecases/code-review/references/performance-and-correctness.md +101 -0
  24. package/usecases/code-review/references/review-guide.md +72 -0
  25. package/usecases/code-review/references/security.md +119 -0
  26. package/usecases/create-feature/SKILL.md +97 -0
  27. package/usecases/create-feature/references/codex-runner.md +57 -0
  28. package/usecases/create-feature/scripts/lock-tests.mjs +66 -0
  29. package/usecases/create-feature/workflow.js +532 -0
  30. package/usecases/design/SKILL.md +66 -0
  31. package/usecases/design/references/codex-runner.md +27 -0
  32. package/usecases/design/references/svg-guide.md +14 -0
  33. package/usecases/design/scripts/check-svg.py +77 -0
  34. package/usecases/fix-bug/SKILL.md +97 -0
  35. package/usecases/fix-bug/references/codex-runner.md +32 -0
  36. package/usecases/fix-bug/workflow.js +392 -0
  37. package/usecases/generate-test-scenarios/SKILL.md +102 -0
  38. package/usecases/generate-test-scenarios/references/codex-runner.md +32 -0
  39. package/usecases/generate-test-scenarios/references/test-case-guide.md +171 -0
  40. package/usecases/generate-test-scenarios/scripts/render-test-cases-markdown.mjs +76 -0
  41. package/usecases/generate-test-scenarios/scripts/render-test-cases.mjs +68 -0
  42. package/usecases/generate-test-scenarios/scripts/test-case-fields.mjs +63 -0
  43. package/usecases/generate-test-scenarios/scripts/validate-test-cases.mjs +69 -0
  44. package/usecases/generate-test-scenarios/scripts/write-xlsx.mjs +157 -0
  45. package/usecases/spec-writing/SKILL.md +63 -0
  46. package/usecases/spec-writing/references/codex-runner.md +25 -0
  47. package/usecases/spec-writing/references/spec-guide.md +62 -0
@@ -0,0 +1,101 @@
1
+ # Performance and correctness checklist
2
+
3
+ Every item says what to look for and the usual fix. Each heading is the category used in finding titles. Apply the fix in the project's own framework, and judge cost at the data sizes production will reach, not the test data.
4
+
5
+ ## N+1 query
6
+
7
+ Look for:
8
+ - A query, an API call or a lazy-loaded relation inside a loop, a `map`, a serializer or a template that runs once per row (`orders.forEach(o => o.customer)`, a GraphQL resolver per field).
9
+ - A count or existence check per item in a list.
10
+
11
+ Fix: load in one query with the ORM's eager loading (`include`, `joinedload`, `includes`, `with`, `preload`), a join, or one `WHERE id IN (...)` and a map in memory. Use a batch loader (DataLoader) for GraphQL resolvers.
12
+
13
+ ## Missing index
14
+
15
+ Look for:
16
+ - A new query, filter, sort or join on columns with no index, on a table that grows: `WHERE`, `ORDER BY`, `JOIN ON`, foreign keys, unique lookups such as email or slug.
17
+ - A composite filter whose index has the columns in the wrong order, or a `LIKE '%term'` or a function on the column that cannot use the index.
18
+ - A migration that adds an index or a column with a default on a large table in a way that locks it.
19
+
20
+ Fix: add the index in a migration (composite in the order of equality filters first, then range or sort). Use a full-text or trigram index for substring search. Build indexes without locking where the database supports it (`CREATE INDEX CONCURRENTLY` in PostgreSQL). Check the plan with `EXPLAIN`.
21
+
22
+ ## Unbounded work
23
+
24
+ Look for:
25
+ - Queries or endpoints with no `LIMIT` or pagination, `SELECT *` on wide tables, a whole table or file loaded into memory.
26
+ - Work that grows with input and has no cap: exports, bulk operations, regular expressions open to catastrophic backtracking, recursion with no depth limit.
27
+ - Slow work done in the request path (sending email, image processing, calls to slow services) that could run in the background.
28
+
29
+ Fix: paginate (cursor-based for large or changing sets), select only the needed columns, stream or process in batches, cap sizes, and move slow work to a queue.
30
+
31
+ ## Inefficient algorithm
32
+
33
+ Look for:
34
+ - Nested loops over the same or related collections (O(n²)), `includes` or `indexOf` inside a loop, repeated sorting, string building by concatenation in a loop.
35
+ - The same expensive value computed again and again (in a loop, on every render, on every request) when it could be computed once.
36
+
37
+ Fix: use a map or set for lookups, sort once, hoist invariant work out of the loop, memoize or cache with a clear invalidation rule. Only flag it when the input can realistically be large; otherwise it is at most a suggestion.
38
+
39
+ ## Race condition
40
+
41
+ Look for:
42
+ - Check then act on shared state without a lock or a constraint: "if the username is free, insert", "if the balance is enough, debit", "if the stock is above zero, decrement".
43
+ - Read, modify, write of a counter or document without an atomic update or a version check.
44
+ - Shared mutable state in a process that serves concurrent requests: module-level variables, singletons, caches without locking.
45
+ - Async code where a promise is not awaited, callbacks run in an order that is assumed, or two requests can interleave between steps.
46
+ - Jobs or webhooks that can run twice or at the same time with no idempotency.
47
+
48
+ Fix: let the database enforce it (unique constraint, `UPDATE ... SET qty = qty - 1 WHERE qty > 0`, `SELECT ... FOR UPDATE` in a transaction), use optimistic locking with a version column, use atomic operations of the store, and make jobs idempotent. Await every promise, or handle it explicitly.
49
+
50
+ ## Transactions and consistency
51
+
52
+ Look for:
53
+ - Several writes that must succeed or fail together without a transaction.
54
+ - External calls (payment, email, another service) inside a database transaction, or a write to two systems with no plan for one of them failing.
55
+ - An isolation level too weak for the invariant the code relies on.
56
+
57
+ Fix: wrap related writes in one transaction, keep external calls out of it, and use an outbox or a compensating step for writes across systems.
58
+
59
+ ## Memory and resource leak
60
+
61
+ Look for:
62
+ - Event listeners, subscriptions, intervals, timers or observers added and never removed (for example in a component without cleanup, or on every request).
63
+ - Caches, maps or arrays at module level that only grow.
64
+ - Connections, file handles, streams, cursors or transactions not closed on every path, including errors.
65
+ - Large objects kept alive by closures, or held after they are needed.
66
+
67
+ Fix: remove listeners and clear timers in the matching teardown (`useEffect` cleanup, `ngOnDestroy`, `finally`). Bound caches by size and age (LRU, TTL). Use `try/finally`, `with`, `using` or `defer` to release resources. Use the connection pool and never open a connection per call.
68
+
69
+ ## Error handling
70
+
71
+ Look for:
72
+ - Errors swallowed: an empty `catch`, a `catch` that logs and goes on as if it worked, a returned error value that is never checked.
73
+ - Async errors that are lost: no `await`, no `.catch`, unhandled rejections in background tasks.
74
+ - Every error mapped to 500, or details of internal errors and stack traces returned to the client.
75
+ - Calls to the network or other services with no timeout, or retries with no backoff and no limit, or retries of actions that are not idempotent.
76
+ - Partial failure leaving data half written.
77
+
78
+ Fix: handle the errors you can recover from, let the others propagate to one handler that logs them and returns a safe message with the right status (400 for bad input, 404, 409 for conflicts). Set timeouts on every external call, retry only idempotent operations with backoff and a cap, and roll back or compensate on partial failure.
79
+
80
+ ## Logic and edge cases
81
+
82
+ Look for:
83
+ - Null or missing values not handled, off-by-one in ranges and pagination, empty lists, first and last items.
84
+ - Money in floating point, rounding done in the wrong place, mixed currencies.
85
+ - Time zones and dates: local time stored where UTC is expected, daylight saving, end of month, dates compared as strings.
86
+ - Comparison and type mistakes: `==` coercion, string and number mixed, integer overflow, case and Unicode in comparisons.
87
+ - Behavior that does not match the spec or acceptance criteria the prompt gives.
88
+
89
+ Fix: handle the case explicitly, and name the input that triggers it. Use integer minor units or a decimal type for money, and store times in UTC.
90
+
91
+ ## Breaking API change
92
+
93
+ Look for:
94
+ - In any public contract (HTTP or GraphQL API, event or message schema, exported function or type of a library, CLI flags, configuration keys, database schema read by others):
95
+ - a removed or renamed field, endpoint, parameter, export or option;
96
+ - a changed type, format, unit, default, status code or error shape;
97
+ - a new required input, or a stricter validation of existing input;
98
+ - a change in meaning with the same shape (sort order, inclusive or exclusive range, null now means something else).
99
+ - Database migrations that drop or rename a column still read by code that is deployed, or that cannot be rolled back.
100
+
101
+ Fix: keep the change additive (new optional fields, new endpoints) and keep the old shape working. When a break is needed, version it (`/v2`, a new event type, a major version), mark the old one deprecated with a removal date, and note it in the changelog. For schema changes, expand then contract: add the new column, write to both, backfill, switch reads, and remove the old column in a later release.
@@ -0,0 +1,72 @@
1
+ # Review guide
2
+
3
+ How `levi-teamlead` reviews code, in this usecase and in every usecase that points here. The prompt that brings you here names the target, the context to judge it against, and where the findings go. When the prompt and this guide disagree on where findings go, what blocks, or what may not be changed, the prompt wins.
4
+
5
+ Read the two checklists in this folder before you start:
6
+
7
+ - [security.md](security.md): security, by OWASP Top 10 category.
8
+ - [performance-and-correctness.md](performance-and-correctness.md): performance and correctness.
9
+
10
+ ## How to review
11
+
12
+ 1. **Know the intent.** Read what the change is for: the spec, plan or designs the prompt gives, the pull request title and body, the commit messages. Judge the code against that intent, not against what you would have written.
13
+ 2. **Read the whole change.** Every changed file, in full where the diff alone does not show enough. Skip generated files, lock files, vendored code and build output, but check that dependency changes in manifests are deliberate (see the supply chain items in the security checklist).
14
+ 3. **Read around it.** For each changed function, look at its callers and what it calls; for each query, the schema and indexes; for each endpoint, the route, the middleware and the authorization it goes through; for configuration, every environment it reaches. A change is correct only in its context.
15
+ 4. **Follow the data.** Trace every input that crosses a trust boundary (request, file, message, header, environment, third-party response) to where it is used: a query, a shell command, a template, a file path, a URL, a deserializer, a log. Most security findings sit on that path.
16
+ 5. **Walk both checklists.** Go through every item that applies to the code. Skip the ones that cannot apply (no XML parsing means no XXE), and do not report items as passed one by one.
17
+ 6. **Try to break it.** For each finding, write the concrete case that fails: the input, the timing, the data size or the caller that triggers it. If you cannot make one, it is not a finding.
18
+ 7. **Report it all in one pass.** The author fixes everything you list, then resubmits. A finding you hold back, or a lower-severity one you skip, costs another round. List every finding you can make a case for, of every severity, before you return.
19
+ 8. **Write the fix.** Give the change to make, where, in the project's language, framework and conventions. Prefer the framework's built-in protection (parameterized queries, the ORM's eager loading, the template engine's escaping, the framework's CSRF and auth middleware) over hand-written code.
20
+
21
+ ## Scope
22
+
23
+ - Review the change and what it directly affects, such as a caller it breaks or a query it slows. When the target is files or folders rather than a change, review all of them.
24
+ - A problem that was already there in code the change did not touch is out of scope, unless the change makes it worse or it is a critical security hole. Then report it and mark it **pre-existing**.
25
+ - Leave formatting and naming to the linter, unless they break a convention the project documents.
26
+ - Do not report a problem twice. When one cause shows in several places, report it once and list every location.
27
+ - A change of more than 100 reviewable files is not read by one reviewer: [large-changes.md](large-changes.md) says how it is split and merged. When you review a slice, these rules apply to your slice's files, and the lead's merge produces the one verdict.
28
+
29
+ ## Severities
30
+
31
+ | Severity | Meaning | Blocks merge |
32
+ |---|---|---|
33
+ | **critical** | Exploitable vulnerability, leaked secret, data loss or corruption, a crash on a main path, or a breaking change to a public contract with no migration | Yes |
34
+ | **warning** | A real defect under realistic conditions: an N+1 on a list, a missing index on a growing table, a race on shared state, an unhandled error path, a leak in a long-running process, a missing authorization check behind other protection | Yes |
35
+ | **suggestion** | Worth doing, not wrong today: hardening, a cheaper algorithm for inputs that stay small, clearer error messages | No |
36
+
37
+ Grade on impact and likelihood together. Judge likelihood by the realistic production load and the inputs real users and attackers send, not by the test data. Do not inflate a grade to be heard or lower one to be kind: a critical finding stays critical even when the author is senior or the deadline is close.
38
+
39
+ ## Finding format
40
+
41
+ Each finding:
42
+
43
+ ````markdown
44
+ ### [critical] A03 Injection: SQL built from the search term
45
+ - **Where:** `src/orders/repository.js:42` (also `src/orders/export.js:17`)
46
+ - **Problem:** `search` from the query string is concatenated into the SQL text.
47
+ - **How it fails:** `?search=' OR 1=1 --` returns every customer's orders.
48
+ - **Fix:** Pass it as a bound parameter:
49
+ ```js
50
+ db.query('SELECT * FROM orders WHERE customer_id = $1 AND note ILIKE $2', [userId, `%${search}%`])
51
+ ```
52
+ - **Assumption:** (only when the finding depends on something you could not see; say what to check)
53
+ ````
54
+
55
+ - The title starts with the severity and a category: the OWASP category for security (for example `A01 Broken Access Control`), otherwise the checklist heading (for example `N+1 query`, `Race condition`, `Breaking API change`).
56
+ - **Where** gives a path and line for every location.
57
+ - **How it fails** is the concrete case from step 6 of [How to review](#how-to-review).
58
+ - **Fix** is specific enough to apply without guessing: code for small fixes; for larger ones, the steps and the pattern, with a short sketch.
59
+
60
+ ## Verdict
61
+
62
+ - **Request changes** when any critical or warning finding is left.
63
+ - **Approve** otherwise. Approving with suggestions is fine.
64
+
65
+ ## The reply
66
+
67
+ Unless the prompt says otherwise, reply with:
68
+
69
+ 1. **Verdict** and a one-line summary: what the change does and its main risk.
70
+ 2. **Findings**, critical first, then warning, then suggestion, in the format above. Write "No findings." when there are none.
71
+ 3. **Not checked:** what you could not verify and why (for example a file too large to read, configuration that is not in the repository, a service you could not reach).
72
+ 4. Your report block from the team protocol, with any questions for the user under "Questions".
@@ -0,0 +1,119 @@
1
+ # Security checklist
2
+
3
+ Grouped by the OWASP Top 10 (2021 edition), whose IDs are used in finding titles. Older names fold in as follows: sensitive data exposure is A02, XSS is A03, XXE is A05, insecure deserialization is A08. Newer editions also list software supply chain failures and the mishandling of exceptional conditions; the first is covered under A06, the second in the last section, whose findings use the category `Exceptional conditions`.
4
+
5
+ Every item says what to look for and the usual fix. Apply the fix in the project's own framework.
6
+
7
+ ## A01 Broken Access Control
8
+
9
+ Look for:
10
+ - An endpoint, resolver, job or message handler that reads or changes data with no authorization check, or one that checks only that the user is logged in.
11
+ - Objects loaded by an ID from the request without checking that the current user owns them or may see them (IDOR): `GET /orders/:id`, `DELETE /files/:id`.
12
+ - Authorization done only in the UI (hidden buttons, disabled fields) and not on the server.
13
+ - Role or tenant taken from the request body, a query string or an unsigned cookie instead of the server-side session or a verified token.
14
+ - Mass assignment: the whole request body bound to a model, so a client can set `role`, `isAdmin`, `ownerId`, `price`.
15
+ - Queries in a multi-tenant system without a tenant filter.
16
+ - File paths built from input (`../` path traversal); CORS that reflects any origin with credentials.
17
+ - A missing CSRF check on cookie-authenticated state-changing requests.
18
+
19
+ Fix: check authorization on the server for every action, deny by default, in one place (policy, middleware, guard). Scope queries by the owner or tenant (`WHERE id = $1 AND owner_id = $2`). Allow-list the fields a client may set. Resolve paths and check they stay under the intended root. Use the framework's CSRF protection and an explicit CORS allow-list.
20
+
21
+ ## A02 Cryptographic Failures (sensitive data exposure)
22
+
23
+ Look for:
24
+ - Passwords stored in plain text or hashed with a fast hash (MD5, SHA-1, SHA-256 with no work factor).
25
+ - Secrets in the code, in committed config, in logs, in error messages, in URLs or in client bundles.
26
+ - Sensitive fields (password hash, tokens, national ID, card data, internal notes) returned in API responses or serialized whole from the model.
27
+ - Personal or secret data sent over plain HTTP, or stored without encryption where the project requires it.
28
+ - Weak or home-made crypto: ECB mode, a fixed IV, `Math.random()` or a similar non-cryptographic generator for tokens, reset codes or IDs that must not be guessed.
29
+ - TLS verification turned off (`rejectUnauthorized: false`, `verify=False`).
30
+
31
+ Fix: hash passwords with bcrypt, scrypt or Argon2. Load secrets from the environment or a secret manager, and rotate any that leaked. Return explicit DTOs or serializers with an allow-list of fields. Use the platform's CSPRNG and vetted libraries with authenticated encryption (AES-GCM). Keep TLS verification on.
32
+
33
+ ## A03 Injection (including XSS)
34
+
35
+ Look for:
36
+ - SQL, NoSQL, LDAP or ORM raw queries built by concatenation or string formatting with input. Includes `ORDER BY`, column names and `LIKE` patterns.
37
+ - NoSQL operator injection: a JSON body passed straight into a filter (`{"$gt": ""}`).
38
+ - Shell commands built from input (`exec`, `system`, `subprocess` with `shell=True`, backticks).
39
+ - Template injection: user input used as a template rather than as data.
40
+ - XSS: input rendered without escaping (`innerHTML`, `dangerouslySetInnerHTML`, `v-html`, `|safe`, `{!! !!}`, `html_safe`), input in `href` or `src` (`javascript:` URLs), or in inline scripts and event handlers.
41
+ - Header and log injection: CR/LF from input written into headers or log lines.
42
+
43
+ Fix: bound parameters or the query builder for values, and an allow-list for identifiers such as sort columns. Validate the type and shape of input at the boundary (schema validation). Call processes with an argument array and no shell. Let the template engine escape by default. Sanitize HTML that must be rendered with a vetted sanitizer (for example DOMPurify), and add a Content Security Policy.
44
+
45
+ ## A04 Insecure Design
46
+
47
+ Look for:
48
+ - No rate limit or lockout on login, reset, OTP, signup, search or other costly endpoints.
49
+ - Business rules that a client can bypass: a price, discount, quantity or state sent from the client and trusted; steps of a flow that can be skipped or replayed.
50
+ - Payments, transfers or other one-time actions with no idempotency key.
51
+ - No upper bound on input size, page size, upload size or the number of items in a request.
52
+
53
+ Fix: rate limit and lock out on the server. Recompute prices and permissions on the server and check state transitions there. Use idempotency keys for one-time actions. Set limits on every size and count.
54
+
55
+ ## A05 Security Misconfiguration (including XXE)
56
+
57
+ Look for:
58
+ - Debug mode, stack traces or verbose errors enabled in production configuration.
59
+ - Default credentials, sample accounts, open admin panels, permissive CORS, missing security headers.
60
+ - Public storage buckets, or files and directories served that should not be (`.env`, `.git`, backups).
61
+ - XML parsers with external entities or DTDs enabled (XXE): `DocumentBuilderFactory`, `XMLReader`, `lxml`, `libxml` defaults, SOAP and SVG uploads.
62
+ - Cookies without `HttpOnly`, `Secure` and a suitable `SameSite`.
63
+
64
+ Fix: separate production configuration with debug off and generic error responses. Add security headers (HSTS, CSP, `X-Content-Type-Options`). Disable DTDs and external entities in every XML parser (or use a safe wrapper such as `defusedxml`). Set the cookie flags.
65
+
66
+ ## A06 Vulnerable and Outdated Components (supply chain)
67
+
68
+ Look for:
69
+ - New or upgraded dependencies: are they needed, maintained, and spelled right (typosquatting)? Do they pull install scripts?
70
+ - Versions with known vulnerabilities, unpinned versions, or a lock file not updated with the manifest.
71
+ - Code, scripts or images fetched from unverified sources at build or run time (`curl | sh`, `latest` tags).
72
+ - CI changes that expose secrets to untrusted pull requests.
73
+
74
+ Fix: pin versions and commit the lock file. Run the ecosystem's audit (`npm audit`, `pip-audit`, `bundle audit`, `govulncheck`) and upgrade or replace what it flags. Verify checksums and pin images by digest. Keep secrets out of jobs triggered by forks.
75
+
76
+ ## A07 Identification and Authentication Failures (broken auth)
77
+
78
+ Look for:
79
+ - Login, reset or token checks that leak whether an account exists, or compare secrets with `==` instead of a constant-time compare.
80
+ - JWTs accepted with `alg: none`, without checking the signature, expiry, issuer or audience, or signed with a weak or committed secret.
81
+ - Sessions not rotated on login or privilege change, not invalidated on logout or password change, or with no expiry.
82
+ - Reset and verification tokens that are guessable, reusable or never expire.
83
+ - Tokens stored in `localStorage` where an HttpOnly cookie is possible.
84
+
85
+ Fix: use the framework's or a vetted library's authentication. Verify every JWT claim with a pinned algorithm. Rotate session IDs on login. Make reset tokens random, single use and short lived. Return the same response whether or not the account exists.
86
+
87
+ ## A08 Software and Data Integrity Failures (insecure deserialization)
88
+
89
+ Look for:
90
+ - Untrusted data passed to a deserializer that can build arbitrary objects: Java `ObjectInputStream`, Python `pickle` or `yaml.load`, PHP `unserialize`, .NET `BinaryFormatter`, Ruby `Marshal`, Node `node-serialize`.
91
+ - Webhooks, callbacks or messages accepted without verifying their signature.
92
+ - Updates, plugins or data pulled without an integrity check.
93
+
94
+ Fix: accept plain data formats (JSON) validated against a schema; use safe loaders (`yaml.safe_load`). Verify HMAC signatures on webhooks with a constant-time compare. Check signatures or checksums of what is downloaded.
95
+
96
+ ## A09 Security Logging and Monitoring Failures
97
+
98
+ Look for:
99
+ - Security events with no log: failed logins, access denied, password and role changes, admin actions.
100
+ - Logs holding passwords, tokens, full card numbers or personal data.
101
+ - Errors swallowed so that an attack leaves no trace.
102
+
103
+ Fix: log security events with the user, action, target and outcome, and no secrets. Mask sensitive fields in the logger.
104
+
105
+ ## A10 Server-Side Request Forgery (SSRF)
106
+
107
+ Look for:
108
+ - The server fetching a URL or host taken from input: webhooks, link previews, image fetchers, imports, PDF renderers.
109
+ - No block on internal addresses (`localhost`, `169.254.169.254`, private ranges), redirects followed blindly, or DNS checked once and then re-resolved.
110
+
111
+ Fix: allow-list the hosts and schemes. Resolve the address, reject private and link-local ranges, and connect to the address you checked. Do not follow redirects, or re-check each one. Run fetchers with no access to internal networks.
112
+
113
+ ## Exceptional conditions (failing open)
114
+
115
+ Look for:
116
+ - Code that fails open: an authorization, validation or payment check that is skipped or succeeds when it throws, times out or gets an unexpected value.
117
+ - A `catch` that falls through to the success path.
118
+
119
+ Fix: fail closed. On any error in a security check, deny and log.
@@ -0,0 +1,97 @@
1
+ ---
2
+ name: levi-create-feature
3
+ description: Build a new feature end to end, spec first and test first. Finds or writes the spec (confirmed with the user), the brainstorming plan and, for UI work, the designs; then the developer writes unit and feature tests and QA writes test cases (Markdown and Excel), both from the spec and reviewed against it; the tests are locked, only QA may change its test cases, and the developer writes the code until every test passes, the teamlead approves the code review, and then QA passes every scenario end to end in a headless browser. Tests and test cases are never changed to make them pass. On Claude Code the implementation runs as a Workflow of independent subagents. Fits requests such as "build feature X", "implement X", "add X to the app", "triển khai tính năng X", "thêm tính năng X".
4
+ argument-hint: "<the feature to build, and the spec if you have one>"
5
+ requires: spec-writing, brainstorming, design, code-review, generate-test-scenarios
6
+ ---
7
+
8
+ # Create a feature
9
+
10
+ Build a feature the spec-driven way: **the spec decides, the tests and scenarios are written from it, and the code is changed until it satisfies them.** You run the team; you never write the spec, the tests, the scenarios or the code yourself.
11
+
12
+ The work has two halves:
13
+
14
+ - **Prepare** (steps 1 to 5), here in the conversation, because it needs the user: the spec, the brainstorming plan and the designs. It reuses the `spec-writing`, `brainstorming` and `design` usecases.
15
+ - **Implement** (step 6), without the user: tests, scenarios, code, end-to-end runs and code review. Every agent call is a fresh, independent subagent that sees only the files it is given, never the conversation or another agent's reasoning. Claude Code runs `workflow.js`; Codex uses the durable runner in [`references/codex-runner.md`](references/codex-runner.md).
16
+
17
+ ## The rules that never bend
18
+
19
+ - **The spec is the top priority.** Tests and scenarios follow it exactly, and the code follows them. Nobody but `levi-pm` touches the spec, and only through the `spec-writing` flow.
20
+ - **Tests and test cases are checked against the spec, then kept.** They are the definition of done: no agent may edit, delete, skip or weaken the tests, or change test configuration to leave them out. When one fails, the code is wrong and the code is fixed. The tests are locked by `scripts/lock-tests.mjs`: every locked file is hashed, checked after every round and restored when changed. The test cases belong to QA: QA writes, changes and runs them with the test case guide of `generate-test-scenarios`, and a change by anyone else is undone with the same script before QA runs them. QA never changes an expected result to match what the code does.
21
+ - **Writers work apart.** The developer writes tests and QA writes scenarios from the spec, each without reading the other's work. QA never reads the application code.
22
+ - **Nothing is committed.** The changes stay in the working tree for the user to review.
23
+
24
+ ## Files
25
+
26
+ | File | Owner | Purpose |
27
+ |---|---|---|
28
+ | `docs/specs/<spec>.md` | PM | The spec. Read-only here, except through the `spec-writing` flow |
29
+ | `docs/brainstorming/<plan>.md` | PM | The brainstorming plan |
30
+ | `docs/designs/<design>/` | Designer | The designs, for UI work |
31
+ | Unit and feature tests, in the framework's folders | Developer | **Deliverable.** Locked once reviewed |
32
+ | `docs/tests/<base>.md`, `docs/tests/<base>.xlsx` | QA | **Deliverable.** The test cases with their PASS or FAIL result, in the format of `generate-test-scenarios`. Only QA changes them |
33
+ | Application code, migrations | Developer, Teamlead | **Deliverable.** The feature |
34
+ | `docs/levi/<slug>/tasks.md` | Teamlead | Scratch: execution plan and the interfaces tests and code share. Deleted at the end |
35
+ | `docs/levi/<slug>/review.md` | Teamlead | Scratch: code review findings. Deleted at the end |
36
+ | `docs/levi/<slug>/locked/`, `qa-snapshot/` | Workflow | Scratch: copies and hashes of the locked tests, and of the test cases as QA last wrote them. Deleted at the end |
37
+ | `docs/levi/<slug>/test-cases.json` | QA | Scratch: the data the test cases are rendered from. Deleted at the end |
38
+
39
+ `<slug>` is a short kebab-case name for the feature, in English (for example `export-orders-csv`). The other usecases are installed next to this one: their `SKILL.md` files are in the sibling folders `levi-spec-writing/`, `levi-brainstorming/`, `levi-design/`, `levi-code-review/` and `levi-generate-test-scenarios/`. When this file says "run the X flow", read that `SKILL.md` and follow its steps with the given subject, then come back here.
40
+
41
+ ## Steps
42
+
43
+ 1. **Intake.** The request is the feature. If it is empty, ask what to build and stop. Derive the slug. Note any spec the user attached or pointed to (a path, a link, "the spec in ...").
44
+
45
+ **Opening round.** Before any flow starts, list the candidates for the spec (`docs/specs/`), the plan (`docs/brainstorming/`) and, when the feature has a user interface, the designs (`docs/designs/`), and ask every confirmation below in one round together with anything else unclear in the request, as the run rules say. Steps 2 to 4 then use these answers instead of asking one at a time. The flows they run ask only what they cannot know before they start (the PM's open questions about the spec); after this and those rounds the run goes on alone.
46
+ 2. **Spec.**
47
+ - *The user gave one:* use it.
48
+ - *Otherwise:* list `docs/specs/` and match files against the feature by name, title and goal. When one or more look like the spec for this feature, ask the user to confirm (in the opening round), in one question: each candidate (path and title) as an option, the most likely first, plus "None of these: write a new spec". Never use a candidate the user did not confirm.
49
+ - *Confirmed:* use it. *Rejected, or no candidate:* run the `spec-writing` flow with the feature as subject, to write a new spec in `docs/specs/`, then use that.
50
+ - **The spec must be Ready.** If its Status is Draft, its open questions would have to be guessed, so do not implement yet. Ask the user to settle them, and run the `spec-writing` flow in update mode with the answers. If the user prefers to leave a point out, that is an answer too: the PM moves it to Out of scope. Continue only when the Status is Ready.
51
+ 3. **Brainstorming plan.** List `docs/brainstorming/` and match plans against the feature and the spec. One clear match: use it, and say which in one line. Two or more equally plausible: ask the user which one (or "none") in the opening round. None: run the `brainstorming` flow, with the feature and the spec, and use the plan it writes.
52
+ 4. **Designs.** Decide from the spec whether the feature has a user interface (screens, pages, forms, components, visible states). If it has none, skip this step. If it has, list `docs/designs/` and match folders against the feature: one clear match is used; two or more plausible ones, ask the user in the opening round; none: run the `design` flow with the feature as subject and the spec as context, and use the folder it writes.
53
+ 5. **Get ready.** Delete `docs/levi/<slug>/locked/` and `qa-snapshot/` if an earlier run left them. Work out the feature ID and the output base `<base>` of the test cases from the spec, as the "Features, IDs and file names" table of `levi-generate-test-scenarios/SKILL.md` says. Say in a few lines what will be used (spec, plan, designs) and that implementation starts now.
54
+ 6. **Implement.**
55
+ - *With a Workflow tool (Claude Code):* call it with `scriptPath` set to `workflow.js` in this skill's folder, and `args`:
56
+
57
+ ```json
58
+ {
59
+ "slug": "<slug>",
60
+ "feature": "<the request, as the user wrote it>",
61
+ "spec": "docs/specs/<spec>.md",
62
+ "plan": "docs/brainstorming/<plan>.md",
63
+ "designs": "docs/designs/<design>/ (omit when there is no UI)",
64
+ "featureId": "<the feature ID>",
65
+ "testBase": "docs/tests/<base>",
66
+ "skillDir": "<this skill's folder, relative to the project root>"
67
+ }
68
+ ```
69
+
70
+ The script runs the steps under [Implementation](#implementation) below and returns a result with a `status`. Follow its progress with the user only when they ask.
71
+ - *On Codex:* follow [`references/codex-runner.md`](references/codex-runner.md). It persists the stage in `docs/levi/<slug>/run.json`, so a stopped run resumes from the recorded stage rather than restarting. Run the steps under [Implementation](#implementation) through that runner, each agent call as a new named subagent call that gets only the paths and instructions written there.
72
+ - *Other tools without a Workflow tool:* run the steps under [Implementation](#implementation) yourself, in order, each agent call as a new subagent call that gets only the paths and instructions written there.
73
+ 7. **Act on the result.**
74
+ - `done`: go to step 8.
75
+ - `spec_questions`: the spec is silent or unclear on a point the tests depend on. Ask the user the questions in one round, run the `spec-writing` flow in update mode with the answers, then run step 6 again from the start.
76
+ - `blocked`: something outside the code stops the work (the app cannot start, a service or a credential is missing, an agent could not finish). Tell the user the stage and the detail, and what they need to provide. Keep `docs/levi/<slug>/`. Run step 6 again when they say to.
77
+ - `stalled`: the build rounds ran out (10 by default) and something still fails. Tell the user what failed last. On Claude Code, continue in the same session with `resumeFromRunId` and a higher `maxRounds`; on Codex, keep `run.json` and resume its active `build` stage after the user asks to continue. Tests and test cases still do not change.
78
+ 8. **Clean up.** Delete `docs/levi/<slug>/` (`tasks.md`, `review.md`, `locked/`), then `docs/levi` if it is empty. Keep everything else: spec, plan, designs, tests, test cases with their results, code.
79
+ 9. **Report.** Tell the user: the spec, plan and designs used (and which were created in this run); the test files and the command that runs them; the test case files with their result (for example `12/12 PASS`); how many build rounds it took; the review outcome and the suggestions left open; the files changed (from `git status`); and that nothing was committed.
80
+
81
+ ## Implementation
82
+
83
+ The steps the Workflow runs, and the ones you run when there is no Workflow tool. Every call names its agent; give it the paths of the spec, the plan, the designs and `docs/levi/<slug>/`. When a call returns questions that only the user can answer about the spec, stop with `spec_questions`. When a call is BLOCKED, stop with `blocked`.
84
+
85
+ 1. **Baseline.** Record `git rev-parse HEAD` and the files `git status --porcelain` lists, so the review later sees only this run's changes.
86
+ 2. **Plan** — `levi-teamlead`. Reads the spec, the plan, the designs and the project. Writes `docs/levi/<slug>/tasks.md`: the interfaces tests and code share (exact names of modules, functions, endpoints, routes, components, data shapes), the test framework and where tests go, and the development tasks from the brainstorming plan with their owners. Returns: every acceptance criterion ID; test groups (each with its criteria and folder) covering every criterion; implementation batches in dependency order, where tasks of one batch do not touch the same files; any test setup the project needs; the command for the new tests and the one for the whole suite; how to start the app for E2E. A criterion left out of every test group goes back to the teamlead.
87
+ 3. **Test setup** — `levi-developer`, only when the plan says the project cannot run tests yet.
88
+ 4. **Tests and scenarios**, two tracks at the same time:
89
+ - *Developer track.* One `levi-developer` call per test group, in parallel, writes unit and feature tests for its criteria, from the spec alone, against the interfaces in `tasks.md`, each test naming the criterion it covers. Then, until approved (at most 5 reviews): run the new tests (they are expected to fail, the feature does not exist yet), and a fresh `levi-teamlead` call reviews the tests against the spec: every criterion covered, every assertion from the spec and nothing beyond it, each test able to fail, one command that runs them. It does not edit them; a `levi-developer` call fixes what it found.
90
+ - *QA track.* `levi-qa` writes the test cases from the spec and the designs, without reading code or tests, following `levi-generate-test-scenarios/references/test-case-guide.md`, with the feature ID, the cases file `docs/levi/<slug>/test-cases.json` and the output base `docs/tests/<base>`. Every acceptance criterion is in the refs of at least one case, and every ambiguity it finds comes back as a question. Then, until approved (at most 5 reviews): a fresh `levi-pm` call reviews the test cases against the spec (coverage, exact expected results, nothing invented, runnable from the file alone); `levi-qa` fixes what it found.
91
+ 5. **Lock.** `node <skill folder>/scripts/lock-tests.mjs lock docs/levi/<slug>/locked <every test file>`, and the same with `docs/levi/<slug>/qa-snapshot docs/tests/<base>.md docs/tests/<base>.xlsx` for the test cases.
92
+ 6. **Build**, in rounds (at most 10 unless raised), until the teamlead approves and every scenario passes:
93
+ 1. *Code.* First round: each batch in order, the tasks of a batch in parallel, each by its owner (`levi-developer`, or `levi-teamlead` for schema, migrations and CI/CD). Later rounds: the owners fix exactly what the last round found.
94
+ 2. *Gate.* Run `lock-tests.mjs verify docs/levi/<slug>/locked` (it restores any locked file that was changed), then the new tests, then the whole suite. Any restored file, failing test or regression sends the round back to the developer with the failures.
95
+ 3. *Review* — once the tests pass, a fresh `levi-teamlead` call reviews the change since the baseline against the spec, `tasks.md` and the designs (correctness, security, performance, fit), following `levi-code-review/references/review-guide.md` and its checklists, writes `review.md` and approves only when no critical or warning finding is left. A change of more than 100 reviewable files is not read by one teamlead: it is split into slices of at most 100 files, reviewed by several fresh `levi-teamlead` calls at the same time, and a lead `levi-teamlead` call merges their reports into the one `review.md`, as `levi-code-review/references/large-changes.md` says. Findings go back to their owners, and the round starts again.
96
+ 4. *E2E* — only after the review approves. First `lock-tests.mjs verify docs/levi/<slug>/qa-snapshot`, which undoes any change to the test cases made outside QA. Then `levi-qa` starts the app, runs every case in a headless browser (the project's E2E runner such as Playwright, or a browser tool; through the API or CLI when there is no UI), records PASS or FAIL and the evidence as its test case guide says, and stops the app; the snapshot is then taken again. Any case that is not PASS goes back to the developer with the evidence, and the next round runs code, gate, review and E2E again.
97
+ 5. The run is done when the review approves and every case passes.
@@ -0,0 +1,57 @@
1
+ # Codex runner
2
+
3
+ This file is the durable runner for Codex. It replaces the Claude-only `workflow.js`; do not try to execute that file with Node or translate its state from chat history.
4
+
5
+ ## Start or continue
6
+
7
+ After preparation has selected a Ready spec, a plan and any required designs, use the state helper installed in this skill folder. Run every command below from the project root:
8
+
9
+ ```bash
10
+ node <this skill folder>/scripts/codex-run-state.mjs status docs/levi/<slug>
11
+ ```
12
+
13
+ If there is no state file, start one:
14
+
15
+ ```bash
16
+ node <this skill folder>/scripts/codex-run-state.mjs init docs/levi/<slug> create-feature <slug> plan tests lock build
17
+ ```
18
+
19
+ Never create a second state file for the same run. On a resumed run, read `status`; its `currentStage`, stage `status`, artifacts and history decide the next action. Do not repeat a completed stage.
20
+
21
+ Before starting or retrying the current stage, call `begin`. It is valid to call `begin` again on an active stage; that records a new attempt. A successful stage is recorded only after its required artifact exists:
22
+
23
+ ```bash
24
+ node <this skill folder>/scripts/codex-run-state.mjs begin docs/levi/<slug> <stage>
25
+ node <this skill folder>/scripts/codex-run-state.mjs complete docs/levi/<slug> <stage> <artifact>...
26
+ ```
27
+
28
+ For a question only the user can settle, or an external blocker, preserve the exact reason before returning it:
29
+
30
+ ```bash
31
+ node <this skill folder>/scripts/codex-run-state.mjs wait docs/levi/<slug> <stage> "<questions for the user>"
32
+ node <this skill folder>/scripts/codex-run-state.mjs block docs/levi/<slug> <stage> "<external blocker>"
33
+ ```
34
+
35
+ When the user answers or supplies the missing dependency, run `resume` and continue the same stage. Do not use `resumeFromRunId`: that is a Claude Workflow capability, not a Codex recovery mechanism.
36
+
37
+ ## Stages
38
+
39
+ ### `plan`
40
+
41
+ Dispatch `levi-teamlead` with only the spec, plan, designs, project and work-folder paths. It writes `tasks.md`. Check that every acceptance criterion has a test group, then complete this stage with `tasks.md`.
42
+
43
+ ### `tests`
44
+
45
+ Run the developer test groups and the QA scenario track as separate named Codex subagents. They may run in parallel only when their output paths do not overlap. The developer tests and QA cases are then independently reviewed and repaired until approved, up to the existing five-review limit. Do not advance until both tracks are approved and `test-cases.json`, `<testBase>.md` and `<testBase>.xlsx` exist. If a reviewer finds a spec ambiguity, mark this stage `wait`; do not guess.
46
+
47
+ ### `lock`
48
+
49
+ Run the existing `lock-tests.mjs` commands for the approved test files and QA deliverables. Complete only after both manifests exist: `locked/manifest.json` and `qa-snapshot/manifest.json`.
50
+
51
+ ### `build`
52
+
53
+ Keep this stage active through all build rounds. In each round, dispatch only the owner of the pending implementation, test, review or E2E finding. Then run the lock verification, feature tests and whole suite. Run the teamlead review only after the test gate passes; for more than 100 reviewable files follow `levi-code-review/references/large-changes.md` (a teamlead split, parallel teamlead slice reviews that write no file, then one teamlead merge that writes `review.md`). Run QA E2E only after that review approves. Record every real failure in the next Codex subagent prompt. Complete `build` only after the review approves and every QA case is PASS; pass `review.md`, `<testBase>.md` and `<testBase>.xlsx` as artifacts.
54
+
55
+ ## Dispatch contract
56
+
57
+ Use the installed named agents (`levi-teamlead`, `levi-developer`, `levi-qa`, `levi-pm`) rather than asking a general agent to impersonate a role. Each prompt must name the allowed input paths, output paths, acceptance criteria, and whether the agent may edit. The coordinator alone advances the state. Keep dependent operations in the coordinator; reserve parallel subagents for independent test groups or implementation batches that the plan says do not overlap.
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ // Locks the tests and test scenarios of a feature, so that nobody can change them to make them pass.
3
+ //
4
+ // node lock-tests.mjs lock <snapshot-dir> <path>... copy the files (folders are walked) and record their hashes
5
+ // node lock-tests.mjs verify <snapshot-dir> restore every locked file that was changed or deleted
6
+ //
7
+ // Run from the project root; paths are relative to it. `verify` prints JSON and exits 1 when it had to restore
8
+ // something. In Markdown files the `- **Status:**` and `- **Evidence:**` lines are left out of the hash: QA fills
9
+ // them in when it runs the scenarios, and that is not a change to the scenario.
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import crypto from 'node:crypto';
14
+
15
+ const RESULT_LINE = /^\s*- \*\*(Status|Evidence):\*\*.*$/gm;
16
+
17
+ function hash(file) {
18
+ let text = fs.readFileSync(file, 'utf8').replace(/\r\n/g, '\n');
19
+ if (file.endsWith('.md')) text = text.replace(RESULT_LINE, '');
20
+ return crypto.createHash('sha256').update(text).digest('hex');
21
+ }
22
+
23
+ function walk(p) {
24
+ if (!fs.existsSync(p)) throw new Error(`not found: ${p}`);
25
+ if (!fs.statSync(p).isDirectory()) return [p];
26
+ return fs.readdirSync(p).flatMap((name) => walk(path.join(p, name)));
27
+ }
28
+
29
+ function lock(dir, paths) {
30
+ if (!paths.length) throw new Error('nothing to lock');
31
+ const files = {};
32
+ for (const file of [...new Set(paths.flatMap(walk))].map((f) => path.normalize(f))) {
33
+ const copy = path.join(dir, 'files', file);
34
+ fs.mkdirSync(path.dirname(copy), { recursive: true });
35
+ fs.copyFileSync(file, copy);
36
+ files[file] = hash(file);
37
+ }
38
+ fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify({ files }, null, 2) + '\n');
39
+ console.log(JSON.stringify({ locked: Object.keys(files) }, null, 2));
40
+ }
41
+
42
+ function verify(dir) {
43
+ const { files } = JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf8'));
44
+ const restored = [];
45
+ for (const [file, expected] of Object.entries(files)) {
46
+ if (fs.existsSync(file) && hash(file) === expected) continue;
47
+ fs.mkdirSync(path.dirname(file), { recursive: true });
48
+ fs.copyFileSync(path.join(dir, 'files', file), file);
49
+ restored.push(file);
50
+ }
51
+ console.log(JSON.stringify({ intact: restored.length === 0, restored, checked: Object.keys(files).length }, null, 2));
52
+ if (restored.length) process.exitCode = 1;
53
+ }
54
+
55
+ const [cmd, dir, ...rest] = process.argv.slice(2);
56
+ try {
57
+ if (cmd === 'lock' && dir) lock(dir, rest);
58
+ else if (cmd === 'verify' && dir) verify(dir);
59
+ else {
60
+ console.error('usage: lock-tests.mjs lock <snapshot-dir> <path>... | verify <snapshot-dir>');
61
+ process.exitCode = 2;
62
+ }
63
+ } catch (e) {
64
+ console.error(e.message);
65
+ process.exitCode = 2;
66
+ }