Use when implementing any feature, bugfix, API, or UI change that should follow Beads plus OpenSpec, and also synchronize existing spec documents when the current service already maintains them.
Quy trình đầy đủ từ yêu cầu → code đã verify. Tự động detect stack và apply conventions phù hợp.
Trước khi bắt đầu, xác định stack của task hiện tại:
BE (Backend) → Spring Boot / Java 21
FE (Frontend) → React / Vue / TypeScript
FS (Fullstack) → Cả hai
Cách detect:
Sau khi xác định stack → follow đúng profile bên dưới.
Trước khi vào Phase 0, kiểm tra nhanh các điều kiện tối thiểu:
bd / Beads workflow có dùng được khôngopenspec workflow có dùng được không/opsx:* skills có sẵn không (/opsx:propose, /opsx:apply, /opsx:verify, /opsx:archive, /opsx:ff nếu dùng fast track)./mvnw, ./gradlew, npm, yarn, pnpm, ...)Nếu thiếu tooling bắt buộc:
Nếu stack detection chưa đủ chắc chắn:
Kiểm tra init:
.beads/ đã được khởi tạo cho repo/service hiện tại/beads:initTạo issue:
bd create "<tên yêu cầu>" \
-t <feature|bug|task|epic> \
-p <0=critical|1=high|2=medium|3=low> \
-d "<mô tả: input/output/context/stack/openspec(+spec nếu có)>" \
-l "<labels: api|ui|backend|frontend|openspec|spec?>"
Map dependencies & bắt đầu:
bd dep add <issue-mới> <issue-phải-xong-trước> # nếu có
bd update <id> -s in_progress
Trước khi chuyển sang Phase 1 — chốt phạm vi tài liệu với user (bắt buộc):
proposal.md, specs/<capability>/spec.md, design.md, tasks.md)requirements.md, design-be.md, api-contract.md, tasks-be.md, testcase.md)requirements.md, design-fe.md, tasks-fe.md, testcase.md)Tạo change:
openspec new change "<bd-id>-<tên-kebab-case>"
## Why
[Vấn đề / cơ hội business]
## What Changes
- [Bullet: thay đổi ở high level]
## Capabilities
### New Capabilities
- `<tên>`: [mô tả]
## Impact
- `path/to/file`: [thay đổi gì]
### Requirement: <Tên>
#### Scenario: Happy path
- WHEN <điều kiện>
- THEN <kết quả>
- AND <bổ sung>
#### Scenario: Edge case / Error
- WHEN <input không hợp lệ>
- THEN <behavior>
Format WHEN/THEN dùng được cho cả API spec lẫn UI behavior spec.
## Context
[Trạng thái hiện tại]
## Goals / Non-Goals
## Technical Decisions
### Decision: <Quyết định>
[Lý do]
## Data Flow / Component Tree
[Diagram ASCII]
Khi nào phải dùng thêm Spec:
specs/features/<feature>/...requirements/design/api-contract/testcase/tasksKhi nào KHÔNG bắt buộc thêm Spec:
Nếu có Spec thì dùng bộ file chuẩn theo stack:
requirements.md, design-be.md, api-contract.md, tasks-be.md, testcase.mdrequirements.md, design-fe.md, tasks-fe.md, testcase.mddesign-be.md + design-fe.md, tasks-be.md + tasks-fe.md## Bối cảnh / Mục tiêu
[Vấn đề / cơ hội business]
## Yêu cầu
### Requirement: <Tên>
- WHEN <điều kiện>
- THEN <kết quả>
- AND <bổ sung>
## Acceptance Criteria
- [ ] AC-01 ...
- [ ] AC-02 ...
## Context
[Trạng thái hiện tại]
## Goals / Non-Goals
## Technical Decisions
### Decision: <Quyết định>
[Lý do]
## Data Flow / Component Tree
[Diagram ASCII]
## Endpoints / Contract
- Method + path
- Request
- Response
- Error codes
## Test Cases
- TC-01: Happy path
- TC-02: Validation error
- TC-03: Permission / security
Khi feature có đủ cả hai lớp tài liệu:
spec.md phải khớp với requirement/scenario trong requirements.mddesign.md và spec design-*.md phải cùng technical directiontasks.md giữ milestone/change-level; spec tasks-be.md / tasks-fe.md giữ implementation detailtestcase.md phải trace lại được các scenario đã viết trong OpenSpec/specScope & placement
OpenSpec completeness
proposal.md nêu rõ WHY, phạm vi thay đổi, impact chínhspecs/<capability>/spec.md có đủ happy path + edge/error scenarios theo format WHEN/THENdesign.md có context, goals/non-goals, technical decisions, data flow/component treetasks.md có milestone chính, verification steps, và mapping theo capability/scenarioSpec decision
Spec completeness (nếu áp dụng)
requirements.md khớp OpenSpec scenarios và có acceptance criteriadesign-be.md / design-fe.md phản ánh đúng technical direction đã chọnapi-contract.md mô tả đủ request/response/error semantics nếu có APItestcase.md trace được requirements/scenariostasks-be.md / tasks-fe.md phản ánh implementation detail theo stackTraceability & readiness
requirements.md) đã có hướng test tương ứng để sang Phase 2review scope / naming strategy từ Phase 1Sau khi viết xong tài liệu, DỪNG LẠI và trình bày tóm tắt cho user:
📋 REVIEW TÀI LIỆU — <change-or-feature-name>
**OpenSpec (bắt buộc):**
- Proposal (WHY): [tóm tắt]
- Capability + Scenarios: WHEN ... THEN ...
- Design decisions: [bullet]
- Tasks.md: [milestone chính]
**Spec (nếu có / nếu cần maintain):**
- Requirements / AC: [tóm tắt]
- Design-be/design-fe: [quyết định chính]
- API contract / UI contract: [điểm chính]
- Testcase + tasks-be/tasks-fe: [coverage chính]
**Sync check:**
- Nếu có cả 2: Scenario và tasks đã khớp chưa?
- Nếu chỉ có OpenSpec: lý do không dùng spec là gì?
---
Tài liệu đã đầy đủ chưa? Có điểm nào cần chỉnh không?
→ Trả lời "OK" hoặc "bắt đầu" để chuyển sang Phase 2 (TDD)
→ Hoặc nêu điểm cần chỉnh để cập nhật lại
Loop cho đến khi user approve:
Test từ Scenarios → JUnit 5 + MockMvc
// Unit test — Service layer
@ExtendWith(MockitoExtension.class)
class <Feature>ServiceTest {
@Mock private <Dep>Repository repo;
@InjectMocks private <Feature>ServiceImpl service;
@Test
void <method>_<condition>_<expected>() {
given(repo.findBy...).willReturn(...);
var result = service.method(input);
assertThat(result).isNotNull();
}
}
// Integration test — Controller layer
class <Feature>ApiTest extends IntegrationTestBase {
@Test
@WithMockCustomUser
void <endpoint>_<scenario>_<expected>() throws Exception {
mockMvc.perform(get("/api/...")
.param("key", "value"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data").isArray());
}
}
Chạy: ./mvnw test → phải FAIL (RED) ✓
Test từ Scenarios → ưu tiên test runner đang có trong repo (Jest / Vitest) + React Testing Library / framework tương đương
// Unit test — Hook / utility
describe('<featureName>', () => {
it('<condition> should <expected>', () => {
const { result } = renderHook(() => useFeature());
expect(result.current.data).toBeDefined();
});
});
// Component test — RTL
describe('<ComponentName>', () => {
it('renders correctly when <condition>', () => {
render(<Component prop={value} />);
expect(screen.getByText('...')).toBeInTheDocument();
});
it('calls handler when user <action>', async () => {
const onAction = jest.fn();
render(<Component onAction={onAction} />);
await userEvent.click(screen.getByRole('button', { name: '...' }));
expect(onAction).toHaveBeenCalledWith(expect.objectContaining({...}));
});
});
// E2E — Playwright (critical flows)
test('<scenario>', async ({ page }) => {
await page.goto('/booking');
await page.click('[data-testid="select-date"]');
await expect(page.locator('.calendar')).toBeVisible();
});
Chạy: test command hiện có của repo (npm test, yarn test, pnpm test, vitest, ...) → phải FAIL (RED) ✓
Thứ tự implement:
Entity → Repository → Migration SQL → DTO → Mapper → Service → Controller
Conventions bắt buộc:
| Layer | Convention |
|---|---|
| Entity | *Entity, ULID via @UlidSequence |
| DTO | *RequestDTO / *ResponseDTO, Jakarta Validation |
| Mapper | *Mapper interface, MapStruct @Mapper |
| Service | Interface *Service + impl *ServiceImpl |
| Controller | @RestController, @Operation, @AuditAction |
| DB | Dated SQL → register db.changelog-master.xml |
Implementation task template BE:
tasks-be.mdopenspec/.../tasks.md## 1. Data Layer
- [ ] 1.1 Entity (nếu cần)
- [ ] 1.2 Repository + query method
- [ ] 1.3 DB migration SQL
## 2. Business Layer
- [ ] 2.1 RequestDTO / ResponseDTO + validation
- [ ] 2.2 Mapper (MapStruct)
- [ ] 2.3 Service interface method
- [ ] 2.4 ServiceImpl
## 3. API Layer
- [ ] 3.1 Controller endpoint + Swagger @Operation
- [ ] 3.2 Swagger checklist đã cover đủ `@Tag` / `@RequestMapping` trên `*Operation` interface
- [ ] 3.3 Mỗi endpoint có `@Operation(summary, description)`; thêm `operationId` nếu API quan trọng hoặc public-facing
- [ ] 3.4 Response codes đã document đủ `200`, `400`, `404`, `409`, `401/403`, `500` theo đúng behavior thực tế
- [ ] 3.5 Happy-path response có `schema` hoặc `examples`; file download/export dùng `type=string`, `format=binary`
- [ ] 3.6 Các example JSON dài được tách thành hằng `String ..._EXAMPLE` ở đầu `*Operation` interface để tái sử dụng
- [ ] 3.7 `@RequestParam` / `@PathVariable` / `Pageable` / filter params được annotate bằng `@Parameter`, có `description`, `required`, `example`, `allowableValues` khi phù hợp
- [ ] 3.8 Query/filter object và `Pageable` dùng `@ParameterObject`; mô tả rõ default paging/sort nếu có
- [ ] 3.9 Request body JSON dùng Swagger/OpenAPI `@io.swagger.v3.oas.annotations.parameters.RequestBody` với `description`, `schema`, `examples`
- [ ] 3.10 Khi mô tả request body hoặc response body trong Swagger/OpenAPI, `description` phải nêu rõ tên DTO tương ứng để người đọc refer nhanh trên Swagger UI (ví dụ `CreateExchangeRateRequestDTO`, `ExchangeRateResponseDTO`)
- [ ] 3.11 Multipart request mô tả rõ từng part (`data`, `file`) và semantics của từng part
- [ ] 3.12 Workflow/action endpoint mô tả rõ state transition, business preconditions và các conflict/error quan trọng
- [ ] 3.13 Response `Void` vẫn có `200` description rõ ràng; nếu cần có thể thêm example rỗng để FE/QA dễ đối chiếu
- [ ] 3.14 Error docs bám đúng business code/message thực tế của service, không mô tả chung chung
- [ ] 3.15 Style Swagger nhất quán trong cùng service, tham chiếu pattern `ExchangeRateOperation` và `RatingScoreRuleOperation`
- [ ] 3.16 Không bắt buộc generate `openapi.json` hoặc `openapi.yaml`; chỉ generate khi repo/service có convention hoặc downstream automation yêu cầu artifact này
- [ ] 3.17 Security config nếu cần
## 4. Tests
- [ ] 4.1 Unit test Service
- [ ] 4.2 Integration test Controller
- [ ] 4.3 Cover tất cả scenarios từ OpenSpec
- [ ] 4.4 Nếu có spec: cover thêm testcase/AC trong spec
## 5. Verify
- [ ] 5.1 ./mvnw clean package -DskipTests
- [ ] 5.2 ./mvnw test
- [ ] 5.3 Đảm bảo Swagger/OpenAPI annotations và `api-contract.md` phản ánh đúng behavior hiện tại để Phase 4 generate/update Postman collection; chỉ cần `openapi.json` / `openapi.yaml` nếu repo/service có convention hoặc downstream automation yêu cầu
- [ ] 5.4 Curl examples ở Phase 5
Thứ tự implement:
Types/Interfaces → API Service → Custom Hook → Component → Page integration
Conventions:
Ưu tiên follow structure và tooling đang có sẵn trong repo hiện tại, không ép một layout/framework convention nếu codebase đang theo pattern khác.
| Layer | Convention |
|---|---|
| Types | types/<feature>.ts hoặc vị trí tương đương trong repo — interfaces, enums |
| API | services/<feature>Api.ts hoặc module API tương đương — axios/fetch calls |
| Hook | hooks/use<Feature>.ts hoặc composable/module state tương đương |
| Component | components/<Feature>/index.tsx hoặc feature component tương đương — UI only |
| Page/Route | pages/<Page>.tsx, app/..., route module hoặc screen hiện có của repo |
| Style | Follow styling system hiện tại của repo (CSS modules, Tailwind, SCSS, design system), không trộn style mới nếu không cần |
Implementation task template FE:
tasks-fe.mdopenspec/.../tasks.md## 1. Foundation
- [ ] 1.1 Types / interfaces
- [ ] 1.2 API service function (gọi BE endpoint)
## 2. Business Logic
- [ ] 2.1 Custom hook (state, loading, error)
- [ ] 2.2 Data transformation / helpers
## 3. UI
- [ ] 3.1 Component markup + props
- [ ] 3.2 Styling
- [ ] 3.3 Error / loading states
- [ ] 3.4 Accessibility (aria labels, keyboard nav)
## 4. Integration
- [ ] 4.1 Tích hợp vào page/route/screen hiện có của repo
- [ ] 4.2 Routing nếu cần, follow router đang dùng trong project
## 5. Tests
- [ ] 5.1 Unit test hook/state logic
- [ ] 5.2 Component test (RTL hoặc framework tương đương theo repo)
- [ ] 5.3 E2E nếu là critical flow
- [ ] 5.4 Cover tất cả scenarios từ OpenSpec
- [ ] 5.5 Nếu có spec: cover thêm testcase/AC trong spec
## 6. Verify
- [ ] 6.1 Chạy test command hiện có của repo (`npm test`, `yarn test`, `pnpm test`, `vitest`, ...)
- [ ] 6.2 Chạy build command hiện có của repo (no errors)
- [ ] 6.3 Visual check trên browser
Build & Test:
# BE
# Chạy test/build command hiện có của repo (ví dụ: ./mvnw test, ./gradlew test, ./gradlew bootJar)
# FE
# Chạy test/build command hiện có của repo (ví dụ: npm test && npm run build, yarn test && yarn build, pnpm test && pnpm build)
OpenSpec Verify (chung, luôn chạy):
/opsx:verify <change-name>
Spec consistency check (nếu feature có spec):
api-contract.md / design-*.md / testcase.md có phản ánh thay đổi cuối cùng khôngtasks-be.md / tasks-fe.md đã được check hết và không lệch openspec/.../tasks.mdBackend API verification artifact (BE/API khi phù hợp):
api-contract.md / OpenAPI / Swagger docs phải khớp với collection vừa generateCollection / environment storage rule (BE/API):
postman/collections/<spec-name>.postman_collection.json<feature-review-scope> trước khi sang Phase 4; khi đó dùng tên như postman/collections/<feature-review-scope>.postman_collection.json và không dùng OpenSpec change name làm defaultreview scope nên bám theo consumer-facing API boundary ổn định như service module, bounded context, hoặc endpoint prefix; không đặt theo layer kỹ thuật nội bộ<feature-review-scope> là tên scope gốc khi không có spec; <scope> chỉ là hậu tố sub-scope dùng khi tách collection từ một spec đã có<spec-name>, <feature-review-scope>, và <scope> phải được normalize về lowercase kebab-case ASCII; dấu phân tách -- chỉ dùng để nối <spec-name> với <scope>postman/collections/<service>--<spec-name>.postman_collection.json, postman/collections/<service>--<spec-name>--<scope>.postman_collection.json, hoặc với non-spec case là postman/collections/<service>--<feature-review-scope>.postman_collection.json, trừ khi repo đã có convention khác<spec-name>postman/collections/<spec-name>--<scope>.postman_collection.json ngay cả khi repo chưa có convention sẵn; các <scope> này phải được nêu rõ trong Phase 1 tasks/review summarypostman/environments/<service>-<runtime-env>.postman_environment.json; nếu repo đã có convention env dùng chung thì follow convention đóCode Review (chọn đúng agent):
| Stack | Agent |
|---|---|
| Java general | Ưu tiên java-reviewer, nếu không có thì dùng code-reviewer |
| Java Spring | Ưu tiên java-reviewer, nếu không có thì dùng code-reviewer |
| Spring Boot BE | Ưu tiên java-reviewer, nếu không có thì dùng code-reviewer |
| React FE | Ưu tiên typescript-reviewer, nếu không có thì dùng code-reviewer |
| Vue FE | Ưu tiên typescript-reviewer, nếu không có thì dùng code-reviewer |
| Cả hai | Thử reviewer chuyên biệt song song; nếu reviewer nào không có thì thay bằng code-reviewer |
Fallback rule:
code-reviewerSecurity Review (chung — focus khác):
security-reviewer
Sau khi có kết quả review, DỪNG LẠI và trình bày tóm tắt cho user:
🔍 KẾT QUẢ REVIEW — <change-name>
**Build & Test:** ✅ PASS / ❌ FAIL
**OpenSpec Verify:** ✅ PASS / ❌ X scenarios fail
**Spec Consistency:** ✅ PASS / ❌ lệch spec (chỉ áp dụng nếu feature có spec)
**Postman Collection (BE/API nếu áp dụng):** ✅ generated/updated + smoke pass / ➖ not applicable / ❌ fail
**Reviewer Used:**
- Backend/API: `java-reviewer` / `code-reviewer`
- Frontend/UI: `typescript-reviewer` / `code-reviewer`
**Code Review Issues:**
- [CRITICAL] <file>: <mô tả> → đã fix / cần fix
- [HIGH] <file>: <mô tả> → đã fix / cần fix
- [MEDIUM] <file>: <mô tả> → đã fix / bỏ qua (lý do)
**Security Issues:**
- [CRITICAL/HIGH] <mô tả> → đã fix / cần fix
- Không có issues
**Thay đổi phát sinh sau review:**
- <file>: <thay đổi gì so với plan ban đầu>
- Nếu có spec: file spec nào đã sync thêm
---
Code đã ổn chưa? Có điểm nào cần chỉnh thêm không?
→ Trả lời "OK" hoặc "viết docs" để chuyển sang Phase 5
→ Hoặc nêu điểm cần chỉnh để fix thêm
Loop cho đến khi user approve:
# Happy path
curl -X GET "http://localhost:8080/api/..." \
-H "Authorization: Bearer <token>"
# Response: HTTP 200 { "success": true, "data": [...] }
# Error case
curl -X GET "http://localhost:8080/api/...?invalidParam=99" \
-H "Authorization: Bearer <token>"
# Response: HTTP 400 { "success": false, "message": "..." }
// Props interface
interface <Feature>Props {
onAction: (value: string) => void;
data: string[];
disabled?: boolean;
}
// Usage example
<FeatureComponent
data={items}
onAction={(val) => handleAction(val)}
/>
Sau khi viết xong docs, DỪNG LẠI và trình bày tóm tắt cho user:
📝 DOCS HOÀN THÀNH — <change-name>
**BE — curl examples:**
- Happy path: [tóm tắt endpoint + response]
- Error case: [tóm tắt error scenario]
**FE — Component usage:**
- Props: [liệt kê props chính]
- Usage example: [snippet ngắn]
**Checklist Done:**
- [ ] Tất cả Scenarios có test tương ứng
- [ ] Build + tests PASS
- [ ] /opsx:verify không fail
- [ ] Nếu có spec: spec files đã sync với code và OpenSpec
- [ ] Nếu BE/API có endpoint mới hoặc đổi API surface/behavior đã expose: Postman collection đã được update ở Phase 4 và smoke pass
- [ ] Không có CRITICAL/HIGH từ review
- [ ] Docs đã sinh
---
Mọi thứ đã ổn chưa? Sẵn sàng đóng issue và archive chưa?
→ Trả lời "OK" hoặc "close" để chuyển sang Phase 6 (Archive & Close)
→ Hoặc nêu điểm còn thiếu để bổ sung
Chỉ chuyển Phase 6 sau khi user confirm.
openspec archive "<change-name>"
bd close <bd-id>
bd ready --json --limit 5 # xem việc tiếp theo
Trước khi archive/close:
bd create "..." -t task -p 2 # capture
/opsx:ff <change-name> # fast-forward design
# implement + test
# BE: chạy test/build command hiện có của repo
# FE: chạy test/build command hiện có của repo
/opsx:verify <change-name> # vẫn bắt buộc trước archive
# BE: sinh curl examples tối thiểu nếu có API
# FE: sinh usage snippet tối thiểu nếu có UI/component mới
openspec archive <name> && bd close <id>
Fast track rules:
/opsx:verify, review phù hợp, và docs tối thiểu theo stack| Phase | BE (Spring Boot) | FE (React/Vue) |
|---|---|---|
| Test framework | JUnit 5 + MockMvc | Repo test runner (Jest/Vitest/...) + RTL/framework equivalent + E2E cho critical flows |
| Implement order | Entity→Repo→DTO→Service→Controller | Types→API→Hook→Component→Page |
| Code review agent | java-reviewer nếu environment có sẵn, fallback code-reviewer |
typescript-reviewer nếu environment có sẵn, fallback code-reviewer |
| Security focus | SQL injection, auth | XSS, data exposure |
| Docs / verify output | Postman verify artifact (Phase 4 nếu có endpoint mới hoặc đổi API surface/behavior đã expose) + curl examples (Phase 5) | Component props + usage |
| Build check | Chạy test/build command hiện có của repo | Chạy test/build command hiện có của repo |
[ ] Tất cả scenarios trong OpenSpec có test tương ứng
[ ] Nếu có spec: requirements / testcase / AC cũng có test tương ứng
[ ] Build + tests PASS
[ ] /opsx:verify không fail scenario nào
[ ] Nếu có spec: spec files đã sync với code và OpenSpec
[ ] Nếu BE/API có endpoint mới hoặc đổi API surface/behavior đã expose: Postman collection đã được update ở Phase 4 và smoke checks pass
[ ] Không có CRITICAL/HIGH từ code review
[ ] Không có security issues
[ ] Docs (curl hoặc component usage) đã sinh
[ ] tasks.md đã hoàn tất
[ ] Nếu có spec: tasks-be.md / tasks-fe.md cũng đã hoàn tất
[ ] Change đã archive
[ ] Beads issue đã close