levi-gear 0.0.0-stage → 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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +135 -2
  3. package/agents/_team-protocol.md +41 -0
  4. package/agents/designer.md +25 -0
  5. package/agents/developer.md +23 -0
  6. package/agents/pm.md +28 -0
  7. package/agents/qa.md +24 -0
  8. package/agents/teamlead.md +26 -0
  9. package/bin/levi.js +2 -0
  10. package/package.json +16 -4
  11. package/src/cli.js +51 -0
  12. package/src/commands/init.js +43 -0
  13. package/src/commands/list.js +19 -0
  14. package/src/commands/status.js +17 -0
  15. package/src/commands/update.js +29 -0
  16. package/src/lib/agents.js +62 -0
  17. package/src/lib/config.js +27 -0
  18. package/src/lib/desired-state.js +93 -0
  19. package/src/lib/frontmatter.js +36 -0
  20. package/src/lib/report.js +21 -0
  21. package/src/lib/role-skills.js +23 -0
  22. package/src/lib/router.js +38 -0
  23. package/src/lib/sync.js +110 -0
  24. package/src/lib/tools.js +98 -0
  25. package/src/lib/usecases.js +109 -0
  26. package/usecases/.gitkeep +0 -0
  27. package/usecases/brainstorming/SKILL.md +84 -0
  28. package/usecases/code-review/SKILL.md +79 -0
  29. package/usecases/code-review/references/performance-and-correctness.md +101 -0
  30. package/usecases/code-review/references/review-guide.md +70 -0
  31. package/usecases/code-review/references/security.md +119 -0
  32. package/usecases/create-feature/SKILL.md +94 -0
  33. package/usecases/create-feature/scripts/lock-tests.mjs +66 -0
  34. package/usecases/create-feature/workflow.js +440 -0
  35. package/usecases/design/SKILL.md +61 -0
  36. package/usecases/design/references/svg-guide.md +14 -0
  37. package/usecases/design/scripts/check-svg.py +77 -0
  38. package/usecases/fix-bug/SKILL.md +96 -0
  39. package/usecases/fix-bug/workflow.js +298 -0
  40. package/usecases/generate-test-scenarios/SKILL.md +97 -0
  41. package/usecases/generate-test-scenarios/references/test-case-guide.md +171 -0
  42. package/usecases/generate-test-scenarios/scripts/render-test-cases-markdown.mjs +76 -0
  43. package/usecases/generate-test-scenarios/scripts/render-test-cases.mjs +68 -0
  44. package/usecases/generate-test-scenarios/scripts/test-case-fields.mjs +63 -0
  45. package/usecases/generate-test-scenarios/scripts/validate-test-cases.mjs +69 -0
  46. package/usecases/generate-test-scenarios/scripts/write-xlsx.mjs +157 -0
  47. package/usecases/spec-writing/SKILL.md +59 -0
  48. package/usecases/spec-writing/references/spec-guide.md +62 -0
