levi-gear 0.1.0 → 0.2.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 (36) hide show
  1. package/README.md +13 -8
  2. package/agents/_team-protocol.md +12 -5
  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 +1 -1
  9. package/src/commands/list.js +2 -1
  10. package/src/lib/agents.js +9 -2
  11. package/src/lib/desired-state.js +23 -7
  12. package/src/lib/role-skills.js +23 -0
  13. package/src/lib/tools.js +6 -1
  14. package/src/lib/usecases.js +40 -1
  15. package/usecases/brainstorming/SKILL.md +8 -4
  16. package/usecases/code-review/SKILL.md +79 -0
  17. package/usecases/code-review/references/performance-and-correctness.md +101 -0
  18. package/usecases/code-review/references/review-guide.md +70 -0
  19. package/usecases/code-review/references/security.md +119 -0
  20. package/usecases/create-feature/SKILL.md +94 -0
  21. package/usecases/create-feature/scripts/lock-tests.mjs +66 -0
  22. package/usecases/create-feature/workflow.js +440 -0
  23. package/usecases/design/SKILL.md +61 -0
  24. package/usecases/design/references/svg-guide.md +14 -0
  25. package/usecases/design/scripts/check-svg.py +77 -0
  26. package/usecases/fix-bug/SKILL.md +96 -0
  27. package/usecases/fix-bug/workflow.js +298 -0
  28. package/usecases/generate-test-scenarios/SKILL.md +97 -0
  29. package/usecases/generate-test-scenarios/references/test-case-guide.md +171 -0
  30. package/usecases/generate-test-scenarios/scripts/render-test-cases-markdown.mjs +76 -0
  31. package/usecases/generate-test-scenarios/scripts/render-test-cases.mjs +68 -0
  32. package/usecases/generate-test-scenarios/scripts/test-case-fields.mjs +63 -0
  33. package/usecases/generate-test-scenarios/scripts/validate-test-cases.mjs +69 -0
  34. package/usecases/generate-test-scenarios/scripts/write-xlsx.mjs +157 -0
  35. package/usecases/spec-writing/SKILL.md +59 -0
  36. package/usecases/spec-writing/references/spec-guide.md +62 -0
@@ -0,0 +1,70 @@
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. **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.
19
+
20
+ ## Scope
21
+
22
+ - 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.
23
+ - 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**.
24
+ - Leave formatting and naming to the linter, unless they break a convention the project documents.
25
+ - Do not report a problem twice. When one cause shows in several places, report it once and list every location.
26
+
27
+ ## Severities
28
+
29
+ | Severity | Meaning | Blocks merge |
30
+ |---|---|---|
31
+ | **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 |
32
+ | **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 |
33
+ | **suggestion** | Worth doing, not wrong today: hardening, a cheaper algorithm for inputs that stay small, clearer error messages | No |
34
+
35
+ 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.
36
+
37
+ ## Finding format
38
+
39
+ Each finding:
40
+
41
+ ````markdown
42
+ ### [critical] A03 Injection: SQL built from the search term
43
+ - **Where:** `src/orders/repository.js:42` (also `src/orders/export.js:17`)
44
+ - **Problem:** `search` from the query string is concatenated into the SQL text.
45
+ - **How it fails:** `?search=' OR 1=1 --` returns every customer's orders.
46
+ - **Fix:** Pass it as a bound parameter:
47
+ ```js
48
+ db.query('SELECT * FROM orders WHERE customer_id = $1 AND note ILIKE $2', [userId, `%${search}%`])
49
+ ```
50
+ - **Assumption:** (only when the finding depends on something you could not see; say what to check)
51
+ ````
52
+
53
+ - 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`).
54
+ - **Where** gives a path and line for every location.
55
+ - **How it fails** is the concrete case from step 6 of [How to review](#how-to-review).
56
+ - **Fix** is specific enough to apply without guessing: code for small fixes; for larger ones, the steps and the pattern, with a short sketch.
57
+
58
+ ## Verdict
59
+
60
+ - **Request changes** when any critical or warning finding is left.
61
+ - **Approve** otherwise. Approving with suggestions is fine.
62
+
63
+ ## The reply
64
+
65
+ Unless the prompt says otherwise, reply with:
66
+
67
+ 1. **Verdict** and a one-line summary: what the change does and its main risk.
68
+ 2. **Findings**, critical first, then warning, then suggestion, in the format above. Write "No findings." when there are none.
69
+ 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).
70
+ 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,94 @@
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. With a Workflow tool (Claude Code) it runs as `workflow.js`; otherwise you run the same steps one by one.
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
+ 2. **Spec.**
45
+ - *The user gave one:* use it.
46
+ - *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 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.
47
+ - *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.
48
+ - **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.
49
+ 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"). None: run the `brainstorming` flow, with the feature and the spec, and use the plan it writes.
50
+ 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; none: run the `design` flow with the feature as subject and the spec as context, and use the folder it writes.
51
+ 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.
52
+ 6. **Implement.**
53
+ - *With a Workflow tool (Claude Code):* call it with `scriptPath` set to `workflow.js` in this skill's folder, and `args`:
54
+
55
+ ```json
56
+ {
57
+ "slug": "<slug>",
58
+ "feature": "<the request, as the user wrote it>",
59
+ "spec": "docs/specs/<spec>.md",
60
+ "plan": "docs/brainstorming/<plan>.md",
61
+ "designs": "docs/designs/<design>/ (omit when there is no UI)",
62
+ "featureId": "<the feature ID>",
63
+ "testBase": "docs/tests/<base>",
64
+ "skillDir": "<this skill's folder, relative to the project root>"
65
+ }
66
+ ```
67
+
68
+ 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.
69
+ - *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.
70
+ 7. **Act on the result.**
71
+ - `done`: go to step 8.
72
+ - `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.
73
+ - `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.
74
+ - `stalled`: the build rounds ran out (10 by default) and something still fails. Tell the user what failed last. If they want to go on, in the same session call the Workflow tool again with `resumeFromRunId` and a higher `maxRounds` in `args`: finished agent calls are reused and the build continues. Tests and test cases still do not change.
75
+ 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.
76
+ 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.
77
+
78
+ ## Implementation
79
+
80
+ 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`.
81
+
82
+ 1. **Baseline.** Record `git rev-parse HEAD` and the files `git status --porcelain` lists, so the review later sees only this run's changes.
83
+ 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.
84
+ 3. **Test setup** — `levi-developer`, only when the plan says the project cannot run tests yet.
85
+ 4. **Tests and scenarios**, two tracks at the same time:
86
+ - *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.
87
+ - *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.
88
+ 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.
89
+ 6. **Build**, in rounds (at most 10 unless raised), until the teamlead approves and every scenario passes:
90
+ 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.
91
+ 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.
92
+ 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. Findings go back to their owners, and the round starts again.
93
+ 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.
94
+ 5. The run is done when the review approves and every case passes.
@@ -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
+ }