1---
2name: refine
3description: '[Project Management] Use when converting ideas to PBIs, validating problem hypotheses, adding acceptance criteria, or refining requirements.'
4metadata:
5 source: https://skillmd.com/skills/duc01226/refine
6---
7
8> Codex compatibility note:
9>
10> - Invoke repository skills with `$skill-name` in Codex; this mirrored copy rewrites legacy Claude `/skill-name` references.
11> - Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
12> - User-question prompts mean to ask the user directly in Codex.
13> - Ignore Claude-specific mode-switch instructions when they appear.
14> - Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
15> - Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required `spawn_agent` subagent(s) for that task.
16> - Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
17> - For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
18> - If a required step/tool cannot run in this environment, stop and ask the user before adapting.
19
20<!-- CODEX:PROJECT-REFERENCE-LOADING:START -->
21
22## Codex Project-Reference Loading (No Hooks)
23
24Codex uses static project-reference loading instead of runtime-injected project docs.
25When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
26
27**Always read:**
28
29- `docs/project-config.json` (project-specific paths, commands, modules, and workflow/test settings)
30- `docs/project-reference/docs-index-reference.md` (routes to the full `docs/project-reference/*` catalog)
31- `docs/project-reference/lessons.md` (always-on guardrails and anti-patterns)
32
33**Missing/stale context route:** If `docs/project-config.json`, the docs index, `lessons.md`, `CLAUDE.md`, `AGENTS.md`, or any task-required reference doc is missing or stale, auto-run `$project-init` or the narrow setup route (`$project-config`, `$docs-init`, `$scan-all`, `$scan --target=<key>`, `$claude-md-init`) before ordinary project-specific work. If Codex mirrors or `AGENTS.md` are missing/stale, ask the user to run `$sync-codex`; do not auto-run it.
34
35**Situation-based docs:**
36
37- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra): `project-structure-reference.md`
38- Backend/CQRS/API/domain/entity changes: `backend-patterns-reference.md`, `domain-entities-reference.md`
39- Frontend/UI/styling/design-system: `frontend-patterns-reference.md`, `scss-styling-guide.md`, `design-system/README.md`
40- Spec authoring, `docs/specs/` pathing, or TC format: `feature-spec-reference.md`, `spec-system-reference.md`, `spec-principles.md`
41- Behavior/public-contract changes or spec-test-code sync: `workflow-spec-test-code-cycle-reference.md` plus the spec docs above
42- Derived spec indexes/ERDs/reimplementation guides: `spec-system-reference.md` and source Feature Specs under `docs/specs/`
43- Integration test implementation/review: `integration-test-reference.md`
44- E2E test implementation/review: `e2e-test-reference.md`
45- Code review/audit work: `code-review-rules.md` plus domain docs above based on changed files
46
47Do not read all docs blindly. Start from `docs-index-reference.md`, then open only relevant files for the task.
48
49<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->
50
51<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:START -->
52
53> **[BLOCKING]** Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.
54> **[BLOCKING]** Before each step or sub-skill call, update task tracking: set `in_progress` when step starts, set `completed` when step ends.
55> **[BLOCKING]** Every completed/skipped step MUST include brief evidence or explicit skip reason.
56> **[BLOCKING]** If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.
57
58<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->
59
60## Quick Summary
61
62**Goal:** Transform raw ideas into a Definition-of-Ready PBI using BA best practices, hypothesis validation, and domain research — problem-validated, tech-agnostic, with testable acceptance criteria, estimates, and a Dependencies table — so a team can build it without re-asking what or why.
63
64**Summary:**
65
66- **Purpose:** turn a raw idea into a groomable, Definition-of-Ready PBI a team can build without re-asking what or why.
67- **Main steps — run in order, track EACH (AI keeps forgetting sub-phases):** Phase 0 locate active plan → 1 idea intake + module detect → 2 domain research → 3 problem-hypothesis validation (GATE) → 4 BABOK elicitation → 5 BDD acceptance criteria → 5.1 AI-SDD M1-M5/M7 gate (BLOCKING) → 5.5 testability assessment → 6 prioritization + draft estimate → 7 validation interview (GATE, 3-5 Qs) → 7.5 RE-DERIVE estimate vs locked scope → 8 PBI artifact generation.
68- Two gates are NON-OPTIONAL: validate the problem hypothesis (Phase 3) before building, and run the 3-5 question validation interview (Phase 7) before writing the PBI — the user decides assumptions, scope, and dependencies, never the AI.
69- Acceptance criteria are BDD GIVEN/WHEN/THEN (min 3: happy/edge/error) and MUST satisfy the AI-SDD M1-M5 and M7 gate (Phase 5.1): tech-agnostic Business Intent, logical FR-/BR- IDs first, observable single-interpretation ACs, rebuild-from-scratch validity, and every AC demoable as a business outcome (M7).
70- Estimate twice: Phase 6 drafts story points/man-days against draft scope, then Phase 7.5 RE-DERIVES them against the locked post-interview scope (per SYNC:estimation-framework) — shipping stale Phase 6 numbers is the cardinal failure.
71- The PBI frontmatter MUST carry `story_points`, `complexity`, `man_days_traditional`, `man_days_ai`, and every PBI MUST include a complete Dependencies table (`must-before`/`can-parallel`/`blocked-by`/`independent`).
72
73**Workflow:**
74
75| Phase | Name | Key Activity | Output |
76| ----- | ------------------------- | ---------------------------------------- | ---------------------- |
77| 0 | Locate Active Plan | Load `plan.md` if in workflow | Plan context |
78| 1 | Idea Intake | Load artifact, detect module | Context loaded |
79| 2 | Domain Research | WebSearch market/competitors | Research summary |
80| 3 | Problem Hypothesis (GATE) | Validate problem exists | Confirmed hypothesis |
81| 4 | Elicitation | Apply BABOK techniques | Requirements extracted |
82| 5 | Acceptance Criteria | Write BDD scenarios | GIVEN/WHEN/THEN |
83| 5.1 | AI-SDD Gate (M1-M5/M7) | Tech-agnostic, FR/BR IDs first, demoable | Mandate-compliant ACs |
84| 5.5 | Testability | Test approach + per-AC outlines | Test seed for `$spec` |
85| 6 | Prioritization | RICE/MoSCoW + DRAFT Story Points | Priority + draft est. |
86| 7 | Validation (GATE) | Interview user (MANDATORY, 3-5Q) | Assumptions confirmed |
87| 7.5 | Re-estimate | RE-DERIVE vs LOCKED scope | Final estimate |
88| 8 | PBI Generation | Create artifact | PBI file saved |
89
90**Key Rules:**
91
92- NEVER skip hypothesis validation for new features
93- Validation interview NOT optional — always ask 3-5 questions
94- Use project domain-specific vocabulary when available
95- MUST ATTENTION include `story_points`, `complexity`, `man_days_traditional`, `man_days_ai` in PBI frontmatter
96- Every PBI MUST ATTENTION include Dependencies table — types: `must-before` | `can-parallel` | `blocked-by` | `independent`
97- `docs/specs/` — read existing TCs for related features; recommend test spec generation for new PBIs
98- `docs/project-reference/domain-entities-reference.md` — read when task involves business entities/models
99
100---
101
102## Frontend/UI Context (if applicable)
103
104- Component patterns: `docs/project-reference/frontend-patterns-reference.md`
105- Styling/BEM guide: `docs/project-reference/scss-styling-guide.md`
106- Design system tokens: `docs/project-reference/design-system/README.md`
107
108---
109
110## Greenfield Mode
111
112> **Auto-detected:** No discovered source directories and no manifest files found. Planning artifacts (docs/, plans/, .claude/) don't count.
113
114**When greenfield detected:**
115
1161. Skip existing backlog refinement (no backlog exists)
1172. Enable DDD domain modeling: bounded contexts, aggregates, entities, value objects
1183. Capture constraints: team skills, expected scale, hosting preferences, budget — as input signals only
1194. Use WebSearch for market research + competitor analysis
1205. Output domain model artifact alongside PBI artifact
1216. Increase ask the user directly frequency — validate domain boundaries, entity relationships, business rules
1227. **[CRITICAL] NEVER ask about tech stack during refinement.** Tech stack decided after business analysis. Capture team skills + scale expectations as signals only.
123
124**Be skeptical. Every claim needs traced proof, confidence >80%.**
125
126---
127
128## Phase 0: Locate Active Plan (if in workflow)
129
130If running in workflow (big-feature, greenfield-init, etc.):
131
1321. Glob `plans/*/plan.md` sorted by modification time, or check the current task list for plan context
1332. Read `plan.md` — project scope, goals, architecture decisions, domain model
1343. Read existing research — `{plan-dir}/research/*.md` for business evaluation, domain analysis
1354. Read `docs/project-reference/domain-entities-reference.md` (if exists) — existing domain entities
1365. Use plan context — don't re-ask questions answered in prior steps
137
138## Phase 1: Idea Intake & Context Loading
139
1401. Read idea artifact from path or find by ID in `team-artifacts/ideas/`
1412. Extract: problem statement, value proposition, target users, scope
1423. Check `module` field; if absent, detect via keywords or prompt user
143
144---
145
146## Phase 2: Domain Research
147
148**Trigger:** New domain, unclear competitors, `--research` flag.
149**Skip:** Internal tooling, well-understood domain, time-constrained.
150
151Use WebSearch with domain terms. Summarize in max 3 bullets (market context, competitors, best practices).
152
153---
154
155## Phase 3: Problem Hypothesis Validation
156
157Validate hypothesis with user by asking the user directly. 42% of startups fail from no market need — validate before building.
158
159**Skip:** `--skip-hypothesis`, validated hypothesis exists, bug fix/tech debt.
160
161### Problem Hypothesis Template
162
163```markdown
164**We believe** [target users/persona]
165**Experience** [specific problem]
166**Because** [root cause]
167**We'll know this is true when** [validation metric/evidence]
168```
169
170### Value Hypothesis Template
171
172```markdown
173**We believe** [feature/solution]
174**Will deliver** [value/benefit]
175**To** [target users]
176**We'll know we're right when** [success metric]
177```
178
179### Validation Process
180
1811. Draft hypothesis from idea content
1822. Use ask the user directly to validate:
183 - "Is this the core problem we're solving?"
184 - "Who exactly experiences this? How often?"
185 - "What evidence do we have this problem exists?"
1863. Validated → proceed to elicitation
1874. Invalidated → return idea for clarification
188
189---
190
191## Phase 4: Requirements Elicitation (BABOK Core 5)
192
193**Think:** What information gaps exist? Which technique fills them with least effort + highest confidence?
194
195| Technique | When to Choose | What to Extract |
196| --------------------- | --------------------------------------------------- | ----------------------------------------------- |
197| **Interviews** | Deep insights needed, stakeholder perspectives vary | Stakeholder needs, pain points, constraints |
198| **Workshops** | Group consensus needed, multiple stakeholders | Prioritized requirements, consensus decisions |
199| **Document Analysis** | Existing systems/processes, regulatory requirements | As-is state, compliance requirements, gaps |
200| **Observation** | Users can't articulate needs, workflow unclear | Actual vs stated workflow, hidden requirements |
201| **Prototyping** | Visual validation needed, UI/UX requirements vague | Validated UI requirements, interaction patterns |
202
203**Technique notes:**
204
205- Interviews: Open-ended questions (why, how, what-if) → active listening → follow-up on unexpected → document verbatim quotes
206- Workshops: Define agenda + 90 min timebox → neutral facilitator → round-robin/silent voting → document decisions AND dissent
207- Observation: Shadow users → note workarounds/pain points → don't interrupt → ask clarifying questions afterward
208
209---
210
211## Phase 5: Acceptance Criteria (BDD Format)
212
213Write GIVEN/WHEN/THEN scenarios. Minimum 3: happy path, edge case, error case.
214
215```gherkin
216Scenario: {Descriptive title}
217 Given {precondition/context}
218 And {additional context}
219 When {action/trigger}
220 And {additional action}
221 Then {expected outcome}
222 And {additional verification}
223```
224
225| Practice | Rule |
226| ------------------------- | --------------------------------- |
227| Single trigger | "When" clause has ONE action |
228| 3 scenarios minimum | Happy path, edge case, error case |
229| No implementation details | Behavior, not how |
230| Testable outcomes | "Then" must be verifiable |
231| Stakeholder language | No technical jargon |
232
233### Example Scenarios
234
235```gherkin
236Scenario: User creates invoice with valid data
237 Given user has permission to create invoices
238 And user is on the invoice creation page
239 When user submits invoice form with all required fields
240 Then invoice is created with status "Draft"
241 And invoice appears in user's invoice list
242
243Scenario: Invoice creation fails with missing required field
244 Given user is on the invoice creation page
245 When user submits form without title
246 Then validation error "Title is required" is displayed
247 And invoice is not created
248
249Scenario: Approver reviews a submitted invoice
250 Given approver has invoices awaiting approval
251 And an invoice has been submitted for approval
252 When approver opens the invoice review page
253 Then the invoice is visible with "Pending Review" status
254```
255
256### Project Test Case Format
257
258- **Format:** `TC-{FEATURE}-{NNN}` (e.g., TC-GM-001)
259- **Evidence:** `[Source: namespace/service/id]` abstract-anchor format (never `file:line`)
260- See `business-analyst` skill for detailed patterns
261
262---
263
264### Phase 5.1: AI-SDD Mandate Gate (M1-M5 and M7) — BLOCKING
265
266See `.claude/skills/shared/sdd-artifact-contract.md` → "AI-SDD Mandates (M1-M7)" for BLOCKING criteria. The generated PBI MUST satisfy M1-M5 and M7 or be reworked before Phase 8 writes it:
267
268- **Separate intent from implementation (M1/M2):** Keep a tech-agnostic **Business Intent** narrative (Description, Business Value, Acceptance Criteria) free of framework/product/language/design-pattern names and source identifiers. Put any optional implementation hints in a clearly separated **Implementation Notes** block, and put source references only in evidence carriers (`[Source: namespace/service/id]`, `**Evidence**`). Prose stays tech-agnostic per `docs/project-reference/spec-principles.md` §3.
269- **Logical Requirement ID first (M3):** Assign each requirement a logical ID (`FR-`/`BR-`) as the PRIMARY citation spine; keep `[Source: namespace/service/id]` abstract-anchor evidence (never physical code coordinates or repository-root paths — those live only in the provenance sidecar) as a SECONDARY carrier in a separate evidence column/section — KEEP it, never remove it.
270- **Testable, observable acceptance criteria (M4):** Every acceptance criterion has ONE valid interpretation, observable completion states, named failure modes, and NO implementation details. Reject vague phrasing ("handle appropriately", "fast", "user-friendly").
271- **Rebuild-from-scratch validation (M5):** Before emitting, confirm a competent team with zero codebase knowledge could re-implement identical business behavior on ANY stack from the PBI alone. If a reader would have to guess a rule, limit, role, or failure mode, add it as a clarification — never guess.
272- **Business-visibility (M7):** Apply the demo test to each acceptance criterion's BODY: _"what would a stakeholder SEE change?"_ — no answer → FAIL as TECHNICAL-ONLY and drop it from the PBI. Every `GIVEN` = a state a user could arrange; every `WHEN` = an action a user could take; every `THEN` = an outcome a user could see. FAIL a `WHEN` that is an invocation (a handler runs, a consumer receives, a job fires, data syncs) or a `THEN` asserting schema/type/nullability/call-count. Judge the BODY, never the AC's title or ID. Never derive the AC count from an architecture inventory (handlers, consumers, jobs) — that count moves when the system is re-architected though no business behavior changed, falsifying M5.
273
274> **M1 governs vocabulary; M7 governs subject matter.** A technical AC in impeccably tech-free prose satisfies M1 while violating M7 — _"the system correctly synchronizes the record"_ names no framework and is still a technical case in a business costume. That gap is the most common way business specs rot. Ask what a user could SEE, not which words were used.
275
276---
277
278### Phase 5.5: Testability Assessment
279
280Use ask the user directly with 2-3 questions:
281
2821. "Which testing approach fits this PBI?"
283 - TDD-first: Write test specs before implementation (Recommended for complex features)
284 - Implement-first: Build feature, then create test specs
285 - Parallel: Spec and implement simultaneously
286
2872. "What test levels are needed?"
288 - Integration tests only (Recommended for backend CQRS)
289 - Integration + E2E
290 - Unit + Integration + E2E
291
292For EACH acceptance criterion, generate corresponding test case outline:
293
294| AC | Test Outline | Priority |
295| ---- | ---------------------------------------------------------- | -------- |
296| AC-1 | TC: Create invoice with valid data → verify persisted | P0 |
297| AC-2 | TC: Create invoice without title → verify validation error | P1 |
298
299Seed for `$spec [mode=tests]` if user chooses TDD-first. Document in PBI under `## Testability Assessment`.
300
301---
302
303## Phase 6: Prioritization & Estimation
304
305Apply RICE score or MoSCoW for priority. Estimate using **Story Points (Modified Fibonacci 1-21)**.
306
307### Quick RICE Score
308
309```
310Score = (Reach x Impact x Confidence) / Effort
311
312Reach: Users affected per quarter (100, 500, 1000+)
313Impact: 0.25 (minimal) | 0.5 (low) | 1 (medium) | 2 (high) | 3 (massive)
314Confidence: 0.5 (low) | 0.8 (medium) | 1.0 (high)
315Effort: Story points (1, 2, 3, 5, 8, 13, 21)
316```
317
318### MoSCoW Categories
319
320| Category | Meaning | Action |
321| --------------- | ------------------------ | ------------------- |
322| **Must Have** | Critical, non-negotiable | Include in MVP |
323| **Should Have** | Important but not vital | Plan for release |
324| **Could Have** | Nice to have, low effort | If time permits |
325| **Won't Have** | Out of scope this cycle | Document for future |
326
327---
328
329## Phase 7: Validation Interview (MANDATORY)
330
331Generate 3-5 questions covering assumptions, scope, dependencies, edge cases. Use ask the user directly. Document in PBI. **NOT optional.**
332
333| Category | Example Question |
334| ------------------- | --------------------------------------------------------------------------- |
335| **Assumptions** | "We assume X is true. Correct?" |
336| **Scope** | "Should Y be included or explicitly excluded?" |
337| **Dependencies** | "This requires Z. Is that available?" |
338| **Edge Cases** | "What happens when data is empty/null?" |
339| **Business Impact** | "Will this affect existing reports/workflows?" |
340| **Entities** | "Create new entity or extend existing X?" |
341| **Prod Readiness** | "Does this feature need linting, error handling, loading, or Docker setup?" |
342| **Authorization** | "Who can perform this action? What roles/permissions are needed?" |
343| **Seed Data** | "Does this feature need reference/lookup data to function?" |
344| **Data Migration** | "Does this change entity schema? Is data transformation needed?" |
345
3461. Generate 3-5 questions from assumptions, scope, dependencies
3472. Use ask the user directly to interview
3483. Document in PBI under `## Validation Summary`
3494. Update PBI based on answers
350
351### Validation Output Format
352
353```markdown
354## Validation Summary
355
356**Validated:** {date}
357
358### Confirmed Decisions
359
360- {decision}: {user choice}
361
362### Assumptions Confirmed
363
364- {assumption}: Confirmed/Modified
365
366### Open Items
367
368- [ ] {follow-up items}
369```
370
371---
372
373## Cross-Cutting & Production Readiness
374
375> Capture in PBI template sections: Production Readiness Concerns, Authorization & Access Control, Seed Data, Data Migration.
376
377---
378
379## Phase 7.5: Re-evaluate Estimation (MANDATORY — runs after Validation Interview)
380
381> **Why this phase exists:** Phase 6 estimation runs against a draft scope. Phase 7 (Validation Interview) and Cross-Cutting capture often resolve unknowns, add constraints, or trim/expand scope. The numbers in `story_points`, `complexity`, `man_days_traditional`, `man_days_ai` MUST be re-derived against the locked scope BEFORE Phase 8 writes them into the PBI frontmatter. Estimating once at draft and forgetting is the #1 source of estimation drift in PBIs.
382
383### Inputs (locked by end of Phase 7)
384
385- Confirmed assumptions, scope inclusions/exclusions
386- Authorization, seed data, migration, prod-readiness decisions
387- Newly discovered dependencies or edge cases
388- Any rescoping the user requested during validation
389
390### Re-derive (per `SYNC:estimation-framework`)
391
3921. Walk the **locked** scope acceptance criteria + cross-cutting concerns; assign hours per slice.
3932. `bottom_up_hours = Σ slice_hours` (use the SP table mapping in Phase 6, not eyeballing).
3943. `likely_days = ceil(bottom_up_hours / 6)` × productivity factor for the team/AI mode.
3954. Recompute `risk_margin_pct` based on remaining unknowns AFTER Phase 7 (margin should usually shrink because validation removed unknowns; rises only if new risks surfaced).
3965. Recompute `min-max range` from the new likely_days ± margin.
3976. Re-pick the closest Fibonacci `story_points` and `complexity` bucket from the re-derived likely_days.
398
399### Compare against Phase 6 draft estimate
400
401Compute `delta_pct = (new_likely_days - draft_likely_days) / draft_likely_days × 100`.
402
403| Delta | Action |
404| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
405| `\|delta\| ≤ 20%` | Keep draft estimate. Note `reestimate_delta_pct: <signed>` + `reestimate_reason: "within tolerance, no change"` in PBI frontmatter for transparency. |
406| `\|delta\| > 20%` | UPDATE `story_points`, `complexity`, `man_days_traditional`, `man_days_ai`. Add `reestimate_delta_pct: <signed>` + 1-line `reestimate_reason` explaining what changed (e.g., "auth scope confirmed wider", "seed data dropped per validation"). |
407| `\|delta\| > 50%` | UPDATE values AND flag `SHOULD-RESCOPE`. Surface to user by asking the user directly BEFORE Phase 8 writes the PBI: "Re-estimate is +/-X% vs original. Options: (a) accept new estimate as-is, (b) split into 2 PBIs, (c) trim scope back to original estimate, (d) defer." Record the user's decision in `## Validation Summary`. |
408
409### Output
410
411- Updated estimation values (carry into Phase 8 frontmatter)
412- New frontmatter fields: `reestimate_delta_pct`, `reestimate_reason` (always populate even when within tolerance — creates a paper trail for retrospective comparison against actual implementation time)
413- If rescoped: updated acceptance criteria/scope sections reflecting the user's choice
414
415> **Run this re-estimation phase against the locked scope — never skip it.** A PBI that ships with stale Phase 6 estimates is the source of unreliable velocity data. The whole point is to make the post-validation numbers — not the pre-validation guesses — the ones the team commits to.
416
417---
418
419## Phase 8: PBI Artifact Generation
420
421**Path:** `team-artifacts/pbis/{YYMMDD}-pbi-{slug}.md` | **ID Pattern:** `PBI-{YYMMDD}-{NNN}`
422
423> **Artifact Path (canonical convention)** — Command `$refine` → base path `team-artifacts/pbis/`, role token `ba`, type `pbi`. General filename pattern: `{YYMMDD}-{role}-{type}-{slug}.md` → e.g. `260119-ba-pbi-invoice-approval.md`. Slug = lowercased basename, non-alphanumeric → `-`, trimmed, max 50 chars.
424
425### PBI Template
426
427```markdown
428---
429id: PBI-{YYMMDD}-{NNN}
430title: '{Brief descriptive title}'
431module: '{ModuleName — detect from project-config.json modules[]}'
432priority: Must Have | Should Have | Could Have | Won't Have
433rank: { numeric 1-999, ascending — populated/updated by $prioritize during cross-PBI ranking; omit until prioritized }
434story_points: 1 | 2 | 3 | 5 | 8 | 13 | 21
435complexity: Low | Medium | High | Very High
436man_days_traditional: '{ Xd (Yd code + Zd test) — from SP table }'
437man_days_ai: '{ Xd (Yd code + Zd test) — from SP table with AI }'
438status: draft | refined | ready | in_progress | done
439rice_score: { calculated }
440created: '{YYYY-MM-DD}'
441source_idea: '{idea artifact path or ID}'
442---
443
444# {PBI Title}
445
446> **Business Intent (tech-agnostic — M1/M2):** Description, Business Value, Business Rules, and Acceptance Criteria below describe observable business behavior only — no framework/product/language/design-pattern names, no source identifiers. Keep implementation hints in `## Implementation Notes` and source references in evidence carriers.
447
448## Requirement IDs (M3 — logical-IDs-first)
449
450| Logical ID | Statement (tech-agnostic) | Evidence (secondary, re-anchorable) |
451| ------------ | ------------------------- | ----------------------------------------- |
452| FR-{MOD}-XXX | {functional requirement} | `[Source: path:line]` or `TBD (pre-impl)` |
453| BR-{MOD}-XXX | {business rule} | `[Source: path:line]` or `TBD (pre-impl)` |
454
455## Description
456
457**As a** {user role}
458**I want** {capability}
459**So that** {business value}
460
461## Business Value
462
463- {Quantified benefit 1}
464- {Quantified benefit 2}
465
466## Problem Hypothesis
467
468**We believe** {target users}
469**Experience** {specific problem}
470**Because** {root cause}
471**We'll know this is true when** {validation metric}
472
473## Business Rules
474
475- BR-{MOD}-XXX: {Rule description}
476
477## Acceptance Criteria
478
479### AC-1: {Title}
480
481Scenario: {Happy path}
482Given {context}
483When {action}
484Then {outcome}
485
486### AC-2: {Title}
487
488Scenario: {Edge case}
489Given {edge state}
490When {action}
491Then {handling}
492
493### AC-3: {Title}
494
495Scenario: {Error case}
496Given {context}
497When {invalid action}
498Then error "{message}"
499
500## Testability Assessment
501
502| AC | Test Outline | Priority |
503| ---- | ------------------ | -------- |
504| AC-1 | {test description} | P0 |
505| AC-2 | {test description} | P1 |
506
507## Out of Scope
508
509- {Explicitly excluded item 1}
510- {Explicitly excluded item 2}
511
512## Dependencies
513
514| Dependency | Type | Description |
515| --------------------- | ------------ | ------------------------------ |
516| {PBI/service/feature} | must-before | {Why this must be done first} |
517| {PBI/service/feature} | can-parallel | {Why this can run in parallel} |
518| {PBI/service/feature} | blocked-by | {What blocks this PBI} |
519| - | independent | {No dependencies — first item} |
520
521## Production Readiness Concerns
522
523| Concern | Required | Notes |
524| ---------------------- | --------------- | ----------------------------------------------------------------------- |
525| Code linting/analyzers | Yes/No/Existing | {tool preference or "scaffold default"} |
526| Error handling setup | Yes/No/Existing | {pattern: toast/inline/error-page} |
527| Loading indicators | Yes/No/Existing | {pattern: spinner/skeleton/progress} |
528| Docker integration | Yes/No/Existing | {scope: infra-only/full/none} |
529| CI/CD quality gates | Yes/No/Existing | {mutation-score gate (line-coverage diagnostic only), lint enforcement} |
530| Security scanning | Yes/No/Existing | {dependency audit, SAST} |
531
532## Authorization & Access Control
533
534| Role | Can Create | Can Read | Can Update | Can Delete | Notes |
535| ------ | ---------- | -------- | ---------- | ---------- | ------------- |
536| {Role} | ✅/❌ | ✅/❌ | ✅/❌ | ✅/❌ | {scope notes} |
537
538**New permissions needed:** {Yes/No — list if yes}
539**Multi-tenant isolation:** {Yes/No}
540
541## Seed Data Requirements
542
543| Data Type | Description | Owner | Required |
544| ------------------ | ------------------------------------ | ------------ | -------- |
545| Reference data | {lookups, statuses, types} | Application | Yes/No |
546| Configuration data | {default settings} | Application | Yes/No |
547| Test seed data | {entities for integration tests} | Test project | Yes/No |
548| Performance data | {large-volume data for load testing} | Test tooling | Yes/No |
549
550> If no seed data needed: `N/A — no seed data required for this feature.`
551
552## Data Migration
553
554| Change | Type | Backward Compatible | Reversible |
555| --------------------------- | -------------------------------------- | ------------------- | ---------- |
556| {schema change description} | Add field / Remove field / Type change | Yes/No | Yes/No |
557
558> If no schema changes: `N/A — no schema changes required.`
559
560## Domain Context
561
562**Entities:** {Entity1}, {Entity2}
563**Related Features:** {feature doc paths}
564
565## Implementation Notes
566
567> Optional, clearly separated from Business Intent. Implementation hints / source identifiers may appear here and in evidence carriers only — never in the tech-agnostic sections above. If none: `N/A — no implementation hints; rebuild from Business Intent + Requirement IDs.`
568
569## UI Layout
570
571**Design Spec:** {link to the `$design-spec` artifact — or inline UI specs ref — that owns this PBI's screen/component design. REQUIRED for any PBI with UI work. Produce it AFTER inventorying existing UI + connected flows (per `SYNC:existing-ui-research`) so it faithfully matches the current UI system. If backend-only: `N/A — Backend-only change. No UI affected.`}
572
573### Wireframe
574
575{ASCII wireframe using box-drawing characters}
576
577**Layout:** {description with approximate proportions/dimensions}
578
579### Components
580
581- **{ComponentName}** — {behavior description} _(tier: common | domain-shared | page/app)_
582
583> Classify per **Component Hierarchy** in UI wireframe protocol — search existing libs before proposing new components.
584
585### States
586
587| State | Behavior |
588| ------- | -------------------------- |
589| Default | {what user sees initially} |
590| Loading | {spinner/skeleton} |
591| Empty | {empty state message} |
592| Error | {error handling} |
593
594> If backend-only: `## UI Layout` → `N/A — Backend-only change. No UI affected.`
595
596## Validation Summary
597
598**Validated:** {date}
599
600### Confirmed Decisions
601
602- {decision}: {user choice}
603
604### Assumptions Confirmed
605
606- {assumption}: Confirmed/Modified
607
608### Open Items
609
610- [ ] {follow-up items}
611```
612
613---
614
615## Anti-Patterns to Avoid
616
617| Anti-Pattern | Better Approach |
618| ------------------------------ | ----------------------------------- |
619| Refining vague ideas | Return to `$idea` for clarification |
620| Skipping hypothesis validation | Always run Phase 3 for new features |
621| Solution-first thinking | Start with problem, not solution |
622| Generic acceptance criteria | Use GIVEN/WHEN/THEN with specifics |
623| Ignoring domain context | Load project docs if applicable |
624| Too large PBI (XL+) | Break into smaller items |
625| Missing "Out of Scope" | Explicitly list exclusions |
626| Assuming instead of asking | Run validation interview |
627
628---
629
630## Key Rules
631
632- **Every PBI MUST ATTENTION include Dependencies table** — types: `must-before`, `can-parallel`, `blocked-by`, `independent`. Enables `$prioritize` and `$plan` to respect ordering.
633- **No vague dependency descriptions** — Each dependency must specify concrete PBI, service, or feature and WHY relationship exists.
634
635## BA Team Refinement Context (canonical)
636
637> Applies to Writes/Edits under `team-artifacts/pbis/`, `.../stories/`, `team-artifacts/ideas/`. Mirrored for Codex via `SYNC:ba-team-decision-model` / `SYNC:refinement-dor-checklist` in AGENTS.md (do not hand-edit the mirror).
638
639**Decision Model:** 2/3 majority vote (UX BA + Designer BA + Dev BA PIC). Dev BA PIC has technical veto.
640**Disagree-and-Commit:** Once decided, everyone commits. No re-litigating.
641**Grooming Override:** BA team decision changes only if >75% remaining team votes to override.
642
643**Role Scopes:**
644
645- **UX BA:** UI/UX flows, wireframes, interaction AC, user research
646- **Designer BA:** Design feasibility, product thinking, visual design, equal vote
647- **Dev BA PIC:** Technical feasibility review, AI pre-review, DoR gate, grooming presentation
648
649**DoR Gate (ALL must pass before grooming):**
650
651- [ ] User story template (As a... I want... So that...)
652- [ ] AC testable (GIVEN/WHEN/THEN, no vague language)
653- [ ] Wireframes attached (UX BA) + UI design ready (Designer BA)
654- [ ] (UI PBIs) Design spec linked — `$design-spec` artifact or inline UI specs present in `## UI Layout`; backend-only PBIs exempt (`N/A — Backend-only`)
655- [ ] AI pre-review passed (`$artifact-review --type=pbi` or `$pbi-challenge`)
656- [ ] Story points estimated by AI
657- [ ] Dependencies table complete
658
659**Refinement Cadence:** Always one sprint ahead. Weekly meeting (60 min + ~3h async).
660**Skills:** Use `$pbi-challenge` for collaborative review, `$dor-gate` before grooming.
661
662## Definition of Ready (INVEST)
663
664| Criterion | Check |
665| ------------------- | ---------------------------- |
666| **I**ndependent | No blocking dependencies |
667| **N**egotiable | Details can be refined |
668| **V**aluable | Clear user/business value |
669| **E**stimable | Team can estimate (XS-XL) |
670| **S**mall | Single sprint |
671| **T**estable | 3+ GIVEN/WHEN/THEN scenarios |
672| Problem Validated | Hypothesis confirmed |
673| Domain Context | BR/entity context loaded |
674| Stakeholder Aligned | Validation interview done |
675| Prod Readiness | Concerns documented |
676
677---
678
679## Project Integration
680
681For domain PBIs: detect module from `docs/specs/` directory names, extract business rules from `docs/specs/{module}/`, load entity context from feature doc. Target 8-12K tokens for feature context.
682
683---
684
685## Related
686
687- **Role Skill:** `business-analyst` (detailed patterns)
688- **Input:** `$idea` output
689- **Next Step:** `$story`, `$spec [mode=tests]` (Recommended for TDD), `$design-spec`
690- **Prioritization:** `$prioritize`
691
692---
693
694## Next Steps
695
696**MANDATORY IMPORTANT MUST ATTENTION** after completing this skill, use ask the user directly to present these options. NEVER skip because task seems "simple" or "obvious":
697
698- **"$why-review (Recommended)"** — Validate design rationale, alternatives, risk assessment before `$story` or implementation
699- **"$domain-analysis"** — If PBI creates/modifies domain entities, model bounded contexts before writing stories
700- **"$story"** — Break PBI into implementable user stories
701- **"$pbi-mockup"** — Generate HTML mockup from PBI
702- **"$spec [mode=tests]"** — If using TDD approach
703- **"Skip, continue manually"** — user decides
704
705---
706
707> **[IMPORTANT]** Use task tracking to break ALL work into small tasks BEFORE starting. Simple tasks: ask user whether to skip.
708
709> **External Memory:** Complex/lengthy work → write findings to `plans/reports/` — prevents context loss.
710
711> **Evidence Gate:** MANDATORY IMPORTANT MUST ATTENTION — every claim requires `file:line` proof or traced evidence, confidence >80% to act.
712
713<!-- SYNC:ai-mistake-prevention -->
714
715> **AI Mistake Prevention** — Failure modes to avoid on every task:
716>
717> **Re-read files after context changes.** Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
718> **Verify generated content against source evidence.** AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
719> **Check downstream references before deleting or renaming.** Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
720> **Trace the full impact chain after edits.** Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
721> **Verify ALL affected outputs, not just the first.** One green check is not all green checks; validate every output surface the change can affect.
722> **Assume existing values are intentional — ask WHY before changing OR flagging one as a defect.** Before changing or reporting a constant, limit, flag, cutoff, wording, or pattern, read nearby context and history, the CALLER's ordering, and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard.
723> **Surface ambiguity before acting — don't pick silently.** Multiple valid interpretations require an explicit question or stated assumption with risk.
724> **Assert the outcome your system owns, not the intermediate state your infrastructure owns.** When verifying async work, assert the final business state — never the delivery/retry bookkeeping held in shared infrastructure that any co-running process can write. Such a check passes when run alone and flakes the moment anything else shares that infrastructure.
725> **Keep shared guidance role-relevant.** Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
726
727<!-- /SYNC:ai-mistake-prevention -->
728
729<!-- SYNC:ui-system-context -->
730
731> **UI System Context** — For ANY task touching `.ts`, `.html`, `.scss`, or `.css` files:
732>
733> **MUST ATTENTION READ before implementing:**
734>
735> 1. `docs/project-reference/frontend-patterns-reference.md` — component base classes, stores, forms
736> 2. `docs/project-reference/scss-styling-guide.md` — BEM methodology, SCSS variables, mixins, responsive
737> 3. `docs/project-reference/design-system/README.md` — design tokens, component inventory, icons
738>
739> Reference `docs/project-config.json` for project-specific paths.
740
741<!-- /SYNC:ui-system-context -->
742
743<!-- SYNC:estimation-framework -->
744
745> **Estimation Framework** — Bottom-up first; SP DERIVED; output min-max range when likely ≥3d. Stack-agnostic. Baseline: 3-5yr dev, 6 productive hrs/day. AI estimate assumes Claude Code + project context.
746>
747> **Method:**
748>
749> 1. **Blast Radius pass** (below) — drives code AND test cost
750> 2. Decompose phases → hours/phase → `bottom_up_hours = Σ phase_hours`
751> 3. `likely_days = ceil(bottom_up_hours / 6) × productivity_factor`
752> 4. Sum **Risk Margin** (base + add-ons) → `max_days = likely_days × (1 + margin)`
753> 5. `min_days = likely_days × 0.9`
754> 6. Output as range when `likely_days ≥3`; single point allowed `<3` (still record margin)
755> 7. `man_days_ai` = same range × AI speedup
756> 8. `story_points` DERIVED from `likely_days` via SP-Days — NEVER driver. Disagreement >50% → trust bottom-up
757>
758> **Productivity factor:** 0.8 strong scaffolding+codegen+AI hooks · 1.0 mature default · 1.2 weak patterns · 1.5 greenfield
759>
760> **Cost Driver Heuristic (apply BEFORE work-type row):**
761>
762> - **UI dominates** in CRUD/business apps — 1.5-3x backend (states, validation, responsive, a11y, polish)
763> - **Backend dominates ONLY:** multi-aggregate invariants, cross-service contracts, schema migrations, heavy query/perf, new event flows
764>
765> **Reuse-vs-Create axis (PRIMARY lever, per layer):**
766>
767> | UI tier | Cost |
768> | -------------------------------------------- | -------- |
769> | Reuse component on existing screen | 0.1-0.3d |
770> | Add control/column to existing screen | 0.3-0.8d |
771> | Compose components into NEW screen | 1-2d |
772> | NEW screen, custom layout/states/validation | 2-4d |
773> | NEW shared/common component (themed, tested) | 3-6d+ |
774>
775> | Backend tier | Cost |
776> | ---------------------------------------------------- | --------- |
777> | Reuse query/handler from new place | 0.1-0.3d |
778> | Small update existing handler/entity | 0.3-0.8d |
779> | NEW query on existing repo/model | 0.5-1d |
780> | NEW command/handler on existing aggregate (additive) | 1-2d |
781> | NEW aggregate/entity (repo, validation, events) | 2-4d |
782> | NEW cross-service contract OR schema migration | 2-4d each |
783> | Multi-aggregate invariant / heavy domain rule | 3-5d |
784>
785> **Rule:** Sum tiers across UI+backend+tests, apply productivity factor. Reuse short-circuits tiers — call out.
786>
787> **Test-Scope drivers (compute test_count EXPLICITLY — "+tests" hand-wave is #1 failure):**
788>
789> | Driver | Count |
790> | --------------------------------- | ------------------------------------------------------ |
791> | Happy-path journeys | 1 per story / AC main flow |
792> | State-machine transitions | reachable transitions × allowed actors |
793> | Multi-entity state combos | state(A) × state(B) — REACHABLE only, not Cartesian |
794> | Authorization matrix | (owner, non-owner, elevated, unauth) × each mutation |
795> | Validation rules | 1 per required field / boundary / format / cross-field |
796> | UI states (per new screen/dialog) | happy, loading, empty, error, partial — present only |
797> | Negative paths / invariants | 1 per violatable business rule |
798>
799> | Test tier (Trad, incl. setup+assert+flake) | Cost |
800> | ------------------------------------------ | -------- |
801> | 1-5 cases, fixtures reused | 0.3-0.5d |
802> | 6-12 cases, 1 new fixture | 0.5-1d |
803> | 13-25 cases, multi-entity setup | 1-2d |
804> | 26-50 cases OR new state-machine coverage | 2-3d |
805> | >50 cases OR full E2E journey | 3-5d |
806>
807> **Test multipliers:** new fixture/seed harness +0.5d · cross-service/bus assertion +0.3d each · UI E2E ×1.5 · each new role +1-2 cases
808>
809> **Blast Radius (mandatory pre-pass — affects code AND test):**
810>
811> 1. Files/components directly modified — count
812> 2. Of those, "complex" (>500 LOC, multi-handler, central, frequently-modified) — count
813> 3. Downstream consumers (callers, event subscribers, cross-service) — list
814> 4. Shared/common code touched (multi-app blast) — yes/no
815> 5. Regression scope — areas needing re-test
816>
817> **Rule:** Complex touch → add `risk_factors`. Each downstream consumer → +1-3 regression cases. Blast >5 areas OR >2 complex → re-evaluate SPLIT before estimating.
818>
819> **Risk Margin (drives max bound):**
820>
821> | likely_days | Base margin |
822> | ------------------- | ------------------------------- |
823> | <1d trivial | +10% |
824> | 1-2d small additive | +20% |
825> | 3-4d real feature | +35% |
826> | 5-7d large | +50% |
827> | 8-10d very large | +75% |
828> | >10d | +100% AND **flag SHOULD SPLIT** |
829>
830> **Risk-factor add-ons (additive — enumerate in `risk_factors`):**
831>
832> | Factor | +margin |
833> | --------------------------------------------------------------------- | ------- |
834> | `touches-complex-existing-feature` (>500 LOC, multi-handler, central) | +20% |
835> | `cross-service-contract` change | +25% |
836> | `schema-migration-on-populated-data` | +25% |
837> | `new-tech-or-unfamiliar-pattern` | +30% |
838> | `regression-fan-out` (≥3 downstream areas re-test) | +20% |
839> | `performance-or-latency-critical` | +20% |
840> | `concurrency-race-event-ordering` | +25% |
841> | `shared-common-code` (multi-consumer/multi-app) | +25% |
842> | `unclear-requirements-or-design` | +30% |
843>
844> **Collapse rule:** total margin >100% → STOP, split (padding past 2x is dishonesty). Margin <15% on `likely_days ≥5` → under-estimated, widen.
845>
846> **Work-Type Caps (hard ceilings on `likely_days`):**
847> | Work type | Max SP | Max likely |
848> | --- | --- | --- |
849> | Single field / config flag / style fix | 1 | 0.5d |
850> | Add property to existing model + bind to existing UI | 2 | 1d |
851> | **Additive endpoint + minor UI control** (button/menu/column), reuses fixtures | **3** | **2-3d** |
852> | Additive endpoint + **NEW UI surface** OR additive multi-layer + new domain rule + 2+ test files | 5 | 3-5d |
853> | NEW model/aggregate OR migration OR cross-module contract OR heavy test (>1.5d) OR NEW UI + non-trivial backend | 8 | 5-7d |
854> | NEW UI surface + (NEW aggregate OR migration OR cross-service contract) | 13 | SHOULD split |
855> | Cross-service contract + migration combined | 13 | SHOULD split |
856> | Beyond | 21 | MUST split |
857>
858> **SP→Days (validation only):** 1=0.5d/0.25d · 2=1d/0.35d · 3=2d/0.65d · 5=4d/1.0d · 8=6d/1.5d · 13=10d/2.0d (Trad/AI likely)
859> **AI speedup:** SP 1≈2x · 2-3≈3x · 5-8≈4x · 13+≈5x. AI cost = `(code_gen × 1.3) + (test_gen × 1.3)` (30% review overhead).
860>
861> **MANDATORY frontmatter:**
862>
863> ```yaml
864> story_points: <n>
865> complexity: low | medium | high | critical
866> man_days_traditional: '<min>-<max>d' # range when likely ≥3d; '<N>d' when <3d
867> man_days_ai: '<min>-<max>d'
868> risk_margin_pct: <n> # base + add-ons
869> risk_factors: [touches-complex-existing-feature, regression-fan-out] # closed-list from add-ons; [] if none
870> blast_radius:
871> touched_areas: <n>
872> complex_touched: <n>
873> downstream_consumers: [list or count]
874> shared_common_code: yes | no
875> estimate_scope_included: [code, integration-tests, frontend, i18n, docs]
876> estimate_scope_excluded: [unit-tests, e2e, perf, deployment, code-review-rounds]
877> estimate_reasoning: |
878> 5-7 lines covering:
879> (a) UI tier — row applied
880> (b) Backend tier — row applied
881> (c) Test scope — case breakdown by driver, file count, fixtures, tier row
882> (d) Cost driver — dominant tier + why
883> (e) Blast radius — touched, complex, regression scope
884> (f) Risk factors — list driving margin; why not larger/smaller
885> Example: "UI: compose Form/Table/Dialog → NEW screen (~1.5d). Backend: NEW command on existing aggregate,
886> reuses validation+repo (~1d). Tests: 4 transitions × 2 actors + 3 validation + 2 UI states = 13 cases,
887> 1 new fixture → tier 13-25 ~1.5d. Driver: UI composition + new states. Blast: 4 areas, 1 complex.
888> Risk: base 35% + touches-complex +20% = 55% → max 3.9d → range 2.5-4d."
889> ```
890>
891> **Sanity self-check:**
892>
893> - `likely_days ≥3d` and single-point? → reject, must be range
894> - Margin <15% on `likely_days ≥5d`? → under-estimated, widen
895> - Margin >100%? → STOP, split instead of buffer
896> - Complex existing feature touched, no regression budget in `(c)`? → reject
897> - Blast `>5` areas OR `>2` complex, no split discussion? → reject
898> - Purely additive on existing model AND existing UI? → cap SP 3 unless tests >1.5d
899> - NEW UI surface (page/complex form/dashboard)? → SP 5+ even if backend one endpoint
900> - Backend cross-service / migration / multi-aggregate? → SP 8+ regardless of UI
901> - `bottom_up_hours / 6` vs SP-Days disagreement >50%? → trust bottom-up, downgrade SP
902> - Without tests, SP drops ≥1 bucket? → tests dominate; state explicitly
903> - Reasoning called out UI vs backend vs blast vs risk factors? → if missing, add
904
905<!-- /SYNC:estimation-framework -->
906
907<!-- SYNC:ui-wireframe -->
908
909> **UI Wireframe** — Process visual design input (Figma URLs, screenshots, wireframes) via appropriate tool BEFORE creating wireframes. Use box-drawing ASCII characters for spatial layout. Classify every component into exactly ONE tier: Common (cross-app reusable) / Domain-Shared (cross-domain) / Page (single-page). Duplicate UI code = wrong tier. Search existing component libraries before creating new (>=80% match = reuse). Detail level varies by skill (idea=rough, story=full decomposition).
910
911<!-- /SYNC:ui-wireframe -->
912
913<!-- SYNC:critical-thinking-mindset -->
914
915> **Critical Thinking Mindset** — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
916> **Anti-hallucination:** Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
917
918<!-- /SYNC:critical-thinking-mindset -->
919
920<!-- SYNC:sequential-thinking-protocol -->
921
922> **Sequential Thinking Protocol** — Structured multi-step reasoning for complex/ambiguous work. Use when planning, reviewing, debugging, or refining ideas where one-shot reasoning is unsafe.
923>
924> **Trigger when:** complex problem decomposition · adaptive plans needing revision · analysis with course correction · unclear/emerging scope · multi-step solutions · hypothesis-driven debugging · cross-cutting trade-off evaluation.
925>
926> **Format (explicit mode — visible thought trail):**
927>
928> 1. `Thought N/M: [aspect]` — one aspect per thought, state assumptions/uncertainty
929> 2. `Thought N/M [REVISION of Thought K]: ...` — when prior reasoning invalidated; state Original / Why revised / Impact
930> 3. `Thought N/M [BRANCH A from Thought K]: ...` — explore alternative; converge with decision rationale
931> 4. `Thought N/M [HYPOTHESIS]: ...` then `[VERIFICATION]: ...` — test before acting
932> 5. `Thought N/N [FINAL]` — only when verified, all critical aspects addressed, confidence >80%
933>
934> **Mandatory closers:** Confidence % stated · Assumptions listed · Open questions surfaced · Next action concrete.
935>
936> **Stop conditions:** confidence <80% on any critical decision → escalate by asking the user directly · ≥3 revisions on same thought → re-frame the problem · branch count >3 → split into sub-task.
937>
938> **Implicit mode:** apply methodology internally without visible markers when adding markers would clutter the response (routine work where reasoning aids accuracy).
939>
940> **Deep-dive:** see `$sequential-thinking` skill (`.claude/skills/sequential-thinking/SKILL.md`) for worked examples (API design, debugging, architecture), advanced techniques (spiral refinement, hypothesis testing, convergence), and meta-strategies (uncertainty handling, revision cascades).
941
942<!-- /SYNC:sequential-thinking-protocol -->
943
944<!-- SYNC:estimation-framework:reminder -->
945
946- **MANDATORY MUST ATTENTION** estimation: bottom-up phase hours drive `man_days_traditional` (`Σh/6 × productivity_factor`); SP DERIVED. UI cost usually dominates — bump SP one bucket if NEW UI surface (page/complex form/dashboard). Frontmatter MUST include `story_points`, `complexity`, `man_days_traditional`, `man_days_ai`, `estimate_scope_included`, `estimate_scope_excluded`, `estimate_reasoning` (UI vs backend cost driver). Cap SP 3 for additive-on-existing-model+existing-UI unless test scope >1.5d. SP 13 SHOULD split, SP 21 MUST split.
947 <!-- /SYNC:estimation-framework:reminder -->
948
949<!-- SYNC:ui-system-context:reminder -->
950
951**IMPORTANT MUST ATTENTION** read frontend-patterns-reference, scss-styling-guide, design-system/README before any UI change.
952
953<!-- /SYNC:ui-system-context:reminder -->
954
955<!-- SYNC:critical-thinking-mindset:reminder -->
956
957**MUST ATTENTION** apply critical + sequential thinking — every claim needs appropriate traced evidence (`file:line` for repo/code claims; source URL or artifact section for research, product, content, and docs claims); confidence >80% to act, <60% DO NOT recommend. Anti-hallucination: never present guess as fact, admit uncertainty freely, cross-reference independently, stay skeptical of own confidence.
958
959<!-- /SYNC:critical-thinking-mindset:reminder -->
960
961<!-- SYNC:sequential-thinking-protocol:reminder -->
962
963**MUST ATTENTION** apply sequential-thinking — multi-step Thought N/M, REVISION/BRANCH/HYPOTHESIS markers, confidence % closer; see `$sequential-thinking` skill.
964
965<!-- /SYNC:sequential-thinking-protocol:reminder -->
966
967<!-- SYNC:ai-mistake-prevention:reminder -->
968
969**MUST ATTENTION** apply AI mistake prevention — verify generated content against evidence, trace downstream references before deleting or renaming, verify all affected outputs, re-read files after context loss, and surface ambiguity before acting.
970
971<!-- /SYNC:ai-mistake-prevention:reminder -->
972
973<!-- PROMPT-ENHANCE:STEP-TASK-CLOSING:START -->
974
975## Prompt-Enhance Closing Anchors
976
977**IMPORTANT MUST ATTENTION** follow declared step order for this skill; NEVER skip, reorder, or merge steps without explicit user approval
978**IMPORTANT MUST ATTENTION** for every step/sub-skill call: set `in_progress` before execution, set `completed` after execution
979**IMPORTANT MUST ATTENTION** every skipped step MUST include explicit reason; every completed step MUST include concise evidence
980**IMPORTANT MUST ATTENTION** if Task tools unavailable, maintain an equivalent step-by-step plan tracker with synchronized statuses
981
982<!-- PROMPT-ENHANCE:STEP-TASK-CLOSING:END -->
983
984<!-- SYNC:project-protocol-overlay -->
985
986> **Project Protocol Overlay** — Before executing this skill, resolve any PROJECT overlay rules layered onto it: match this skill's name against the `Target` column of the project's skill-protocol index (`docs/project-reference/skill-protocols-reference.md` by default; a `referenceDocs` entry in `docs/project-config.json` overrides the path), taking the most specific matching tier ONLY — exact name > glob > `*`. **That precedence orders overlays against EACH OTHER, never against this skill.** Read ONLY the matched bodies, resolved as `<protocols-dir>/<Name>.md`; a row's Body link is display text, never a read path. A matched body that is missing or malformed is REPORTED and skipped — never reconstructed from the index Description. No index, or no match -> proceed with no overlay, silently. Full contract: `.claude/skills/project-skill-protocol/references/registry.md`.
987>
988> Overlays are **ADDITIVE ONLY**: they ADD rules on top of this skill's own protocol and NEVER replace, override, disable, or reinterpret a rule it already states — removing every overlay must return this skill to exactly its documented behavior. An overlay is a BRIEF, not an authority escalation: it can NEVER waive a workflow gate, git discipline, a review gate, or a user-confirmation gate. A genuine overlay-vs-skill conflict, or two equally-specific overlays that directly contradict -> surface both to the user; NEVER resolve silently.
989
990<!-- /SYNC:project-protocol-overlay -->
991
992<!-- SYNC:project-protocol-overlay:reminder -->
993
994**MUST ATTENTION** resolve project protocol overlays for this skill BEFORE executing — most specific matching tier only (exact > glob > `*`, which ranks overlays against each other, NEVER against this skill), read only matched bodies at `<protocols-dir>/<Name>.md`; a missing or malformed body is reported, never reconstructed. Overlays are ADDITIVE ONLY (they never replace this skill's own rules) and are a brief, NEVER an authority escalation; an equal-specificity contradiction goes to the user.
995
996<!-- /SYNC:project-protocol-overlay:reminder -->
997
998## Closing Reminders
999
1000- **IMPORTANT MUST ATTENTION Goal:** transform a raw idea into a Definition-of-Ready PBI — problem-validated, tech-agnostic, with testable acceptance criteria, estimates, and a Dependencies table — so a team can build it without re-asking what or why.
1001- **IMPORTANT MUST ATTENTION — run + track EVERY step (AI forgets sub-phases):** Phase 0 locate active plan → 1 idea intake + module detect → 2 domain research → 3 problem-hypothesis GATE → 4 BABOK elicitation → 5 BDD acceptance criteria → 5.1 AI-SDD M1-M5/M7 BLOCKING gate → 5.5 testability → 6 prioritization + DRAFT estimate → 7 validation interview GATE → 7.5 RE-DERIVE estimate vs locked scope → 8 PBI generation — NEVER skip, reorder, or merge a phase without explicit user approval.
1002
1003**Protocols in force — MUST ATTENTION (concise digest of the SYNC/shared blocks this skill carries):**
1004
1005- **AI Mistake Prevention:** verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
1006- **UI System Context:** ALWAYS read frontend-patterns, scss-styling-guide, design-system before any UI change.
1007- **Estimation Framework:** bottom-up hours drive man-days; SP derived; UI cost usually dominates.
1008- **UI Wireframe:** ASCII layout, classify every component into ONE tier, reuse before creating.
1009- **Critical Thinking:** traced proof per claim, confidence >80% to act, NEVER guess.
1010- **Sequential Thinking:** multi-step Thought N/M with REVISION/BRANCH/HYPOTHESIS markers, confidence-% closer.
1011
1012- **IMPORTANT MUST ATTENTION** Phase 3 problem-hypothesis validation + Phase 7 validation interview (3-5 questions) are NON-OPTIONAL for new features — user decides assumptions/scope/dependencies, AI NEVER auto-decides — why: 42% of products fail from no market need; a silent AI assumption ships an unvalidated build
1013- **IMPORTANT MUST ATTENTION** Phase 7.5 RE-DERIVES `story_points`/`complexity`/`man_days_traditional`/`man_days_ai` against the LOCKED post-interview scope (per `SYNC:estimation-framework`) — NEVER ship stale Phase 6 draft numbers — why: pre-validation guesses are the #1 source of unreliable velocity data
1014- **MANDATORY IMPORTANT MUST ATTENTION** break work into small tasks via task tracking BEFORE starting; mark one `in_progress`, complete it before the next; on context loss the current task list first — why: compaction wipes prior-work memory, resume don't duplicate
1015- **MANDATORY IMPORTANT MUST ATTENTION** validate decisions with user by asking the user directly — NEVER auto-decide
1016- **IMPORTANT MUST ATTENTION** acceptance criteria are BDD GIVEN/WHEN/THEN (min 3: happy/edge/error) and MUST satisfy the Phase 5.1 AI-SDD M1-M5 and M7 gate — tech-agnostic Business Intent, logical `FR-`/`BR-` IDs first, observable single-interpretation ACs, rebuild-from-scratch validity, every AC demoable as a business outcome — why: a reader who must guess a rule/limit/role re-implements the wrong behavior
1017- **IMPORTANT MUST ATTENTION** apply the M7 demo test to every AC's BODY — _"what would a stakeholder SEE change?"_; no answer → TECHNICAL-ONLY, drop it. FAIL a `WHEN` that is an invocation (handler runs, consumer receives, job fires, data syncs) or a `THEN` asserting schema/type/nullability/call-count; NEVER derive the AC count from an architecture inventory — why: M1 governs vocabulary, M7 governs subject matter — a technical AC in tech-free prose passes M1 and still rots the PBI
1018- **IMPORTANT MUST ATTENTION** every PBI MUST include `story_points`, `complexity`, `man_days_traditional`, `man_days_ai` frontmatter AND a complete Dependencies table (`must-before`/`can-parallel`/`blocked-by`/`independent`) — fill even when `independent`
1019- **IMPORTANT MUST ATTENTION** keep PBI Business Intent prose tech-agnostic — NO framework/product/language/design-pattern names; implementation hints go ONLY in `## Implementation Notes`, source refs ONLY in `[Source: namespace/service/id]` evidence carriers — why: a tech-leaked spec is not rebuildable on another stack (M1/M2)
1020- **IMPORTANT MUST ATTENTION** greenfield mode: NEVER ask about tech stack during refinement — capture team skills/scale as signals only; tech decided after business analysis
1021- **MANDATORY IMPORTANT MUST ATTENTION** before refining domain PBIs, read existing TCs in `docs/specs/` and `docs/project-reference/domain-entities-reference.md`; grep 3+ existing PBIs/specs for local conventions before authoring — why: project vocabulary and patterns override generic BABOK/INVEST defaults
1022- **MANDATORY IMPORTANT MUST ATTENTION** cite `file:line` (or `[Source: ...]`) evidence for every claim, confidence >80% to act, <60% DO NOT recommend — NEVER present a guess as fact
1023- **IMPORTANT MUST ATTENTION** complex/lengthy work → persist findings to `plans/reports/` incrementally — why: prevents silent loss of all findings on context exhaustion
1024- **MANDATORY IMPORTANT MUST ATTENTION** add final review task to verify work quality
1025- **MANDATORY IMPORTANT MUST ATTENTION** add task: run `$why-review` — validate PBI design rationale before `$story` or `$spec [mode=tests]`
1026- **MANDATORY IMPORTANT MUST ATTENTION** add task: run `$pbi-challenge` — Dev BA PIC review before `$dor-gate` or `$story`
1027
1028**Anti-Rationalization:**
1029
1030| Evasion | Rebuttal |
1031| ------------------------------------------ | ---------------------------------------------------------------------------------------- |
1032| "Simple PBI, skip hypothesis validation" | Wrong assumption wastes more time than validation check. Apply Phase 3 always. |
1033| "Validation interview is optional here" | NEVER optional — Phase 7 user decides assumptions, AI doesn't |
1034| "Phase 6 estimate is fine, skip re-derive" | Phase 7.5 is MANDATORY — interview changed scope; stale numbers corrupt velocity |
1035| "Skip Dependencies table, no blockers" | Unknown blockers exist. Always fill table — even if `independent` |
1036| "Skip story points, just write ACs" | `story_points`, `man_days_traditional`, `man_days_ai` mandatory in frontmatter |
1037| "Add a stack hint, it clarifies the AC" | Business Intent stays tech-agnostic (M1/M2) — hints go to `## Implementation Notes` only |
1038| "Domain context not needed for small PBI" | Small PBIs touch entities. Read domain-entities-reference first |
1039
1040**[TASK-PLANNING]** Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using task tracking.
1041
1042**IMPORTANT MUST ATTENTION** Phase 3 hypothesis + Phase 7 interview are NON-OPTIONAL — user decides, AI never auto-decides.
1043**IMPORTANT MUST ATTENTION** Phase 7.5 re-derives estimates against locked scope — never ship stale Phase 6 numbers.
1044**IMPORTANT MUST ATTENTION** keep Business Intent tech-agnostic; cite `file:line`/`[Source:]` evidence, confidence >80% to act.
1045
1046<!-- CODEX:SYNC-PROMPT-PROTOCOLS:START -->
1047
1048## Hookless Prompt Protocol Mirror (Auto-Synced)
1049
1050Source: `.claude/.ck.json` + `.claude/skills/shared/sync-inline-versions.md` (`:full` blocks) + `.claude/scripts/lib/hookless-prompt-protocol.cjs`
1051
1052## [WORKFLOW-EXECUTION-PROTOCOL] [BLOCKING] Workflow Execution Protocol — MANDATORY IMPORTANT MUST CRITICAL. Do not skip for any reason.
1053
1054**Generic portability boundary:** Reusable skills and protocol text stay project-neutral; project-specific conventions are discovered from docs/project-config.json and docs/project-reference/. Apply shared AI-SDD from `shared/sdd-artifact-contract.md`. Read `docs/project-config.json` and `docs/project-reference/docs-index-reference.md`, then open the project reference docs named there. For spec, test-case, behavior-change, public-contract, or `docs/specs/` work, route through the local spec docs named by the docs index: `feature-spec-reference.md`, `spec-system-reference.md`, `spec-principles.md`, and `workflow-spec-test-code-cycle-reference.md` when specs/tests/code must stay synchronized. If either file or a required reference doc is missing or stale, auto-run `$project-init` (or the narrow lower-level route such as `$project-config`, `$docs-init`, `$scan-all`, or `$scan --target=<key>`) before ordinary project-specific work. Any supported AI tool may execute when this shared context and local docs are available.
1055
10561. **DETECT:** If the prompt starts with an explicit slash skill/workflow command, execute it directly. Otherwise match the prompt against the workflow catalog and skill list.
10572. **ANALYZE:** Choose the best option: execute directly, invoke a skill, activate a standard workflow, or compose a custom step combination.
10583. **AUTO-SELECT:** Pick the best option yourself. Do not ask the user to choose between direct execution, skill, standard workflow, or custom workflow.
10594. **ACTIVATE:** For a selected workflow, call `$start-workflow <workflowId>`; for a selected skill, invoke that skill; for a custom workflow, sequence custom steps directly; for direct execution, proceed with the task.
10605. **CREATE TASKS:** task tracking for ALL workflow/skill/custom steps before execution when the selected path has multiple steps.
10616. **PARALLELIZE:** Before executing the task list, tag each task `PAR` (independent inputs + write set disjoint from every other `PAR` task) or `SEQ` (name the blocking dependency), group `PAR` tasks into waves, declare the wave plan, and spawn each wave's sub-agents in ONE message — all-return barrier per wave, fan-out one level deep unless a sub-agent's own definition authorizes further fan-out. Sequential-by-default is a defect when tasks are independent; do not parallelize shared write targets, output-consuming tasks, trivial single-file work, ordering a skill or workflow explicitly fixes, or user-approval gates.
10627. **EXECUTE:** Advance per the **Workflow Step Advancement & Parallel Phases** rule in your context instructions — model-driven; a sub-agent completion advances a step identically to an inline call; a parallel-phase group is an all-return barrier (advance only after ALL members return, never serialize it)
1063
1064## Shared AI-SDD Protocol Markers
1065
1066Source: `.claude/skills/shared/sync-inline-versions.md`
1067
1068## SYNC:ai-sdd-artifact-contract
1069
1070> **AI-SDD Artifact Contract** — Shared spec-driven development rules stay portable and source-owned.
1071>
1072> 1. Keep reusable AI-SDD principles in `.claude`; put repository-specific paths, commands, owners, products, and formats in project config/reference docs.
1073> 2. Preserve cycle: `spec -> plan -> tasks -> implement -> verify -> update spec/docs`.
1074> 3. Trace every requirement or invariant through decision, task, TC/test, source evidence, and docs/spec update.
1075> 4. Treat code-to-spec extraction as reference-only until accepted by the canonical spec owner.
1076> 5. Any supported AI tool may plan, implement, review, or verify with synced context; using multiple tools is optional.
1077> 6. Update `.claude` source first, then sync generated mirrors; do not manually edit `.agents`, `.codex`, or `AGENTS.md`. — why: mirrors are generated artifacts; hand-edits are overwritten on the next sync
1078> 7. If `docs/project-config.json`, root instruction files, or a required project-reference doc is missing or stale, auto-run `$project-init` or the narrow lower-level route before ordinary project-specific work.
1079>
1080> **Active reference:** `shared/sdd-artifact-contract.md` in the active skills root.
1081
1082---
1083
1084## SYNC:ai-sdd-artifact-contract:reminder
1085
1086- **MANDATORY** Apply `shared/sdd-artifact-contract.md`; keep reusable AI-SDD in `.claude` and local rules in project docs.
1087- **MANDATORY** Code-to-spec extraction is reference-only until canonical acceptance; any supported AI tool may execute with synced context.
1088- **MANDATORY** Update `.claude` source before syncing generated mirrors; do not manually edit `.agents`, `.codex`, or `AGENTS.md`.
1089- **MANDATORY** Missing or stale project config, root instruction files, or required reference docs route project-specific work through `$project-init` or the narrow setup route automatically.
1090 **[TASK-PLANNING] [MANDATORY]** BEFORE executing any workflow or skill step, create/update task tracking for all planned steps, then keep it synchronized as each step starts/completes.
1091
1092## [LESSON-LEARNED-REMINDER] [BLOCKING] Task Planning & Continuous Improvement — MANDATORY. Do not skip.
1093
1094Break work into small tasks (task tracking) before starting. Add final task: "Analyze AI mistakes & lessons learned".
1095
1096**Extract lessons — ROOT CAUSE ONLY, not symptom fixes:**
1097
10981. Name the FAILURE MODE (reasoning/assumption failure), not symptom — "assumed API existed without reading source" not "used wrong enum value".
10992. Generality test: does this failure mode apply to ≥3 contexts/codebases? If not, abstract one level up.
11003. Write as a universal rule — strip project-specific names/paths/classes. Useful on any codebase.
11014. Consolidate: multiple mistakes sharing one failure mode → ONE lesson.
11025. **Recurrence gate:** "Would this recur in future session WITHOUT this reminder?" — No → skip `$learn`.
11036. **Auto-fix gate:** "Could `$code-review`/`$code-simplifier`/`$security-review`/`$lint` catch this?" — Yes → improve review skill instead.
11047. BOTH gates pass → ask user to run `$learn`.
1105 **[CRITICAL-THINKING-MINDSET]** Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
1106 **Anti-hallucination principle:** Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
1107 **AI Attention principle (Primacy-Recency):** Put the 3 most critical rules at both top and bottom of long prompts/protocols so instruction adherence survives long context windows.
1108 **Goal-driven execution:** Define success criteria first, loop until verified, and stop only when observable checks pass.
1109 **Tests verify intent:** Tests must protect business rules/invariants and fail when the protected intent breaks, not only mirror current behavior.
1110
1111## Common AI Mistake Prevention (System Lessons)
1112
1113- **Re-read files after context compaction.** Edit requires prior Read in same context; compaction wipes read state. Re-read before editing.
1114- **Grep for old terms after bulk replacements.** AI over-trusts find/replace completeness. Grep full repo after bulk edits for missed refs in docs/configs/catalogs.
1115- **Check downstream references before deleting.** Deletions cascade doc/code staleness. Map referencing files before removal.
1116- **After memory loss, check existing state before creating new.** Compaction wipes prior-work memory. Query current state to resume — never blindly duplicate.
1117- **Verify AI-generated content against actual code.** AI hallucinates APIs, class names, method signatures. Grep to confirm existence before documenting/referencing.
1118- **Trace full dependency chain after edits.** Changing a definition misses downstream consumers. Trace the full chain.
1119- **When renaming, grep ALL consumer file types.** Some file types silently ignore missing refs (no compile error). Search code, templates, configs, generated files.
1120- **Trace ALL code paths when verifying correctness.** Code existing ≠ code executing. Trace early exits, error branches, conditional skips — not just happy path.
1121- **Update docs that embed canonical data when source changes.** Docs inlining derived data (workflows, schemas, configs) go stale silently. Update all embedding docs alongside source.
1122- **Verify sub-agent results after context recovery.** Background agents may finish while parent compacted — grep-verify output, don't trust assumed completion.
1123- **Cross-check full target list against sub-agent assignments.** Parallel sub-agents by category miss boundary items. Reconcile union of assignments against target list before proceeding.
1124- **Sub-agents inherit knowledge only from their agent .md definition — use custom agent types, not built-in Explore.** Tool adoption = permission + knowledge + enforcement (numbered workflow step).
1125- **Persist sub-agent findings incrementally, not as a final batch.** Long sub-agents hit cutoffs before final write — findings lost. Instruct append-per-section to report file.
1126- **When debugging, ask "whose responsibility?" before fixing.** Trace caller (wrong data) vs callee (wrong handling). Fix at responsible layer — never patch symptom site.
1127- **Test failure → record a provisional verdict before trace/edit, then investigate.** Use the full five-way taxonomy: SOURCE-WRONG (production violates intent), TEST-WRONG (assertion/setup is stale), TEST-NOT-OPTIMAL (valid but fragile or low-signal test), ENVIRONMENT-BLOCKED (external state prevents a verdict), or AMBIGUOUS (intent/evidence cannot choose safely). Then trace root cause and triangulate against the governing spec (`docs/specs/**` if one exists) AND source. NEVER weaken an assertion, add a skip, relax a timeout, or change source merely to force green.
1128- **Grep ALL removed names after extraction/refactoring.** Primary file "done" ≠ secondary files clean. Grep entire scope for every removed symbol before declaring complete.
1129- **Assume existing values are intentional — ask WHY before changing OR flagging one as a defect.** Pattern-matching as "wrong" skips context. Before changing or reporting any constant/limit/flag/cutoff: read comments, git blame, the CALLER's ordering (the guarantee that makes the value correct usually lives in code running immediately BEFORE the cited line), and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard — and in a validation pass, an accurate `file:line` citation proves the transcription, never the defect.
1130- **Verify ALL affected outputs, not just the first.** One build green ≠ all green. Multi-stack changes (backend/frontend/tests/docs) require verifying EVERY output.
1131- **Evaluate fit before copying a nearby pattern.** Closest example ≠ matching preconditions — verify the new context shares the same constraints, base classes, scope, lifetime.
1132- **Holistic-first debugging — resist nearest-attention trap.** Don't dive into first plausible cause. List EVERY precondition (config, env vars, paths, DB, endpoints, creds, versions, DI, data). Verify each against evidence (grep/query — not reasoning). Ask "what would falsify this?" — if nothing, it's not a hypothesis. Most expensive failure: going deeper in "obvious" layer while bug sits in layer never questioned.
1133- **Surgical changes — apply the diff test (context-aware).** Two modes: (1) Bug fix → every line traces to the bug; no restyling; orphan cleanup only for imports YOUR changes made unused. (2) Review/enhancement → implement improvements AND announce as "Enhancement beyond main request: [what]". Never silently scope-creep. Diff test: "Would this line exist if I wasn't asked to do X?" — if no, delete or announce.
1134- **Surface ambiguity before coding — don't pick silently.** Multiple valid interpretations → present each with effort: "[Request] could mean (1) [N h], (2) [N h]. Which matters?" List scope/format/volume/constraints assumptions first. If simpler path exists, say so. Never silently pick.
1135- **[MANDATORY FIRST ACTION] ALWAYS activate a suitable skill or workflow BEFORE responding.** Match task against workflow catalog + skill list; invoke via skill invocation or `$start-workflow <workflowId>`. NEVER answer or write code before checking. Skip = protocol violation.
1136- **Why-Review adversarial mindset — apply when reviewing any plan, decision, or design.** Default SKEPTIC not VALIDATOR: steel-man a rejected alternative, invert each stated reason ("what does it sacrifice?"), stress-test top 2-3 assumptions, run pre-mortem ("ships, fails in 3 months — what breaks?"), surface 1-2 alternatives author missed. Section presence ≠ quality; quality = causal reasoning + concrete mitigations + evidence, not "it's better" or "monitor closely".
1137- **Front-load report-write in sub-agent prompts for large reviews.** Many-file sub-agents hit budget before final write — findings lost. Design prompts so: (1) report-write is first explicit deliverable, (2) append per-file/section (not batched), (3) scope bounded so reads don't exhaust budget. Truncated mid-sentence with no report file → spawn narrower scope, don't retry same prompt.
1138- **After context compaction, re-verify all prior phase outcomes before continuing.** Summaries describe intent, not environment state (git index, filesystem, processes). On resume, FIRST audit: git status, re-read modified files, verify filesystem. Every "completed" claim is an untested hypothesis until evidence confirms.
1139- **OOM/memory: check row count before row size.** Triage: (1) Unbounded query — no DB filter for trigger? Push filter to DB; eliminates OOM. (2) Large rows? Projection reduces proportionally. Row reduction > projection in ROI.
1140- **Assert the outcome your system OWNS, never the intermediate state your INFRASTRUCTURE owns.** When testing anything asynchronous (queue/broker delivery, retries, background jobs, caches, replication), assert the final business/entity state. NEVER assert the delivery bookkeeping — consume/send status, attempt counts, last-error, row existence or counts in a broker, scheduler, or outbox/inbox table. That bookkeeping lives in shared infrastructure that ANY co-running process (a peer worker, a second replica, a leftover local container) can write, usually under a deterministic shared key, so the assertion silently tests the developer's environment instead of the system: green when run alone, flaky the instant anything else shares that broker + database. Gate question for every assertion: "would this hold no matter WHICH process did the work?" — if no, assert the converged data state instead. Corollary: process-local fault injection and in-process telemetry cannot gate work any process may perform — use them as stress amplifiers (arm → bounded window → disarm → assert convergence), never as preconditions.
1141- **Keep domain concepts out of generic/shared/infrastructure layers.** Reusable layer (shared library, framework, infra module) must reference NO consumer-specific domain concept — tenant/customer/product IDs, business entities, feature rules. Leak compiles + runs → passes review silently while coupling the "reusable" layer to one consumer. Keep shared type domain-free; push domain fields/logic down into the consumer via subclass/composition. — why: a layer coupled to one consumer's domain is no longer reusable.
1142
1143<!-- CODEX:SYNC-PROMPT-PROTOCOLS:END -->