@@ -0,0 +1,440 @@
1
+ export const meta = {
2
+ name: 'levi-create-feature',
3
+ description: 'Implement a feature test-first: tests and QA scenarios from the spec, reviewed and locked, then code until every test passes, the teamlead approves the review and every E2E scenario passes',
4
+ whenToUse: 'Started by the levi-create-feature skill once the spec, the brainstorming plan and the designs are ready',
5
+ phases: [
6
+ { title: 'Plan', detail: 'the teamlead turns the brainstorming plan into an execution plan' },
7
+ { title: 'Tests', detail: 'developer tests and QA scenarios, written apart and reviewed against the spec' },
8
+ { title: 'Lock', detail: 'snapshot and hash the tests, and snapshot the test cases as QA wrote them' },
9
+ { title: 'Build', detail: 'implement, run the tests, review, then E2E; repeat until the review approves and every scenario passes' },
10
+ ],
11
+ }
12
+
13
+ // args: { slug, feature, spec, plan, designs?, featureId?, testBase?, skillDir, maxRounds? } — see the skill's SKILL.md.
14
+ const A = args || {}
15
+ const absent = ['slug', 'feature', 'spec', 'plan', 'skillDir'].filter((k) => !A[k])
16
+ if (absent.length) return { status: 'error', message: `missing args: ${absent.join(', ')}` }
17
+
18
+ const WORK = `docs/levi/${A.slug}`
19
+ const TASKS = `${WORK}/tasks.md`
20
+ const REVIEW = `${WORK}/review.md`
21
+ // QA's test cases, written and run with the test case guide of levi-generate-test-scenarios.
22
+ const FEATURE_ID = A.featureId || A.slug.toUpperCase()
23
+ const TEST_BASE = A.testBase || `docs/tests/${A.slug}-test-cases`
24
+ const SCENARIOS = `${TEST_BASE}.md`
25
+ const SCENARIO_FILES = [SCENARIOS, `${TEST_BASE}.xlsx`]
26
+ const CASES = `${WORK}/test-cases.json`
27
+ const TEST_GUIDE = `${A.skillDir}/../levi-generate-test-scenarios/references/test-case-guide.md`
28
+ const LOCK_DIR = `${WORK}/locked`
29
+ // Only QA changes its test cases: a snapshot taken after each QA step restores changes made by anyone else.
30
+ const QA_SNAPSHOT = `${WORK}/qa-snapshot`
31
+ const LOCK = `node ${A.skillDir}/scripts/lock-tests.mjs`
32
+ const REVIEW_GUIDE = `${A.skillDir}/../levi-code-review/references/review-guide.md`
33
+ const MAX_TEST_REVIEWS = 5
34
+ const MAX_BUILD_ROUNDS = A.maxRounds || 10
35
+
36
+ const CONTEXT = [
37
+ `Feature: ${A.feature}`,
38
+ `Spec, the single source of truth for what is expected: ${A.spec}`,
39
+ `Brainstorming plan: ${A.plan}`,
40
+ `Designs: ${A.designs || 'none'}`,
41
+ `Work folder: ${WORK}`,
42
+ ].join('\n')
43
+
44
+ const LOCKED_RULES = (tests) => `The test cases in ${SCENARIO_FILES.join(' and ')} belong to QA: do not edit them; a change by anyone else is undone. Locked files: the tests (${tests.join(', ')}). They were checked against the spec and are the definition of done. Never edit, delete, rename, skip or weaken any of them, and never change test configuration to leave them out. A locked file you change is restored automatically and your work is wasted. When a test fails, the code is wrong: fix the code, at the root cause, without special-casing test inputs.`
45
+
46
+ // ---- schemas ----
47
+
48
+ const STATUS = { type: 'string', enum: ['DONE', 'DONE_WITH_CONCERNS', 'BLOCKED', 'NEEDS_CONTEXT'] }
49
+ const QUESTIONS = {
50
+ type: 'array',
51
+ items: { type: 'string' },
52
+ description: 'Questions only the user can answer, because the spec is silent, unclear or contradictory on a point that changes the work. Empty when none.',
53
+ }
54
+ const STRINGS = { type: 'array', items: { type: 'string' } }
55
+ const obj = (properties) => ({ type: 'object', properties, required: Object.keys(properties) })
56
+
57
+ const PLAN = obj({
58
+ status: STATUS,
59
+ summary: { type: 'string' },
60
+ criteria: { ...STRINGS, description: 'Every acceptance criterion ID in the spec' },
61
+ hasUi: { type: 'boolean' },
62
+ testSetup: { type: 'string', description: 'What must be installed or configured before unit and feature tests can run; empty when nothing' },
63
+ testCommand: { type: 'string', description: 'Shell command, from the project root, that runs only the new unit and feature tests of this feature' },
64
+ suiteCommand: { type: 'string', description: 'Shell command that runs the whole existing test suite; empty when the project has none' },
65
+ app: obj({ start: { type: 'string' }, url: { type: 'string' }, notes: { type: 'string' } }),
66
+ testGroups: {
67
+ type: 'array',
68
+ items: obj({ id: { type: 'string' }, area: { type: 'string' }, criteria: STRINGS, location: { type: 'string' } }),
69
+ },
70
+ batches: {
71
+ type: 'array',
72
+ description: 'Implementation batches in order. Tasks in one batch run in parallel and must not touch the same files',
73
+ items: {
74
+ type: 'array',
75
+ items: obj({
76
+ id: { type: 'string' },
77
+ title: { type: 'string' },
78
+ owner: { type: 'string', enum: ['levi-developer', 'levi-teamlead'] },
79
+ criteria: STRINGS,
80
+ areas: { type: 'string' },
81
+ }),
82
+ },
83
+ },
84
+ questions: QUESTIONS,
85
+ })
86
+
87
+ const WRITTEN = obj({ status: STATUS, summary: { type: 'string' }, files: STRINGS, scenarioCount: { type: 'integer' }, questions: QUESTIONS })
88
+
89
+ const SPEC_REVIEW = obj({
90
+ approved: { type: 'boolean' },
91
+ issues: {
92
+ type: 'array',
93
+ items: obj({ file: { type: 'string' }, criterion: { type: 'string' }, problem: { type: 'string' }, fix: { type: 'string' } }),
94
+ },
95
+ testCommand: { type: 'string', description: 'The command that runs exactly these tests; empty for scenarios' },
96
+ questions: QUESTIONS,
97
+ })
98
+
99
+ const RUN = obj({ exitCode: { type: 'integer' }, summary: { type: 'string' } })
100
+ const GATE = obj({ restored: STRINGS, testsExit: { type: 'integer' }, suiteExit: { type: 'integer' }, failures: { type: 'string' } })
101
+ const BASE = obj({ head: { type: 'string' }, dirty: STRINGS })
102
+ const E2E = obj({
103
+ status: STATUS,
104
+ summary: { type: 'string' },
105
+ results: { type: 'array', items: obj({ id: { type: 'string' }, result: { type: 'string', enum: ['PASS', 'FAIL'] }, evidence: { type: 'string' } }) },
106
+ })
107
+ const IMPL = obj({ status: STATUS, summary: { type: 'string' }, files: STRINGS, blockers: STRINGS })
108
+ const CODE_REVIEW = obj({
109
+ approved: { type: 'boolean' },
110
+ summary: { type: 'string' },
111
+ findings: {
112
+ type: 'array',
113
+ items: obj({
114
+ severity: { type: 'string', enum: ['critical', 'warning', 'suggestion'] },
115
+ owner: { type: 'string', enum: ['levi-developer', 'levi-teamlead'] },
116
+ file: { type: 'string' },
117
+ problem: { type: 'string' },
118
+ fix: { type: 'string' },
119
+ }),
120
+ },
121
+ })
122
+
123
+ // ---- helpers ----
124
+
125
+ // Mechanical steps (git, the lock script, running tests) go to a plain agent that only runs commands.
126
+ const guard = (label, prompt, schema) =>
127
+ agent(`${prompt}\n\nRun the commands from the project root. Do not create, edit or delete any file yourself, and do not try to fix anything. Report only what you observed.`, {
128
+ label,
129
+ schema,
130
+ effort: 'low',
131
+ })
132
+
133
+ const runGate = (testCommand, suiteCommand) =>
134
+ guard(
135
+ 'gate',
136
+ [
137
+ `1. Run \`${LOCK} verify ${LOCK_DIR}\` and put the paths it lists under "restored" into restored (empty list when intact).`,
138
+ `2. Run \`${testCommand}\` and record its exit code as testsExit.`,
139
+ suiteCommand && suiteCommand !== testCommand
140
+ ? `3. Run \`${suiteCommand}\` and record its exit code as suiteExit.`
141
+ : '3. There is no separate suite: set suiteExit to testsExit.',
142
+ 'In failures, summarize every failing or erroring test: file, test name, and the first lines of the error. At most 80 lines. Empty when everything passed.',
143
+ ].join('\n'),
144
+ GATE,
145
+ )
146
+
147
+ const questionsOf = (...results) => [...new Set(results.filter(Boolean).flatMap((r) => r.questions || []))]
148
+ const blocked = (results) => results.filter((r) => !r || r.status === 'BLOCKED')
149
+
150
+ // ---- 1. Plan ----
151
+
152
+ phase('Plan')
153
+ const base = await guard('baseline', 'Run `git rev-parse HEAD` (use "none" when the repository has no commit yet) and `git status --porcelain`. Return the commit as head and the paths listed by git status as dirty.', BASE)
154
+
155
+ let plan = await agent(
156
+ `${CONTEXT}
157
+
158
+ You are starting the implementation of this feature. Read the spec, the brainstorming plan, the designs and the project, then:
159
+
160
+ 1. Write ${TASKS}: the execution plan the team follows. It holds the interfaces the tests and the code share (modules, functions, endpoints, routes, components, data shapes, with exact names), the test framework and where tests go, and the implementation tasks taken from the brainstorming plan. Keep the owners the plan gives; only development work goes into the batches (spec, design, QA and acceptance work is handled elsewhere). Database schema, migrations and CI/CD tasks are yours (levi-teamlead); application code is levi-developer's.
161
+ 2. Return the execution plan as structured data:
162
+ - criteria: every acceptance criterion ID in the spec.
163
+ - testGroups: split the unit and feature tests into groups that can be written in parallel, each with the criteria it covers and the folder where the project's framework expects those tests. Every criterion belongs to at least one group.
164
+ - batches: the implementation tasks in dependency order. Tasks in one batch run in parallel in the same working tree, so they must not touch the same files.
165
+ - testSetup when the project cannot run unit and feature tests yet (pick the framework that fits the stack), testCommand, suiteCommand, and how to start the app for end-to-end tests (app.start, app.url, app.notes, including seed data or env it needs).
166
+ Ask in questions only what the spec cannot answer.`,
167
+ { label: 'teamlead:plan', agentType: 'levi-teamlead', schema: PLAN },
168
+ )
169
+ for (let i = 0; plan && i < 2; i++) {
170
+ const grouped = new Set(plan.testGroups.flatMap((g) => g.criteria))
171
+ const uncovered = plan.criteria.filter((c) => !grouped.has(c))
172
+ if (!uncovered.length) break
173
+ log(`criteria with no test group: ${uncovered.join(', ')}; asking the teamlead to fix the plan`)
174
+ plan = await agent(
175
+ `${CONTEXT}\n\nYour execution plan in ${TASKS} leaves these acceptance criteria out of every test group: ${uncovered.join(', ')}. Put each into a test group, update ${TASKS}, and return the whole corrected plan.`,
176
+ { label: 'teamlead:plan-fix', agentType: 'levi-teamlead', schema: PLAN },
177
+ )
178
+ }
179
+ if (!plan || plan.status === 'BLOCKED') return { status: 'blocked', stage: 'plan', detail: plan ? plan.summary : 'the teamlead did not return a plan' }
180
+ if (questionsOf(plan).length) return { status: 'spec_questions', stage: 'plan', questions: questionsOf(plan) }
181
+
182
+ if (plan.testSetup) {
183
+ const setup = await agent(
184
+ `${CONTEXT}\n\nPrepare the project so that unit and feature tests can run, as the execution plan in ${TASKS} says: ${plan.testSetup}\nInstall and configure only that. Do not write any test or feature code yet. Check it by running \`${plan.testCommand}\` (no tests found is fine at this point).`,
185
+ { label: 'developer:test-setup', agentType: 'levi-developer', schema: IMPL },
186
+ )
187
+ if (!setup || setup.status === 'BLOCKED') return { status: 'blocked', stage: 'test setup', detail: setup ? setup.blockers : [] }
188
+ }
189
+
190
+ // ---- 2. Tests and scenarios, written apart, each reviewed against the spec ----
191
+
192
+ phase('Tests')
193
+
194
+ async function developerTests() {
195
+ const written = await parallel(
196
+ plan.testGroups.map((g) => () =>
197
+ agent(
198
+ `${CONTEXT}
199
+
200
+ Write the unit tests and feature tests of test group ${g.id} (${g.area}). They cover acceptance criteria ${g.criteria.join(', ')}. Put them in ${g.location}, with the project's framework and conventions, against the interfaces in ${TASKS}.
201
+
202
+ - The spec is the only source of what is expected. Every assertion follows from the spec (and the design for UI): values, messages, status codes, states, the edge cases, invalid input, error cases and permissions it states. Do not assert anything the spec does not state.
203
+ - Every criterion of the group has at least one test, and each test names the criterion it covers (for example "AC-3: ...").
204
+ - The feature is not built yet, so these tests are expected to fail now. Do not write application code, stubs or fakes of the feature.
205
+ - Work from the spec alone: do not read ${SCENARIOS} or the tests of other groups. If files from an earlier run exist, bring them in line with the spec.
206
+ - After this step the tests are locked: the code will have to pass them and nobody may change them. Get them right now.
207
+
208
+ Return every test file you created or changed (helpers and fixtures included).`,
209
+ { label: `developer:tests-${g.id}`, phase: 'Tests', agentType: 'levi-developer', schema: WRITTEN },
210
+ ),
211
+ ),
212
+ )
213
+ if (blocked(written).length) return { stop: 'blocked', detail: written.map((w) => w && w.summary) }
214
+ let questions = questionsOf(...written)
215
+ if (questions.length) return { stop: 'spec_questions', questions }
216
+ const files = [...new Set(written.flatMap((w) => w.files))]
217
+ let testCommand = plan.testCommand
218
+
219
+ for (let i = 1; i <= MAX_TEST_REVIEWS; i++) {
220
+ const red = await guard(`red-run-${i}`, `Run \`${testCommand}\`. These tests were written before the feature exists, so failures are expected. Return the exit code, and in summary the result of each test (pass, fail or error) with the first line of each error. At most 80 lines.`, RUN)
221
+ const review = await agent(
222
+ `${CONTEXT}
223
+
224
+ Review the unit and feature tests of this feature against the spec, as an independent reviewer: ${files.join(', ')}. Interfaces: ${TASKS}.
225
+ Result of running them before any implementation exists (exit ${red ? red.exitCode : '?'}):
226
+ ${red ? red.summary : 'not available'}
227
+
228
+ Check that:
229
+ - every acceptance criterion in ${plan.criteria.join(', ')} is covered;
230
+ - every assertion follows from the spec (and the design) exactly, and nothing asserts behavior the spec does not state;
231
+ - each test can fail on a real bug; a test that already passes without the feature needs a real reason;
232
+ - they use the project's framework and the interfaces in ${TASKS}, and one command runs exactly these tests (return it as testCommand).
233
+
234
+ The tests belong to the developer: do not edit them. Approve only when nothing is left to change.`,
235
+ { label: `teamlead:review-tests-${i}`, phase: 'Tests', agentType: 'levi-teamlead', schema: SPEC_REVIEW },
236
+ )
237
+ if (!review) return { stop: 'blocked', detail: 'the test review did not complete' }
238
+ if (review.testCommand) testCommand = review.testCommand
239
+ questions = questionsOf(review)
240
+ if (questions.length) return { stop: 'spec_questions', questions }
241
+ if (review.approved) return { files, testCommand }
242
+ const fixed = await agent(
243
+ `${CONTEXT}\n\nThe review of your unit and feature tests against the spec found these problems. Fix each one in the tests, and only these:\n${JSON.stringify(review.issues, null, 2)}\nThe spec decides. Do not write application code. Return every test file of the feature (${files.join(', ')}, plus any you add).`,
244
+ { label: `developer:fix-tests-${i}`, phase: 'Tests', agentType: 'levi-developer', schema: WRITTEN },
245
+ )
246
+ if (fixed) fixed.files.forEach((f) => files.includes(f) || files.push(f))
247
+ }
248
+ return { stop: 'blocked', detail: `the tests were not approved after ${MAX_TEST_REVIEWS} reviews` }
249
+ }
250
+
251
+ async function qaScenarios() {
252
+ let written = await agent(
253
+ `${CONTEXT}
254
+
255
+ Write the test cases of this feature, following your test case guide, ${TEST_GUIDE} ("The source rule" and "Writing test cases").
256
+
257
+ Sources (your only ones): the spec ${A.spec}${A.designs ? ` and the designs in ${A.designs}` : ''}. Do not read the application code or the developer's tests.
258
+ Feature ID: ${FEATURE_ID}
259
+ Cases file: ${CASES}
260
+ Output base: ${TEST_BASE}. If its files exist from an earlier run, they are yours: get the cases back as the guide's "Changing test cases" says and bring them in line with the spec.
261
+
262
+ On top of the guide:
263
+ - Every acceptance criterion in ${plan.criteria.join(', ')} is in the refs of at least one case.
264
+ - Each case can be run end to end ${plan.hasUi ? 'in a browser' : 'through the API or the CLI'} by someone who has only the rendered file and the running app (${plan.app.url}).
265
+ - Do not record results: they are recorded when the cases are run, after the code is built.
266
+ - The spec is Ready, so it should settle everything a case needs. Put every ambiguity you find into questions as well.
267
+
268
+ Return the number of cases as scenarioCount.`,
269
+ { label: 'qa:scenarios', phase: 'Tests', agentType: 'levi-qa', schema: WRITTEN },
270
+ )
271
+ if (!written || written.status === 'BLOCKED') return { stop: 'blocked', detail: written ? written.summary : 'QA did not write the scenarios' }
272
+ let questions = questionsOf(written)
273
+ if (questions.length) return { stop: 'spec_questions', questions }
274
+
275
+ for (let i = 1; i <= MAX_TEST_REVIEWS; i++) {
276
+ const review = await agent(
277
+ `${CONTEXT}
278
+
279
+ Review the test cases in ${SCENARIOS} against the spec, as an independent reviewer. Check that:
280
+ - every acceptance criterion in ${plan.criteria.join(', ')} is covered by at least one case (its Notes name the criteria it traces to);
281
+ - every Expected Result matches the spec exactly, and no case expects behavior the spec does not state;
282
+ - each case can be run end to end from the file alone.
283
+
284
+ The file belongs to QA: do not edit it. Approve only when nothing is left to change.`,
285
+ { label: `pm:review-scenarios-${i}`, phase: 'Tests', agentType: 'levi-pm', schema: SPEC_REVIEW },
286
+ )
287
+ if (!review) return { stop: 'blocked', detail: 'the scenario review did not complete' }
288
+ questions = questionsOf(review)
289
+ if (questions.length) return { stop: 'spec_questions', questions }
290
+ if (review.approved) return { scenarioCount: written.scenarioCount }
291
+ written =
292
+ (await agent(
293
+ `${CONTEXT}\n\nThe review of ${SCENARIOS} against the spec found these problems. Fix each one, and only these, as your test case guide (${TEST_GUIDE}, "Changing test cases") says, with the cases file ${CASES} and the output base ${TEST_BASE}:\n${JSON.stringify(review.issues, null, 2)}\nThe spec decides. Return the number of cases as scenarioCount.`,
294
+ { label: `qa:fix-scenarios-${i}`, phase: 'Tests', agentType: 'levi-qa', schema: WRITTEN },
295
+ )) || written
296
+ }
297
+ return { stop: 'blocked', detail: `the scenarios were not approved after ${MAX_TEST_REVIEWS} reviews` }
298
+ }
299
+
300
+ const [tests, scenarios] = await parallel([developerTests, qaScenarios])
301
+ for (const [stage, r] of [['tests', tests], ['scenarios', scenarios]]) {
302
+ if (!r) return { status: 'blocked', stage, detail: 'the step did not complete' }
303
+ if (r.stop === 'spec_questions') return { status: 'spec_questions', stage, questions: r.questions }
304
+ if (r.stop) return { status: 'blocked', stage, detail: r.detail }
305
+ }
306
+
307
+ // ---- 3. Lock ----
308
+
309
+ phase('Lock')
310
+ const snapshotScenarios = () => guard('qa-snapshot', `Run \`${LOCK} lock ${QA_SNAPSHOT} ${SCENARIO_FILES.join(' ')}\` and return its exit code, and its output as summary.`, RUN)
311
+ const restoreScenarios = () => guard('qa-restore', `Run \`${LOCK} verify ${QA_SNAPSHOT}\` and return its exit code, and its output as summary.`, RUN)
312
+ const locked = await guard('lock', `Run \`${LOCK} lock ${LOCK_DIR} ${tests.files.join(' ')}\` and return its exit code, and its output as summary.`, RUN)
313
+ if (!locked || locked.exitCode !== 0) return { status: 'blocked', stage: 'lock', detail: locked ? locked.summary : 'the lock step did not complete' }
314
+ const snapped = await snapshotScenarios()
315
+ if (!snapped || snapped.exitCode !== 0) return { status: 'blocked', stage: 'lock', detail: snapped ? snapped.summary : 'the test cases could not be snapshotted' }
316
+ log(`locked ${tests.files.length} test file(s); ${scenarios.scenarioCount} test case(s) kept as QA wrote them`)
317
+
318
+ // ---- 4. Build: implement, tests, review, then E2E, until the review approves and every scenario passes ----
319
+
320
+ const RULES = LOCKED_RULES(tests.files)
321
+
322
+ async function implement() {
323
+ for (const [b, batch] of plan.batches.entries()) {
324
+ const done = await parallel(
325
+ batch.map((t) => () =>
326
+ agent(
327
+ `${CONTEXT}
328
+
329
+ Implement task ${t.id}: ${t.title}. Areas: ${t.areas}. Acceptance criteria: ${t.criteria.join(', ') || 'see the task'}. Follow ${TASKS}, the spec, the designs and the project's conventions.
330
+ Other tasks of this batch run at the same time in the same working tree: touch only the areas of your task.
331
+ ${RULES}
332
+ Before finishing, run the tests that cover your task and report the real result.`,
333
+ { label: `${t.owner.replace('levi-', '')}:${t.id}`, phase: 'Build', agentType: t.owner, schema: IMPL },
334
+ ),
335
+ ),
336
+ )
337
+ const stuck = blocked(done)
338
+ if (stuck.length) return { blocked: `batch ${b + 1}`, detail: stuck.map((d) => (d ? d.blockers.join('; ') || d.summary : 'an agent did not complete')) }
339
+ }
340
+ return {}
341
+ }
342
+
343
+ async function fix(items) {
344
+ for (const owner of ['levi-teamlead', 'levi-developer']) {
345
+ const mine = items.filter((f) => f.owner === owner)
346
+ if (!mine.length) continue
347
+ const done = await agent(
348
+ `${CONTEXT}
349
+
350
+ Fix the code so that the following pass. Each item says where it comes from (unit and feature tests, end-to-end scenarios, or the code review):
351
+ ${mine.map((f) => `- [${f.source}] ${f.detail}`).join('\n')}
352
+
353
+ ${RULES}
354
+ Before finishing, run \`${tests.testCommand}\` and report the real result.`,
355
+ { label: `${owner.replace('levi-', '')}:fix`, phase: 'Build', agentType: owner, schema: IMPL },
356
+ )
357
+ if (!done || done.status === 'BLOCKED') return { blocked: 'fix', detail: done ? done.blockers : ['the fix did not complete'] }
358
+ }
359
+ return {}
360
+ }
361
+
362
+ async function e2e(note) {
363
+ return agent(
364
+ `${CONTEXT}
365
+
366
+ The code was approved in review. Run every test case in ${SCENARIOS} (there are ${scenarios.scenarioCount}) against the running app and record the results, following your test case guide, ${TEST_GUIDE} ("Recording results"), with the cases file ${CASES} and the output base ${TEST_BASE}. Run them ${
367
+ plan.hasUi
368
+ ? "in a headless browser: the project's E2E runner (such as Playwright) or a browser tool you have"
369
+ : 'through its API or CLI'
370
+ }. Start the app with \`${plan.app.start}\` (${plan.app.url}; ${plan.app.notes}) and stop it when you are done.
371
+ Change no application code. Return the result of every case, by its ID.${note ? `\n\n${note}` : ''}`,
372
+ { label: 'qa:e2e', phase: 'Build', agentType: 'levi-qa', schema: E2E },
373
+ )
374
+ }
375
+
376
+ phase('Build')
377
+ let pending = null
378
+ let last = null
379
+ for (let round = 1; round <= MAX_BUILD_ROUNDS; round++) {
380
+ log(`build round ${round}`)
381
+ const step = pending ? await fix(pending) : await implement()
382
+ if (step.blocked) return { status: 'blocked', stage: step.blocked, detail: step.detail }
383
+
384
+ const gate = await runGate(tests.testCommand, plan.suiteCommand)
385
+ if (!gate) return { status: 'blocked', stage: 'gate', detail: 'the test run did not complete' }
386
+ const tampered = gate.restored.length ? ` These locked files had been changed and were restored: ${gate.restored.join(', ')}. Never touch them.` : ''
387
+ if (gate.restored.length || gate.testsExit !== 0 || gate.suiteExit !== 0) {
388
+ last = { stage: 'tests', failures: gate.failures, restored: gate.restored }
389
+ pending = [{ owner: 'levi-developer', source: 'tests', detail: `${gate.failures || 'the test run failed'}${tampered}` }]
390
+ continue
391
+ }
392
+
393
+ const review = await agent(
394
+ `${CONTEXT}
395
+
396
+ Review the code change of this feature as the gate before merge. The change is everything that differs from commit ${base.head} (git diff and untracked files), leaving out files that were already modified before the run: ${base.dirty.join(', ') || 'none'}.
397
+ All unit and feature tests pass. The tests are locked and the test cases are QA's; both are correct by definition: do not propose changing them.
398
+ Check the change against the spec, ${TASKS} and the designs: correctness, security (input validation, authorization, secrets), performance, fit with the architecture and conventions, missing pieces.
399
+ Follow ${REVIEW_GUIDE} and the two checklists next to it (security by OWASP Top 10, performance and correctness), but write the findings where and how this prompt says.
400
+ Write ${REVIEW}: findings graded critical / warning / suggestion, each with the file, the problem, a concrete fix and its owner (levi-teamlead for schema, migrations and CI/CD, levi-developer for the rest). Approve only when no critical or warning finding remains; suggestions alone do not block.`,
401
+ { label: `teamlead:review-${round}`, phase: 'Build', agentType: 'levi-teamlead', schema: CODE_REVIEW },
402
+ )
403
+ if (!review) return { status: 'blocked', stage: 'review', detail: 'the code review did not complete' }
404
+ const blocking = review.findings.filter((f) => f.severity !== 'suggestion')
405
+ if (!review.approved || blocking.length) {
406
+ last = { stage: 'review', findings: blocking }
407
+ pending = blocking.map((f) => ({ owner: f.owner, source: `review ${f.severity}`, detail: `${f.file}: ${f.problem} Fix: ${f.fix}` }))
408
+ continue
409
+ }
410
+
411
+ // The review approved: QA runs the scenarios end to end.
412
+ // Changes to the test cases by anyone but QA are undone before QA runs them; QA's own results are kept after.
413
+ const restored = await restoreScenarios()
414
+ if (restored && restored.exitCode !== 0) log('the test cases had been changed outside QA and were restored')
415
+ const run = await e2e()
416
+ if (!run) return { status: 'blocked', stage: 'e2e', detail: 'the E2E run did not complete' }
417
+ await snapshotScenarios()
418
+ const caseIds = Array.from({ length: scenarios.scenarioCount }, (_, i) => `TC-${FEATURE_ID}-${String(i + 1).padStart(3, '0')}`)
419
+ const passed = new Set(run.results.filter((r) => r.result === 'PASS').map((r) => r.id))
420
+ const failing = caseIds.filter((id) => !passed.has(id))
421
+ if (!failing.length) {
422
+ return {
423
+ status: 'done',
424
+ rounds: round,
425
+ tests: tests.files,
426
+ testCommand: tests.testCommand,
427
+ scenarios: { files: SCENARIO_FILES, count: scenarios.scenarioCount },
428
+ review: review.summary,
429
+ suggestions: review.findings.filter((f) => f.severity === 'suggestion'),
430
+ }
431
+ }
432
+ const evidence = failing.map((id) => {
433
+ const r = run.results.find((x) => x.id === id)
434
+ return `${id}: ${r ? r.evidence : 'not run'}`
435
+ })
436
+ last = { stage: 'e2e', failing, evidence }
437
+ pending = [{ owner: 'levi-developer', source: 'E2E', detail: `failing test cases in ${SCENARIOS}:\n${evidence.join('\n')}` }]
438
+ }
439
+
440
+ return { status: 'stalled', rounds: MAX_BUILD_ROUNDS, last }
@@ -0,0 +1,61 @@
1
+ ---
2
+ name: levi-design
3
+ description: Create UI/UX designs as SVG files with the Designer, from a plain text description, from images or videos the user uploads (screenshots, mockups, sketches, screen recordings), or from both. Videos are turned into key frames first. The SVG files go to docs/designs/<slug>/. Uses the project's spec in docs/specs/ as context when one exists; never creates or edits specs. Fits requests such as "design a login screen", "draw this screen as SVG", "recreate this mockup", "design the app shown in this video", "thiết kế màn hình X", "vẽ lại giao diện trong ảnh này".
4
+ argument-hint: "<what to design, and the images or videos to base it on>"
5
+ skill-for: designer
6
+ skill-when: you draw or change designs as SVG
7
+ skill-guide: references/svg-guide.md
8
+ ---
9
+
10
+ # Design
11
+
12
+ Turn a description, images or videos into SVG designs. `levi-designer` is the only agent that draws; you prepare what it needs to see, run it, check the files it wrote, and relay its questions to the user. Never draw, edit or fix an SVG yourself.
13
+
14
+ A design is built from what the user gave: the text, the images, the frames of the videos, the spec. Do not invent product content, data or features. When the designer needs a text or a value nobody provided, it uses a clearly marked placeholder.
15
+
16
+ ## Inputs
17
+
18
+ | Input | How it is used |
19
+ |---|---|
20
+ | Text | What to design, for whom, the style, the screens, the sizes. The words of the user decide whether an image is something to **recreate** or only a **style reference**. When it is unclear, recreate |
21
+ | Image (screenshot, mockup, photo of a sketch, PDF) | The designer reads it directly from a file path |
22
+ | Video or GIF | Cannot be read by the designer. You extract key frames to image files first (step 3) |
23
+ | Spec in `docs/specs/` | Context only: the user stories and rules the design must serve. Read-only |
24
+
25
+ ## Files
26
+
27
+ | File | Owner | Purpose |
28
+ |---|---|---|
29
+ | `docs/designs/<slug>/<name>.svg` | Designer | **The deliverable**: one file per screen, state or breakpoint |
30
+ | `docs/levi/<slug>/frames/` | Workflow | Scratch: key frames extracted from videos. Deleted at the end |
31
+ | `docs/levi/<slug>/references.md` | Workflow | Scratch: a plain description of images that exist only in the conversation. Deleted at the end |
32
+ | `docs/levi/<slug>/render/` | Workflow | Scratch: PNG renders of the SVG files, for the visual check. Deleted at the end |
33
+
34
+ `<slug>` is a short kebab-case name for what is designed, in English (for example `login-screen`). Create folders as needed. Pass the designer the exact paths it should read and write. The files the user uploaded are the user's: never move, edit or delete them.
35
+
36
+ ## Steps
37
+
38
+ 1. **Intake.** The request is the text plus the attachments. If there is neither text nor an attachment, ask what to design and stop. Derive the slug. List every image and video with its file path. Note the user's intent for each: recreate it, take its style, or extract its flow.
39
+ 2. **Find the context.**
40
+ - *Existing design.* List `docs/designs/` and match folders against the subject. One clear match is an update: the designer revises those files and leaves the rest as they are. Two or more equally plausible: ask the user which one (or "new design"). None: a new folder `docs/designs/<slug>/`.
41
+ - *Spec.* List `docs/specs/` and match files by name and title. Use a clear match as context and say which in one line; with no clear match, go on without one. Never create or edit anything under `docs/specs/`.
42
+ 3. **Prepare the references.** The designer works only from files, never from the conversation.
43
+ - *Images with a file path:* pass the path.
44
+ - *Images that exist only in the conversation* (pasted or attached with no path): write `docs/levi/<slug>/references.md` with one section per image, a plain description of what is visible and nothing else: the layout region by region, every text exactly as written, colors as hex values, sizes and spacing you can read, icons, states, and what you cannot make out. No design opinions, no additions. Name the section `Image N` and tell the designer that the description is its only view of that image.
45
+ - *Videos and GIFs:* extract key frames into `docs/levi/<slug>/frames/`. With ffmpeg, first try scene changes, and cap them at 12 frames:
46
+
47
+ ```bash
48
+ ffmpeg -i <video> -vf "select='gt(scene,0.25)',scale=1280:-2" -vsync vfr -frames:v 12 docs/levi/<slug>/frames/%02d.png
49
+ ```
50
+
51
+ If that gives fewer than 3 frames, take one frame every few seconds instead (`-vf "fps=1/3,scale=1280:-2"`). Look at the frames, keep one per distinct screen or state and delete near-duplicates, and write `frames/index.md` listing each frame with its timestamp or order. If ffmpeg is not installed, do not guess what the video shows: tell the user and ask for screenshots of the key screens (or for ffmpeg to be installed), then continue with what you have.
52
+ 4. **Designer draws.** Call `levi-designer` with: the request as the user wrote it, the intent for each reference, every reference path (images, `frames/`, `references.md`), the spec path if any, the existing design folder if updating, the output folder `docs/designs/<slug>/`, and the path of `references/svg-guide.md` in this skill's folder (the SVG rules). It must:
53
+ - decide the list of files before drawing, and keep tokens and components the same across all of them;
54
+ - write only SVG files in the output folder, no notes or other files;
55
+ - follow a recreate reference closely (layout, proportions, texts, colors, icons, states) and be honest about what it could not reproduce; follow a style reference for colors, type, radii and density only;
56
+ - return in its report the file list with one line per file, the assumptions it made, what it could not reproduce, and its questions.
57
+ 5. **Check the files.** Run the checker over the output folder: `python3 <this skill's folder>/scripts/check-svg.py docs/designs/<slug>/` (or `xmllint --noout` on each file if there is no Python). Then, if a renderer exists (`rsvg-convert`, `inkscape`, or headless Chrome/Chromium), render every SVG to `docs/levi/<slug>/render/<name>.png` and look at the renders. Check that nothing is cut off, overlapping or unreadable, that the texts are the right ones, and, for recreate references, that the design matches the reference. If there is no renderer, say so in the report and rely on the checker.
58
+ 6. **Fix, once.** When the checker or the render check found problems, call `levi-designer` once more with the exact problems (file, what is wrong, where) and the paths of the renders and references. It fixes only those, and you run step 5 again. Do not start a third pass: report what is still wrong.
59
+ 7. **Ask the user.** The designer cannot ask. Take the questions from its reports and ask them in one round (use the tool's structured question feature if it has one), each with two to four options and the recommended one first. Only ask what changes the design: missing content, a choice between layouts, an unclear reference. If the answers change files, call the designer once more with them and run step 5 again. Skip this step when there are no questions; the assumptions go in the report instead.
60
+ 8. **Clean up.** Delete `frames/`, `references.md` and `render/` from `docs/levi/<slug>/`, then remove the folder if empty, and `docs/levi` if that is empty. Delete only those, only after the designs are final. Keep the SVG files, the user's uploads and the spec.
61
+ 9. **Report.** Tell the user the folder, the files with one line each (what screen or state it shows), whether it is new or an update, the spec used (if any), the assumptions, what could not be reproduced from the references (photos become labeled placeholders, fonts fall back to the stack), what the checks found and fixed, and whether the render check ran. Offer the next step in one line only when it is obvious, such as the missing states or breakpoints.
@@ -0,0 +1,14 @@
1
+ # SVG guide
2
+
3
+ How `levi-designer` draws SVG designs, in the `design` usecase and in every usecase that has it draw. The prompt names what to draw, the references and the output folder. These rules add to the ones in your own definition.
4
+
5
+ ## Rules
6
+
7
+ - **Valid and self-contained.** `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 W H" width="W" height="H">`, with a `<title>` as the first child and a `<desc>` saying what the screen is. No `<image>`, no raster data, no external files, fonts, links or scripts, no `<foreignObject>`, no animation. Photos and illustrations are drawn as simple shapes or as a labeled placeholder rectangle.
8
+ - **One artboard per file.** One screen, state or breakpoint per file, drawn on an artboard with a background rect. Name files after what they show: `<screen>.svg`, `<screen>-<state>.svg`, `<screen>-<breakpoint>.svg`, in kebab-case.
9
+ - **Size.** Use the size of the reference when there is one (its aspect ratio is kept). Otherwise: mobile 390×844, tablet 768×1024, desktop 1440×900.
10
+ - **Tokens.** Define colors, type sizes, radii and shadows once per file in a `<style>` block as classes with literal values (`.text-primary{fill:#1F2937}`), and use the classes. Do not use CSS variables: many renderers ignore them. Reuse the same values in every file of the folder, and the project's tokens when it has them.
11
+ - **Structure.** Group by what things are, with kebab-case `id`s: `header`, `nav`, `card-order`, `button-primary`, `input-email`. Repeated parts (icons, buttons) are defined once in `<defs>` and drawn with `<use>`. Ids are unique in the file.
12
+ - **Text.** Real `<text>` elements, not outlines, so the content stays readable and searchable. Use a system font stack (`font-family="Inter, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif"`), never a font loaded from a URL. Text that wraps is split into `<tspan>` lines that fit their container.
13
+ - **Content.** Texts, labels, numbers and data come from the request or the references, exactly as given. Anything else is a placeholder, written like `[Product name]` or `Lorem ipsum`, never made-up facts, names or figures.
14
+ - **Accessibility.** Text contrast WCAG 2.1 AA (4.5:1, or 3:1 for large text), touch targets at least 44px, visible focus in focus states, meaning never by color alone. A recreate reference that breaks one of these is reproduced as it is and the problem is named in the report.
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env python3
2
+ """Check SVG design files against the levi-design rules.
3
+
4
+ Usage: check-svg.py <file.svg|folder> [...]
5
+
6
+ Prints one line per problem and exits 1 when any file has one. Standard library only.
7
+ """
8
+ import re
9
+ import sys
10
+ import xml.etree.ElementTree as ET
11
+ from pathlib import Path
12
+
13
+ SVG = "{http://www.w3.org/2000/svg}"
14
+ XLINK_HREF = "{http://www.w3.org/1999/xlink}href"
15
+ FORBIDDEN = {"script", "foreignObject", "iframe", "audio", "video", "animate", "animateTransform", "set"}
16
+
17
+
18
+ def local(tag):
19
+ return tag.split("}", 1)[-1] if isinstance(tag, str) else ""
20
+
21
+
22
+ def check(path):
23
+ problems = []
24
+ try:
25
+ root = ET.parse(path).getroot()
26
+ except ET.ParseError as e:
27
+ return [f"not well-formed XML: {e}"]
28
+
29
+ if root.tag != SVG + "svg":
30
+ problems.append("root element is not <svg xmlns=\"http://www.w3.org/2000/svg\">")
31
+ if not root.get("viewBox"):
32
+ problems.append("<svg> has no viewBox")
33
+ if not any(local(c.tag) == "title" for c in root):
34
+ problems.append("<svg> has no <title> as a direct child")
35
+
36
+ ids = set()
37
+ for el in root.iter():
38
+ name = local(el.tag)
39
+ if name in FORBIDDEN:
40
+ problems.append(f"<{name}> is not allowed")
41
+ if name == "image":
42
+ problems.append("<image> is not allowed: draw it as vector shapes or a labeled placeholder")
43
+ href = el.get("href") or el.get(XLINK_HREF) or ""
44
+ if href and not href.startswith("#"):
45
+ problems.append(f"<{name}> references something outside the file: {href[:60]}")
46
+ if any(a.startswith("on") for a in el.attrib):
47
+ problems.append(f"<{name}> has an event handler attribute")
48
+ i = el.get("id")
49
+ if i:
50
+ if i in ids:
51
+ problems.append(f"duplicate id \"{i}\"")
52
+ ids.add(i)
53
+ if name == "style" and el.text and re.search(r"@import|url\(\s*['\"]?(https?:|//|data:)", el.text):
54
+ problems.append("<style> loads an external resource")
55
+ return problems
56
+
57
+
58
+ def main(args):
59
+ files = []
60
+ for a in args:
61
+ p = Path(a)
62
+ files += sorted(p.rglob("*.svg")) if p.is_dir() else [p]
63
+ if not files:
64
+ print("no SVG files given", file=sys.stderr)
65
+ return 2
66
+ bad = 0
67
+ for f in files:
68
+ problems = check(f)
69
+ for msg in problems:
70
+ print(f"{f}: {msg}")
71
+ bad += bool(problems)
72
+ print(f"{len(files)} file(s) checked, {bad} with problems")
73
+ return 1 if bad else 0
74
+
75
+
76
+ if __name__ == "__main__":
77
+ sys.exit(main(sys.argv[1:]))