mirror of
https://github.com/azaion/admin.git
synced 2026-06-21 13:01:08 +00:00
Compare commits
32 Commits
stage
...
e3b0fe6582
| Author | SHA1 | Date | |
|---|---|---|---|
| e3b0fe6582 | |||
| 6e1e147562 | |||
| 837b1f2374 | |||
| 5224a12589 | |||
| 8b7d8a4275 | |||
| 4bf2e689cb | |||
| ebde2b2d25 | |||
| f369153149 | |||
| d2b5308b45 | |||
| 1bdbe8c96d | |||
| a77b3f8a59 | |||
| c2c659ef62 | |||
| 1e1ded73f5 | |||
| 8e7c602f51 | |||
| 51a293dbcc | |||
| 491993f9c1 | |||
| 9679b5636f | |||
| 3a925b9b0f | |||
| c7b297de83 | |||
| 43fe38e67d | |||
| 0c9340a1af | |||
| 4914f08aff | |||
| 5e90512987 | |||
| 5ca9ccab2c | |||
| f13c57b314 | |||
| e40ea3eeaa | |||
| 15631b37cb | |||
| 64887e5bfc | |||
| 7ba2f1b9c2 | |||
| ea55f695dc | |||
| 210b249665 | |||
| ad8c690550 |
@@ -39,6 +39,7 @@ alwaysApply: true
|
||||
- When you think you are done with changes, run the full test suite. Every failure in tests that cover code you modified or that depend on code you modified is a **blocking gate**. For pre-existing failures in unrelated areas, report them to the user but do not block on them. Never silently ignore or skip a failure without reporting it. On any blocking failure, stop and ask the user to choose one of:
|
||||
- **Investigate and fix** the failing test or source code
|
||||
- **Remove the test** if it is obsolete or no longer relevant
|
||||
- **Iterative-skill exception**: when an iterative loop skill is active (e.g. autodev / `implement/SKILL.md` batch loop, `refactor/SKILL.md` batch loop), the skill governs full-suite cadence — typically focused tests per task/batch and a single full-suite gate at the very end of the implementation phase, NOT after each batch. "Done with changes" means done with the entire implementation phase the skill is running, not done with one batch. Do not run the full suite per batch unless the skill explicitly says to.
|
||||
- Do not rename any databases or tables or table columns without confirmation. Avoid such renaming if possible.
|
||||
|
||||
- Make sure we don't commit binaries, create and keep .gitignore up to date and delete binaries after you are done with the task
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
description: "Use chunked writes (Write + StrReplace marker pattern) for large generated files, especially after a monolithic Write fails"
|
||||
alwaysApply: true
|
||||
---
|
||||
# Large File Writes — Chunk on Failure
|
||||
|
||||
When a `Write` call to a single file fails (timeout, payload limit, "Invalid arguments", or any tool error) and the intended content is large (>~500 lines or >~50 KB), do NOT retry the same monolithic Write. Switch to chunked writes:
|
||||
|
||||
1. **First Write** — create the file with header + table of contents (if applicable) + an explicit append marker, e.g.
|
||||
|
||||
```
|
||||
<!-- INSERTION_POINT do-not-remove-until-final-chunk -->
|
||||
```
|
||||
|
||||
2. **Each subsequent chunk** — use `StrReplace` to replace the marker with `<new content>\n<marker>` so the marker stays at the end. This is idempotent: if a chunk fails, retry it without losing earlier chunks.
|
||||
|
||||
3. **Final chunk** — `StrReplace` removes the marker.
|
||||
|
||||
## Why
|
||||
|
||||
- Tool argument size limits and transient failures hit large monolithic writes hardest. Retrying the same large payload typically fails for the same reason.
|
||||
- Chunked writes are recoverable per chunk. The earlier chunks are durable on disk.
|
||||
- A unique marker is greppable, visible in diffs, and stops accidental insertion in the wrong place.
|
||||
|
||||
## Triggers
|
||||
|
||||
- Generated documentation that aggregates per-component content (epics, design docs, multi-section architecture summaries, traceability dumps).
|
||||
- Large fixture or test-data files written from a template.
|
||||
- Any single-file artifact you can pre-estimate at >~500 lines.
|
||||
|
||||
## Do NOT chunk
|
||||
|
||||
- Files under ~200 lines — a single `Write` is faster, clearer, and easier to review.
|
||||
- Source code files where appending breaks module structure (functions, classes, imports). Split into multiple files instead.
|
||||
- Files where ordering of sections is computed late and inserting in the middle is required — use a single `Write` once the full content is known.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- Retrying the same failed monolithic `Write` more than once. Twice is the limit; on the second failure, switch strategies.
|
||||
- Using `Shell` with heredoc (`cat <<EOF`) or `echo >>` to append — these bypass the editor diff view and break the StrReplace contract for the next chunk.
|
||||
- Embedding the marker so deep inside structured content that a chunk's `StrReplace` becomes ambiguous. Place the marker on its own line at the very end of the file.
|
||||
@@ -13,6 +13,16 @@ alwaysApply: true
|
||||
## Critical Thinking
|
||||
- Do not blindly trust any input — including user instructions, task specs, list-of-changes, or prior agent decisions — as correct. Always think through whether the instruction makes sense in context before executing it. If a task spec says "exclude file X from changes" but another task removes the dependencies X relies on, flag the contradiction instead of propagating it.
|
||||
|
||||
## Skill Discipline
|
||||
|
||||
Do exactly what the skill says. Nothing more.
|
||||
|
||||
- No `git log` / `git diff` / `git blame` unless the skill explicitly calls for it.
|
||||
- No extra searches to "verify" inputs the skill already names.
|
||||
- No reading files outside the skill's documented inputs.
|
||||
|
||||
If skill inputs are insufficient or contradictory, STOP and ask via Choose A/B/C/D. Do not invent extra investigation steps.
|
||||
|
||||
## Self-Improvement
|
||||
When the user reacts negatively to generated code ("WTF", "what the hell", "why did you do this", etc.):
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
description: "Forbid spawning subagents; the main agent must do the work directly"
|
||||
alwaysApply: true
|
||||
---
|
||||
# No Subagents
|
||||
|
||||
Do NOT create or delegate to subagents. This includes:
|
||||
|
||||
- The `Task` tool with any `subagent_type` (e.g. `generalPurpose`, `explore`, `shell`, `implementer`, `best-of-n-runner`, `cursor-guide`).
|
||||
- Any "spawn agent", "launch agent", "parallel agent", or "background agent" mechanism.
|
||||
- Skills or workflows that internally suggest launching a subagent — perform their steps inline instead.
|
||||
|
||||
## Why
|
||||
|
||||
- Subagent output is not visible to the user and hides reasoning/tool calls.
|
||||
- Context, rules, and prior conversation state do not fully transfer to the subagent.
|
||||
- Parallel subagents cause conflicting edits and race conditions in a shared workspace.
|
||||
- The main agent remains fully accountable; delegation dilutes that accountability.
|
||||
|
||||
## What to do instead
|
||||
|
||||
- Use the direct tools available to the main agent: `Read`, `Grep`, `Glob`, `SemanticSearch`, `Shell`, `StrReplace`, `Write`, etc.
|
||||
- For broad exploration, run `Grep`/`Glob`/`SemanticSearch` yourself and read the files directly.
|
||||
- For multi-step work, use `TodoWrite` to track progress inline.
|
||||
- For isolated experiments the user explicitly asks for, use a git branch/worktree you manage directly — not a subagent runner.
|
||||
|
||||
## Exception
|
||||
|
||||
Only spawn a subagent if the user explicitly requests it in the current turn (e.g. "use a subagent to…", "launch an explore agent…"). Even then, confirm once before spawning.
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
description: "Explanation length and reasoning depth calibration"
|
||||
alwaysApply: true
|
||||
---
|
||||
# Response Calibration
|
||||
|
||||
Default to concise. Expand only when the content demands it.
|
||||
|
||||
## Length target
|
||||
|
||||
- **Default**: a direct answer in ~3–10 lines. Short paragraphs or a tight bullet list.
|
||||
- **Expand when**: the question involves trade-offs across multiple options, a migration/architectural decision, a security/data-loss risk, or the user explicitly asks for depth ("explain in detail", "walk me through", "why").
|
||||
- **Shrink when**: the user asks for "shorter", "simpler", "TL;DR", "one line", or similar. Do not re-inflate in later turns unless they ask a new deeper question.
|
||||
|
||||
## Completeness floor
|
||||
|
||||
Short ≠ incomplete. Every response must still:
|
||||
|
||||
- Answer the actual question asked (not a reframed version).
|
||||
- State the key constraint or reason *once*, not repeatedly.
|
||||
- Flag a real caveat if one exists (data loss, breaking change, wrong-OS, security). One sentence is enough.
|
||||
- Not drop a step from an action sequence. If there are 5 steps, list 5 — but without narration between them.
|
||||
|
||||
If the honest answer truly needs more space (e.g. trade-off matrix, multi-option decision), write more — but lead with the recommendation or direct answer, then the detail.
|
||||
|
||||
## Structure
|
||||
|
||||
- One direct sentence first. Then supporting detail.
|
||||
- Prefer bullets over prose for enumerations, comparisons, or step lists.
|
||||
- Drop section headers for anything under ~15 lines.
|
||||
- No "Summary" / "Conclusion" sections unless the response is genuinely long.
|
||||
|
||||
## Reasoning depth (internal)
|
||||
|
||||
- Match thinking to the problem, not the length of the answer.
|
||||
- Factual / "where is X used" / single-file edit → minimal thinking, go straight to tools.
|
||||
- Trade-off / refactor / debugging 3+ hypotheses deep → full thinking budget.
|
||||
- Do not pad thinking to look thorough. Do not skip thinking on genuinely ambiguous problems to look fast.
|
||||
|
||||
## Anti-patterns to avoid
|
||||
|
||||
- Restating the question back to the user.
|
||||
- Multi-paragraph preambles before the answer.
|
||||
- Exhaustive "alternatives considered" sections when the user didn't ask for alternatives.
|
||||
- Recapping what was just done at the end of every tool-using turn ("Done. I have edited the file…") — a one-line confirmation is enough.
|
||||
- Speculative "you might also want to…" paragraphs. Offer follow-ups as a single short sentence, or not at all.
|
||||
@@ -0,0 +1,38 @@
|
||||
---
|
||||
description: "Standards for creating and maintaining Cursor skills"
|
||||
globs: [".cursor/skills/**"]
|
||||
---
|
||||
|
||||
# Skill Building
|
||||
|
||||
## When To Create A Skill
|
||||
- Create a skill for repeatable, bounded workflows that benefit from a reusable process.
|
||||
- Do not create a skill for a one-off task, vague goal, or workflow that still needs product decisions.
|
||||
- Start small; evolve the skill when repeated use reveals clearer steps, constraints, or checks.
|
||||
|
||||
## Skill Contract
|
||||
- `SKILL.md` must define a clear `name` and a proactive `description` that explains when the skill should be used.
|
||||
- State expected inputs, constraints, workflow steps, and final output shape.
|
||||
- Make trigger conditions explicit enough that the agent can recognize intent without an exact command.
|
||||
- Base instructions on observable project evidence; do not invite fabrication or unsupported assumptions.
|
||||
|
||||
## Keep The Core Lean
|
||||
- Keep `SKILL.md` concise and under the repo's `.cursor/` size guidance.
|
||||
- Move detailed standards, examples, and background knowledge into `references/`.
|
||||
- Put reusable output shapes in `templates/` or other skill-local assets instead of embedding them in the main instructions.
|
||||
- Keep one primary responsibility per skill; use an orchestrator skill only when multiple existing skills must run in a defined order.
|
||||
|
||||
## Deterministic Work
|
||||
- Use scripts for mechanical steps that are repeatable, parameterized, and safer outside the model's reasoning.
|
||||
- Scripts must expose explicit inputs, avoid hidden side effects, and fail loudly on errors.
|
||||
- Do not use scripts to bypass review, hide destructive behavior, or hardcode secrets.
|
||||
|
||||
## Quality Proof
|
||||
- Include realistic examples, checklists, or eval-style scenarios that define what good output looks like.
|
||||
- Cover common failure cases such as missing sections, leftover placeholders, hallucinated facts, unsafe actions, or malformed output.
|
||||
- Review skill changes against those checks before treating the skill as ready.
|
||||
|
||||
## Security Review
|
||||
- Treat third-party skills like untrusted code until reviewed.
|
||||
- Inspect scripts, dependencies, references, secret handling, network calls, and destructive commands before use.
|
||||
- Prefer local, project-scoped assets and dependencies; document any external dependency the skill requires.
|
||||
@@ -14,11 +14,14 @@ alwaysApply: true
|
||||
- Issue types: Epic, Story, Task, Bug, Subtask
|
||||
|
||||
## Tracker Availability Gate
|
||||
- If Jira MCP returns **Unauthorized**, **errored**, **connection refused**, or any non-success response: **STOP** tracker operations and notify the user via the Choose A/B/C/D format documented in `.cursor/skills/autodev/protocols.md`.
|
||||
- If Jira MCP returns **Unauthorized**, **errored**, **connection refused**, **timeout**, a non-2xx status code, an empty body, or any response shape that does not clearly confirm the requested change: **STOP IMMEDIATELY** — no automatic retry, no silent continuation. Surface the full raw error/response to the user verbatim and notify via the Choose A/B/C/D format documented in `.cursor/skills/autodev/protocols.md`.
|
||||
- A minimal `{"success": true}` body with no echoed issue state is NOT a confirmed transition. When a transition's success matters (status moves, ticket creation, blocking link), follow it with a read-back call (`getJiraIssue` or equivalent) and confirm the new state matches what you asked for. If the read-back disagrees → STOP and ASK.
|
||||
- Do NOT loop "retry up to N times before asking". One call, one verification. On failure, the user decides whether to retry.
|
||||
- The user may choose to:
|
||||
- **Retry authentication** — preferred; the tracker remains the source of truth.
|
||||
- **Retry the same operation** — once, after the user authorizes it. If it fails again, surface both responses.
|
||||
- **Retry authentication** — preferred when the failure looks like an auth/credentials problem; the tracker remains the source of truth.
|
||||
- **Continue in `tracker: local` mode** — only when the user explicitly accepts this option. In that mode all tasks keep numeric prefixes and a `Tracker: pending` marker is written into each task header. The state file records `tracker: local`. The mode is NOT silent — the user has been asked and has acknowledged the trade-off.
|
||||
- Do NOT auto-fall-back to `tracker: local` without a user decision. Do not pretend a write succeeded. If the user is unreachable (e.g., non-interactive run), stop and wait.
|
||||
- Do NOT auto-fall-back to `tracker: local` without a user decision. Do not pretend a write succeeded. Do not paper over an opaque response by moving on. If the user is unreachable (e.g., non-interactive run), stop and wait.
|
||||
- When the tracker becomes available again, any `Tracker: pending` tasks should be synced — this is done at the start of the next `/autodev` invocation via the Leftovers Mechanism below.
|
||||
|
||||
## Leftovers Mechanism (non-user-input blockers only)
|
||||
|
||||
@@ -3,7 +3,7 @@ name: autodev
|
||||
description: |
|
||||
Auto-chaining orchestrator that drives the full BUILD-SHIP workflow from problem gathering through deployment.
|
||||
Detects current project state from _docs/ folder, resumes from where it left off, and flows through
|
||||
problem → research → plan → decompose → implement → deploy without manual skill invocation.
|
||||
problem → research → plan → test specs → decompose → implement → tests → docs sync → deploy without manual skill invocation.
|
||||
Maximizes work per conversation by auto-transitioning between skills.
|
||||
Trigger phrases:
|
||||
- "autodev", "auto", "start", "continue"
|
||||
@@ -52,7 +52,7 @@ Determine which flow to use (check in order — first match wins):
|
||||
|
||||
After selecting the flow, apply its detection rules (first match wins) to determine the current step.
|
||||
|
||||
**Note**: the meta-repo flow uses a different artifact layout — its source of truth is `_docs/_repo-config.yaml`, not `_docs/NN_*/` folders. Other detection rules assume the BUILD-SHIP artifact layout; they don't apply to meta-repos.
|
||||
**Note**: the meta-repo flow uses a different artifact layout — its source of truth is `_docs/_repo-config.yaml`, not `_docs/NN_*/` folders. After Step 2.5 it also produces `_docs/glossary.md` and a `## Architecture Vision` section in the cross-cutting architecture doc identified by `docs.cross_cutting`. Other detection rules assume the BUILD-SHIP artifact layout; they don't apply to meta-repos.
|
||||
|
||||
## Execution Loop
|
||||
|
||||
@@ -67,8 +67,9 @@ B3. Read state — `_docs/_autodev_state.md` (if it exists).
|
||||
B4. Read File Index — `state.md`, `protocols.md`, and the active flow file.
|
||||
|
||||
### Resolve (once per invocation, after Bootstrap)
|
||||
R1. Reconcile state — verify state file against `_docs/` contents; on disagreement, trust the folders
|
||||
and update the state file (rules: `state.md` → "State File Rules" #4).
|
||||
R1. Reconcile state — verify state file against `_docs/` contents; probe `<workspace-root>/../docs`
|
||||
(parent suite `docs/` — see `state.md` → "State File Rules" #4); on disagreement,
|
||||
trust the folders and update the state file (rules: `state.md` → "State File Rules" #4).
|
||||
After this step, `state.step` / `state.status` are authoritative.
|
||||
R2. Resolve flow — see §Flow Resolution above.
|
||||
R3. Resolve current step — when a state file exists, `state.step` drives detection.
|
||||
@@ -112,6 +113,15 @@ Do NOT modify, skip, or abbreviate any part of the sub-skill's workflow. The aut
|
||||
|
||||
The state file (`_docs/_autodev_state.md`) is a minimal pointer — only the current step. See `state.md` for the authoritative template, field semantics, update rules, and worked examples. Do not restate the schema here — `state.md` is the single source of truth.
|
||||
|
||||
**Conciseness rule (authoritative).** The state file MUST stay short. Acceptable content per field:
|
||||
|
||||
- `name` — the step title from the active flow's Step Reference Table. That's it.
|
||||
- `sub_step.name` — kebab-case identifier from the active sub-skill. That's it.
|
||||
- `sub_step.detail` — **leave empty (`""`) by default.** Add a one-line note ONLY when the next-session resumer cannot infer where to pick up from `phase` + `name` + on-disk artifacts alone (e.g. `"batch 2 of 4"`, `"blocked on D-PROJ-2 reply"`, `"variant 1b"`). NEVER use `detail` as a changelog, recap, or summary of completed work — those facts belong in the relevant `_docs/` artifact (glossary, traceability matrix, leftovers folder, retro report, etc.) and in git history.
|
||||
- **Total file size target: <30 lines.** If you're tempted to write more, you're using the wrong artifact — write in `_docs/` instead.
|
||||
|
||||
Multi-line `detail` blobs that recap what was just completed are a smell. The state file is a *pointer*, not a logbook.
|
||||
|
||||
## Trigger Conditions
|
||||
|
||||
This skill activates when the user wants to:
|
||||
|
||||
@@ -13,7 +13,7 @@ A first-time run executes Phase A then Phase B; every subsequent invocation re-e
|
||||
|
||||
| Step | Name | Sub-Skill | Internal SubSteps |
|
||||
|------|------|-----------|-------------------|
|
||||
| 1 | Document | document/SKILL.md | Steps 1–8 |
|
||||
| 1 | Document | document/SKILL.md | Steps 0–7 incl. inline 2.5 (module-layout) and 4.5 (glossary + arch vision) |
|
||||
| 2 | Architecture Baseline Scan | code-review/SKILL.md (baseline mode) | Phase 1 + Phase 7 |
|
||||
| 3 | Test Spec | test-spec/SKILL.md | Phases 1–4 |
|
||||
| 4 | Code Testability Revision | refactor/SKILL.md (guided mode) | Phases 0–7 (conditional) |
|
||||
@@ -53,6 +53,8 @@ Action: An existing codebase without documentation was detected. Read and execut
|
||||
|
||||
The document skill's Step 2.5 produces `_docs/02_document/module-layout.md`, which is required by every downstream step that assigns file ownership (`/implement` Step 4, `/code-review` Phase 7, `/refactor` discovery). If this file is missing after Step 1 completes (e.g., a pre-existing `_docs/` dir predates the 2.5 addition), re-invoke `/document` in resume mode — it will pick up at Step 2.5.
|
||||
|
||||
The document skill's Step 4.5 produces `_docs/02_document/glossary.md` and prepends a confirmed `## Architecture Vision` section to `architecture.md`. Both are user-confirmed artifacts; downstream skills (refactor, decompose, new-task) treat them as authoritative for terminology and structural intent. If `glossary.md` is missing after Step 1 (pre-existing `_docs/` dir from before the 4.5 addition), re-invoke `/document` in resume mode — it will pick up at Step 4.5 without redoing module/component analysis.
|
||||
|
||||
---
|
||||
|
||||
**Step 2 — Architecture Baseline Scan**
|
||||
@@ -150,15 +152,17 @@ If `_docs/02_tasks/` subfolders have some task files already (e.g., refactoring
|
||||
---
|
||||
|
||||
**Step 6 — Implement Tests**
|
||||
Condition (folder fallback): `_docs/02_tasks/todo/` contains task files AND `_dependencies_table.md` exists AND `_docs/03_implementation/implementation_report_tests.md` does not exist.
|
||||
Condition (folder fallback): `_docs/02_tasks/todo/` contains test task files AND `_dependencies_table.md` exists AND `_docs/03_implementation/implementation_report_tests.md` does not exist.
|
||||
State-driven: reached by auto-chain from Step 5.
|
||||
|
||||
Action: Read and execute `.cursor/skills/implement/SKILL.md`
|
||||
Action: Invoke `.cursor/skills/implement/SKILL.md` with task selection context **Test implementation**.
|
||||
|
||||
The implement skill reads test tasks from `_docs/02_tasks/todo/` and implements them.
|
||||
The implement skill reads only test tasks from `_docs/02_tasks/todo/` and implements them.
|
||||
|
||||
If `_docs/03_implementation/` has batch reports, the implement skill detects completed tasks and continues.
|
||||
|
||||
For folder fallback, **test task files** means `*_test_infrastructure.md` plus task specs whose `**Component**` or `**Epic**` identifies `Blackbox Tests`.
|
||||
|
||||
---
|
||||
|
||||
**Step 7 — Run Tests**
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Greenfield Workflow
|
||||
|
||||
Workflow for new projects built from scratch. Flows linearly: Problem → Research → Plan → UI Design (if applicable) → Decompose → Implement → Run Tests → Security Audit (optional) → Performance Test (optional) → Deploy → Retrospective.
|
||||
Workflow for new projects built from scratch. Flows linearly: Problem → Research → Plan → UI Design (if applicable) → Test Spec → Decompose → Implement + Product Completeness Gate → Code Testability Revision → Decompose Tests → Implement Tests → Run Tests → Test-Spec Sync → Update Docs → Security Audit (optional) → Performance Test (optional) → Deploy → Retrospective.
|
||||
|
||||
## Step Reference Table
|
||||
|
||||
@@ -10,13 +10,19 @@ Workflow for new projects built from scratch. Flows linearly: Problem → Resear
|
||||
| 2 | Research | research/SKILL.md | Mode A: Phase 1–4 · Mode B: Step 0–8 |
|
||||
| 3 | Plan | plan/SKILL.md | Step 1–6 + Final |
|
||||
| 4 | UI Design | ui-design/SKILL.md | Phase 0–8 (conditional — UI projects only) |
|
||||
| 5 | Decompose | decompose/SKILL.md | Step 1–4 |
|
||||
| 6 | Implement | implement/SKILL.md | (batch-driven, no fixed sub-steps) |
|
||||
| 7 | Run Tests | test-run/SKILL.md | Steps 1–4 |
|
||||
| 8 | Security Audit | security/SKILL.md | Phase 1–5 (optional) |
|
||||
| 9 | Performance Test | test-run/SKILL.md (perf mode) | Steps 1–5 (optional) |
|
||||
| 10 | Deploy | deploy/SKILL.md | Step 1–7 |
|
||||
| 11 | Retrospective | retrospective/SKILL.md (cycle-end mode) | Steps 1–4 |
|
||||
| 5 | Test Spec | test-spec/SKILL.md | Phases 1–4 |
|
||||
| 6 | Decompose | decompose/SKILL.md (implementation task decomposition) | Step 1 + Step 1.5 + Step 2 + Step 4 |
|
||||
| 7 | Implement | implement/SKILL.md | Batch loop + Product Implementation Completeness Gate |
|
||||
| 8 | Code Testability Revision | refactor/SKILL.md (guided mode) | Phases 0–7 (conditional) |
|
||||
| 9 | Decompose Tests | decompose/SKILL.md (tests-only) | Step 1t + Step 3 + Step 4 |
|
||||
| 10 | Implement Tests | implement/SKILL.md | (batch-driven, no fixed sub-steps) |
|
||||
| 11 | Run Tests | test-run/SKILL.md | Steps 1–4 |
|
||||
| 12 | Test-Spec Sync | test-spec/SKILL.md (cycle-update mode) | Phase 2 + Phase 3 (scoped) |
|
||||
| 13 | Update Docs | document/SKILL.md (task mode) | Task Steps 0–5 |
|
||||
| 14 | Security Audit | security/SKILL.md | Phase 1–5 (optional) |
|
||||
| 15 | Performance Test | test-run/SKILL.md (perf mode) | Steps 1–5 (optional) |
|
||||
| 16 | Deploy | deploy/SKILL.md | Step 1–7 |
|
||||
| 17 | Retrospective | retrospective/SKILL.md (cycle-end mode) | Steps 1–4 |
|
||||
|
||||
## Detection Rules
|
||||
|
||||
@@ -80,12 +86,12 @@ If `_docs/02_document/` exists but is incomplete (has some artifacts but no `FIN
|
||||
---
|
||||
|
||||
**Step 4 — UI Design (conditional)**
|
||||
Condition (folder fallback): `_docs/02_document/architecture.md` exists AND `_docs/02_tasks/todo/` does not exist or has no task files.
|
||||
Condition (folder fallback): `_docs/02_document/architecture.md` exists AND `_docs/02_document/tests/traceability-matrix.md` does not exist.
|
||||
State-driven: reached by auto-chain from Step 3.
|
||||
|
||||
Action: Read and execute `.cursor/skills/ui-design/SKILL.md`. The skill runs its own **Applicability Check**, which handles UI project detection and the user's A/B choice. It returns one of:
|
||||
|
||||
- `outcome: completed` → mark Step 4 as `completed`, auto-chain to Step 5 (Decompose).
|
||||
- `outcome: completed` → mark Step 4 as `completed`, auto-chain to Step 5 (Test Spec).
|
||||
- `outcome: skipped, reason: not-a-ui-project` → mark Step 4 as `skipped`, auto-chain to Step 5.
|
||||
- `outcome: skipped, reason: user-declined` → mark Step 4 as `skipped`, auto-chain to Step 5.
|
||||
|
||||
@@ -93,34 +99,162 @@ The autodev no longer inlines UI detection heuristics — they live in `ui-desig
|
||||
|
||||
---
|
||||
|
||||
**Step 5 — Decompose**
|
||||
Condition: `_docs/02_document/` contains `architecture.md` AND `_docs/02_document/components/` has at least one component AND `_docs/02_tasks/todo/` does not exist or has no task files
|
||||
**Step 5 — Test Spec**
|
||||
Condition (folder fallback): `_docs/02_document/FINAL_report.md` exists AND `_docs/02_document/architecture.md` exists AND `_docs/02_document/tests/traceability-matrix.md` does not exist.
|
||||
State-driven: reached by auto-chain from Step 4 (completed or skipped).
|
||||
|
||||
Action: Read and execute `.cursor/skills/decompose/SKILL.md`
|
||||
Action: Read and execute `.cursor/skills/test-spec/SKILL.md`.
|
||||
|
||||
This step converts the greenfield problem statement, acceptance criteria, solution, architecture, component docs, and UI design artifacts (if any) into test specifications before implementation begins. The test spec should cover unit, integration, blackbox, and e2e scenarios where those levels are applicable to the project.
|
||||
|
||||
---
|
||||
|
||||
**Step 6 — Decompose**
|
||||
Condition: `_docs/02_document/` contains `architecture.md` AND `_docs/02_document/components/` has at least one component AND `_docs/02_document/tests/traceability-matrix.md` exists AND `_docs/02_tasks/todo/` does not exist or has no implementation task files.
|
||||
|
||||
Action: Invoke `.cursor/skills/decompose/SKILL.md` for **implementation task decomposition**. The greenfield flow selects the implementation entrypoint before handing off: Bootstrap Structure, Module Layout, Component Task Decomposition, and Cross-Task Verification.
|
||||
|
||||
Do not invoke Blackbox Test Task Decomposition from Step 6. Test tasks are intentionally deferred to Step 9 (Decompose Tests) so the first implementation batch stays focused on product functionality and Step 8 can revise testability before test task files exist.
|
||||
|
||||
If `_docs/02_tasks/` subfolders have some task files already, the decompose skill's resumability handles it.
|
||||
|
||||
---
|
||||
|
||||
**Step 6 — Implement**
|
||||
Condition: `_docs/02_tasks/todo/` contains task files AND `_dependencies_table.md` exists AND `_docs/03_implementation/` does not contain any `implementation_report_*.md` file
|
||||
**Step 7 — Implement**
|
||||
Condition: `_docs/02_tasks/todo/` contains implementation task files AND `_dependencies_table.md` exists AND `_docs/03_implementation/` does not contain a valid product implementation report.
|
||||
|
||||
Action: Read and execute `.cursor/skills/implement/SKILL.md`
|
||||
Action: Invoke `.cursor/skills/implement/SKILL.md` with task selection context **Product implementation**.
|
||||
|
||||
The implement skill must run its **Product Implementation Completeness Gate** before it writes any final product implementation report. This gate compares completed product task specs, architecture/component promises, and actual source code so scaffold-only implementations cannot advance to Step 8. A final product implementation report without `_docs/03_implementation/implementation_completeness_cycle[N]_report.md` is incomplete and must not be treated as Step 7 completion.
|
||||
|
||||
If `_docs/03_implementation/` has batch reports, the implement skill detects completed tasks and continues. The FINAL report filename is context-dependent — see implement skill documentation for naming convention.
|
||||
|
||||
For folder fallback, **implementation task files** means task specs that are not test-only specs: exclude `*_test_infrastructure.md` and task specs whose `**Component**` or `**Epic**` identifies `Blackbox Tests`.
|
||||
|
||||
For folder fallback, a **product implementation report** is any `_docs/03_implementation/implementation_report_*.md` file except `_docs/03_implementation/implementation_report_tests.md` and refactor reports. It is valid for greenfield progression only when:
|
||||
- the matching `_docs/03_implementation/implementation_completeness_cycle[N]_report.md` exists,
|
||||
- that completeness report does not contain unresolved `FAIL` classifications, and
|
||||
- `_docs/02_tasks/todo/` contains no pending implementation task files.
|
||||
|
||||
If a product report exists but any of those validity checks fail, treat product implementation as incomplete and stay in Step 7.
|
||||
|
||||
---
|
||||
|
||||
**Step 7 — Run Tests**
|
||||
Condition (folder fallback): `_docs/03_implementation/` contains an `implementation_report_*.md` file.
|
||||
State-driven: reached by auto-chain from Step 6.
|
||||
**Step 8 — Code Testability Revision**
|
||||
Condition (folder fallback): `_docs/03_implementation/` contains a valid product implementation report, `_docs/03_implementation/implementation_completeness_cycle[N]_report.md` exists without unresolved `FAIL` classifications, `_docs/04_refactoring/01-testability-refactoring/testability_assessment.md` does not exist, `_docs/04_refactoring/01-testability-refactoring/testability_changes_summary.md` does not exist, `_docs/03_implementation/implementation_report_tests.md` does not exist, and `_docs/02_tasks/todo/` does not contain test task files.
|
||||
State-driven: reached by auto-chain from Step 7.
|
||||
|
||||
**Purpose**: verify the newly built code can be exercised by the planned tests before writing the test suite. Greenfield code should be testable by design; this step catches accidental hardcoded paths, singletons, direct external service construction, or other implementation choices that would make meaningful tests impossible.
|
||||
|
||||
**Scope — MINIMAL, SURGICAL fixes**: this is not a general refactor. It is the smallest set of changes required to make the implemented code runnable under tests.
|
||||
|
||||
**Allowed changes** in this phase:
|
||||
- Replace hardcoded URLs / file paths / credentials / magic numbers with env vars or constructor arguments.
|
||||
- Extract narrow interfaces for components that need stubbing in tests.
|
||||
- Add optional constructor parameters for dependency injection; default to the existing behavior so callers do not break.
|
||||
- Wrap global singletons in thin accessors that tests can override.
|
||||
- Split a function ONLY when necessary to stub one of its collaborators — do not split for clarity alone.
|
||||
|
||||
**NOT allowed** in this phase (defer to a later refactor task):
|
||||
- Renaming public APIs.
|
||||
- Moving code between files unless strictly required for isolation.
|
||||
- Changing algorithms or business logic.
|
||||
- Restructuring module boundaries or rewriting layers.
|
||||
|
||||
Action: Analyze the codebase against the test specs to determine whether the code can be tested as-is.
|
||||
|
||||
1. Read `_docs/02_document/tests/traceability-matrix.md` and all test scenario files in `_docs/02_document/tests/`.
|
||||
2. For each test scenario, check whether the code under test can be exercised in isolation. Look for:
|
||||
- Hardcoded file paths or directory references
|
||||
- Hardcoded configuration values (URLs, credentials, magic numbers)
|
||||
- Global mutable state that cannot be overridden
|
||||
- Tight coupling to external services without abstraction
|
||||
- Missing dependency injection or non-configurable parameters
|
||||
- Direct file system operations without path configurability
|
||||
- Inline construction of heavy dependencies (models, clients)
|
||||
3. If ALL scenarios are testable as-is:
|
||||
- Create `_docs/04_refactoring/01-testability-refactoring/`
|
||||
- Write `_docs/04_refactoring/01-testability-refactoring/testability_assessment.md` with the scenarios reviewed and outcome "Code is testable — no changes needed"
|
||||
- Mark Step 8 as `completed` with outcome "Code is testable — no changes needed"
|
||||
- Auto-chain to Step 9 (Decompose Tests)
|
||||
4. If testability issues are found:
|
||||
- Create `_docs/04_refactoring/01-testability-refactoring/`
|
||||
- Write `list-of-changes.md` in that directory using the refactor skill template (`.cursor/skills/refactor/templates/list-of-changes.md`), with:
|
||||
- **Mode**: `guided`
|
||||
- **Source**: `autodev-greenfield-testability-analysis`
|
||||
- One change entry per testability issue found (change ID, file paths, problem, proposed change, risk, dependencies). Each entry must fit the allowed-changes list above; reject entries that drift into full refactor territory and log them under "Deferred refactor candidates" instead.
|
||||
- Invoke the refactor skill in **guided mode**: read and execute `.cursor/skills/refactor/SKILL.md` with the `list-of-changes.md` as input
|
||||
- Phase 3 (Safety Net) is skipped for this testability run because the test suite has not been implemented yet
|
||||
- After execution, surface `RUN_DIR/testability_changes_summary.md` to the user via the Choose format (accept / request follow-up) before auto-chaining
|
||||
- Copy or save the accepted summary as `_docs/04_refactoring/01-testability-refactoring/testability_changes_summary.md` so folder fallback can detect Step 8 completion
|
||||
- Mark Step 8 as `completed`
|
||||
- Auto-chain to Step 9 (Decompose Tests)
|
||||
|
||||
---
|
||||
|
||||
**Step 9 — Decompose Tests**
|
||||
Condition (folder fallback): `_docs/02_document/tests/traceability-matrix.md` exists AND workspace contains source code files AND `_docs/03_implementation/` contains a valid product implementation report AND `_docs/03_implementation/implementation_completeness_cycle[N]_report.md` exists without unresolved `FAIL` classifications AND (`_docs/04_refactoring/01-testability-refactoring/testability_assessment.md` exists OR `_docs/04_refactoring/01-testability-refactoring/testability_changes_summary.md` exists) AND (`_docs/02_tasks/todo/` does not exist or has no test task files) AND `_docs/03_implementation/implementation_report_tests.md` does not exist.
|
||||
State-driven: reached by auto-chain from Step 8.
|
||||
|
||||
Action: Read and execute `.cursor/skills/decompose/SKILL.md` in **tests-only mode** (pass `_docs/02_document/tests/` as input). The decompose skill will:
|
||||
1. Run Step 1t (test infrastructure bootstrap)
|
||||
2. Run Step 3 (blackbox/e2e-capable test task decomposition)
|
||||
3. Run Step 4 (cross-verification against test coverage)
|
||||
|
||||
If `_docs/02_tasks/` subfolders have some task files already, the decompose skill's resumability handles it — it appends test tasks alongside existing completed implementation tasks.
|
||||
|
||||
---
|
||||
|
||||
**Step 10 — Implement Tests**
|
||||
Condition (folder fallback): `_docs/02_tasks/todo/` contains test task files AND `_dependencies_table.md` exists AND `_docs/03_implementation/implementation_report_tests.md` does not exist.
|
||||
State-driven: reached by auto-chain from Step 9.
|
||||
|
||||
Action: Invoke `.cursor/skills/implement/SKILL.md` with task selection context **Test implementation**.
|
||||
|
||||
The implement skill reads only test tasks from `_docs/02_tasks/todo/` and implements them.
|
||||
|
||||
If `_docs/03_implementation/` has batch reports, the implement skill detects completed test tasks and continues.
|
||||
|
||||
For folder fallback, **test task files** means `*_test_infrastructure.md` plus task specs whose `**Component**` or `**Epic**` identifies `Blackbox Tests`.
|
||||
|
||||
---
|
||||
|
||||
**Step 11 — Run Tests**
|
||||
Condition (folder fallback): `_docs/03_implementation/implementation_report_tests.md` exists.
|
||||
State-driven: reached by auto-chain from Step 10.
|
||||
|
||||
Action: Read and execute `.cursor/skills/test-run/SKILL.md`
|
||||
|
||||
Verifies the implemented unit, integration, blackbox, and e2e tests pass before proceeding to spec and documentation sync. This is a hard product gate, not a harness-smoke gate: e2e/blackbox tests must exercise the actual implemented system through public runtime boundaries and compare actual outputs against `_docs/00_problem/input_data/expected_results/results_report.md` or referenced machine-readable expected-result files. Stubs are allowed only for external systems outside the product boundary; missing internal product implementation must fail or block the gate and send the flow back to Implement.
|
||||
|
||||
---
|
||||
|
||||
**Step 8 — Security Audit (optional)**
|
||||
State-driven: reached by auto-chain from Step 7.
|
||||
**Step 12 — Test-Spec Sync**
|
||||
State-driven: reached by auto-chain from Step 11. Requires `_docs/02_document/tests/traceability-matrix.md` to exist — if missing, mark Step 12 `skipped` (see Action below).
|
||||
|
||||
Action: Read and execute `.cursor/skills/test-spec/SKILL.md` in **cycle-update mode**. Pass the completed implementation task specs, completed test task specs, and implementation reports as inputs.
|
||||
|
||||
The skill appends implementation-learned acceptance criteria, scenarios, and NFR updates to the existing test-spec files without rewriting unaffected sections. If `traceability-matrix.md` is missing, mark Step 12 as `skipped` — the next `/test-spec` full run will regenerate it.
|
||||
|
||||
After completion, auto-chain to Step 13 (Update Docs).
|
||||
|
||||
---
|
||||
|
||||
**Step 13 — Update Docs**
|
||||
State-driven: reached by auto-chain from Step 12 (completed or skipped). Requires `_docs/02_document/` to contain existing documentation — if missing, mark Step 13 `skipped` (see Action below).
|
||||
|
||||
Action: Read and execute `.cursor/skills/document/SKILL.md` in **Task mode**. Pass all completed implementation and test task spec files plus the implementation reports.
|
||||
|
||||
The document skill in Task mode updates affected module docs, component docs, system-level docs, and test documentation without redoing full discovery, verification, or problem extraction.
|
||||
|
||||
If `_docs/02_document/` does not contain existing docs, mark Step 13 as `skipped`.
|
||||
|
||||
After completion, auto-chain to Step 14 (Security Audit).
|
||||
|
||||
---
|
||||
|
||||
**Step 14 — Security Audit (optional)**
|
||||
State-driven: reached by auto-chain from Step 13 (completed or skipped).
|
||||
|
||||
Action: Apply the **Optional Skill Gate** (`protocols.md` → "Optional Skill Gate") with:
|
||||
- question: `Run security audit before deploy?`
|
||||
@@ -128,12 +262,12 @@ Action: Apply the **Optional Skill Gate** (`protocols.md` → "Optional Skill Ga
|
||||
- option-b-label: `Skip — proceed directly to deploy`
|
||||
- recommendation: `A — catches vulnerabilities before production`
|
||||
- target-skill: `.cursor/skills/security/SKILL.md`
|
||||
- next-step: Step 9 (Performance Test)
|
||||
- next-step: Step 15 (Performance Test)
|
||||
|
||||
---
|
||||
|
||||
**Step 9 — Performance Test (optional)**
|
||||
State-driven: reached by auto-chain from Step 8.
|
||||
**Step 15 — Performance Test (optional)**
|
||||
State-driven: reached by auto-chain from Step 14 (completed or skipped).
|
||||
|
||||
Action: Apply the **Optional Skill Gate** (`protocols.md` → "Optional Skill Gate") with:
|
||||
- question: `Run performance/load tests before deploy?`
|
||||
@@ -141,30 +275,30 @@ Action: Apply the **Optional Skill Gate** (`protocols.md` → "Optional Skill Ga
|
||||
- option-b-label: `Skip — proceed directly to deploy`
|
||||
- recommendation: `A or B — base on whether acceptance criteria include latency, throughput, or load requirements`
|
||||
- target-skill: `.cursor/skills/test-run/SKILL.md` in **perf mode** (the skill handles runner detection, threshold comparison, and its own A/B/C gate on threshold failures)
|
||||
- next-step: Step 10 (Deploy)
|
||||
- next-step: Step 16 (Deploy)
|
||||
|
||||
---
|
||||
|
||||
**Step 10 — Deploy**
|
||||
State-driven: reached by auto-chain from Step 9 (after Step 9 is completed or skipped).
|
||||
**Step 16 — Deploy**
|
||||
State-driven: reached by auto-chain from Step 15 (after Step 15 is completed or skipped).
|
||||
|
||||
Action: Read and execute `.cursor/skills/deploy/SKILL.md`.
|
||||
|
||||
After the deploy skill completes successfully, mark Step 10 as `completed` and auto-chain to Step 11 (Retrospective).
|
||||
After the deploy skill completes successfully, mark Step 16 as `completed` and auto-chain to Step 17 (Retrospective).
|
||||
|
||||
---
|
||||
|
||||
**Step 11 — Retrospective**
|
||||
State-driven: reached by auto-chain from Step 10.
|
||||
**Step 17 — Retrospective**
|
||||
State-driven: reached by auto-chain from Step 16.
|
||||
|
||||
Action: Read and execute `.cursor/skills/retrospective/SKILL.md` in **cycle-end mode**. This closes the cycle's feedback loop by folding metrics into `_docs/06_metrics/retro_<date>.md` and appending the top-3 lessons to `_docs/LESSONS.md`.
|
||||
|
||||
After retrospective completes, mark Step 11 as `completed` and enter "Done" evaluation.
|
||||
After retrospective completes, mark Step 17 as `completed` and enter "Done" evaluation.
|
||||
|
||||
---
|
||||
|
||||
**Done**
|
||||
State-driven: reached by auto-chain from Step 11. (Sanity check: `_docs/04_deploy/` should contain all expected artifacts — containerization.md, ci_cd_pipeline.md, environment_strategy.md, observability.md, deployment_procedures.md, deploy_scripts.md.)
|
||||
State-driven: reached by auto-chain from Step 17. (Sanity check: `_docs/04_deploy/` should contain all expected artifacts — containerization.md, ci_cd_pipeline.md, environment_strategy.md, observability.md, deployment_procedures.md, deploy_scripts.md.)
|
||||
|
||||
Action: Report project completion with summary. Then **rewrite the state file** so the next `/autodev` invocation enters the feature-cycle loop in the existing-code flow:
|
||||
|
||||
@@ -191,47 +325,65 @@ On the next invocation, Flow Resolution rule 1 reads `flow: existing-code` and r
|
||||
| Research (2) | Auto-chain → Research Decision (ask user: another round or proceed?) |
|
||||
| Research Decision → proceed | Auto-chain → Plan (3) |
|
||||
| Plan (3) | Auto-chain → UI Design detection (4) |
|
||||
| UI Design (4, done or skipped) | Auto-chain → Decompose (5) |
|
||||
| Decompose (5) | **Session boundary** — suggest new conversation before Implement |
|
||||
| Implement (6) | Auto-chain → Run Tests (7) |
|
||||
| Run Tests (7, all pass) | Auto-chain → Security Audit choice (8) |
|
||||
| Security Audit (8, done or skipped) | Auto-chain → Performance Test choice (9) |
|
||||
| Performance Test (9, done or skipped) | Auto-chain → Deploy (10) |
|
||||
| Deploy (10) | Auto-chain → Retrospective (11) |
|
||||
| Retrospective (11) | Report completion; rewrite state to existing-code flow, step 9 |
|
||||
| UI Design (4, done or skipped) | Auto-chain → Test Spec (5) |
|
||||
| Test Spec (5) | Auto-chain → Decompose (6) |
|
||||
| Decompose (6) | **Session boundary** — suggest new conversation before Implement |
|
||||
| Implement (7) | Auto-chain only after Product Implementation Completeness Gate passes → Code Testability Revision (8) |
|
||||
| Code Testability Revision (8) | Auto-chain → Decompose Tests (9) |
|
||||
| Decompose Tests (9) | **Session boundary** — suggest new conversation before Implement Tests |
|
||||
| Implement Tests (10) | Auto-chain → Run Tests (11) |
|
||||
| Run Tests (11, all pass) | Auto-chain → Test-Spec Sync (12) |
|
||||
| Test-Spec Sync (12, done or skipped) | Auto-chain → Update Docs (13) |
|
||||
| Update Docs (13, done or skipped) | Auto-chain → Security Audit choice (14) |
|
||||
| Security Audit (14, done or skipped) | Auto-chain → Performance Test choice (15) |
|
||||
| Performance Test (15, done or skipped) | Auto-chain → Deploy (16) |
|
||||
| Deploy (16) | Auto-chain → Retrospective (17) |
|
||||
| Retrospective (17) | Report completion; rewrite state to existing-code flow, step 9 |
|
||||
|
||||
## Status Summary — Step List
|
||||
|
||||
Flow name: `greenfield`. Render using the banner template in `protocols.md` → "Banner Template (authoritative)". No header-suffix, current-suffix, or footer-extras — all empty for this flow.
|
||||
|
||||
| # | Step Name | Extra state tokens (beyond the shared set) |
|
||||
|---|--------------------|--------------------------------------------|
|
||||
| 1 | Problem | — |
|
||||
| 2 | Research | `DONE (N drafts)` |
|
||||
| 3 | Plan | — |
|
||||
| 4 | UI Design | — |
|
||||
| 5 | Decompose | `DONE (N tasks)` |
|
||||
| 6 | Implement | `IN PROGRESS (batch M of ~N)` |
|
||||
| 7 | Run Tests | `DONE (N passed, M failed)` |
|
||||
| 8 | Security Audit | — |
|
||||
| 9 | Performance Test | — |
|
||||
| 10 | Deploy | — |
|
||||
| 11 | Retrospective | — |
|
||||
| # | Step Name | Extra state tokens (beyond the shared set) |
|
||||
|---|-----------------------------|--------------------------------------------|
|
||||
| 1 | Problem | — |
|
||||
| 2 | Research | `DONE (N drafts)` |
|
||||
| 3 | Plan | — |
|
||||
| 4 | UI Design | — |
|
||||
| 5 | Test Spec | — |
|
||||
| 6 | Decompose | `DONE (N tasks)` |
|
||||
| 7 | Implement | `IN PROGRESS (batch M of ~N)` |
|
||||
| 8 | Code Testability Revision | — |
|
||||
| 9 | Decompose Tests | `DONE (N tasks)` |
|
||||
| 10 | Implement Tests | `IN PROGRESS (batch M)` |
|
||||
| 11 | Run Tests | `DONE (N passed, M failed)` |
|
||||
| 12 | Test-Spec Sync | — |
|
||||
| 13 | Update Docs | — |
|
||||
| 14 | Security Audit | — |
|
||||
| 15 | Performance Test | — |
|
||||
| 16 | Deploy | — |
|
||||
| 17 | Retrospective | — |
|
||||
|
||||
All rows also accept the shared state tokens (`DONE`, `IN PROGRESS`, `NOT STARTED`, `FAILED (retry N/3)`); rows 4, 8, 9 additionally accept `SKIPPED`.
|
||||
All rows also accept the shared state tokens (`DONE`, `IN PROGRESS`, `NOT STARTED`, `FAILED (retry N/3)`); rows 4, 12, 13, 14, 15 additionally accept `SKIPPED`.
|
||||
|
||||
Row rendering format (step-number column is right-padded to 2 characters for alignment):
|
||||
|
||||
```
|
||||
Step 1 Problem [<state token>]
|
||||
Step 2 Research [<state token>]
|
||||
Step 3 Plan [<state token>]
|
||||
Step 4 UI Design [<state token>]
|
||||
Step 5 Decompose [<state token>]
|
||||
Step 6 Implement [<state token>]
|
||||
Step 7 Run Tests [<state token>]
|
||||
Step 8 Security Audit [<state token>]
|
||||
Step 9 Performance Test [<state token>]
|
||||
Step 10 Deploy [<state token>]
|
||||
Step 11 Retrospective [<state token>]
|
||||
Step 1 Problem [<state token>]
|
||||
Step 2 Research [<state token>]
|
||||
Step 3 Plan [<state token>]
|
||||
Step 4 UI Design [<state token>]
|
||||
Step 5 Test Spec [<state token>]
|
||||
Step 6 Decompose [<state token>]
|
||||
Step 7 Implement [<state token>]
|
||||
Step 8 Code Testability Rev. [<state token>]
|
||||
Step 9 Decompose Tests [<state token>]
|
||||
Step 10 Implement Tests [<state token>]
|
||||
Step 11 Run Tests [<state token>]
|
||||
Step 12 Test-Spec Sync [<state token>]
|
||||
Step 13 Update Docs [<state token>]
|
||||
Step 14 Security Audit [<state token>]
|
||||
Step 15 Performance Test [<state token>]
|
||||
Step 16 Deploy [<state token>]
|
||||
Step 17 Retrospective [<state token>]
|
||||
```
|
||||
|
||||
@@ -5,7 +5,8 @@ Workflow for **meta-repositories** — repos that aggregate multiple components
|
||||
This flow differs fundamentally from `greenfield` and `existing-code`:
|
||||
|
||||
- **No problem/research/plan phases** — meta-repos don't build features, they coordinate existing ones
|
||||
- **No test spec / implement / run tests** — the meta-repo has no code to test
|
||||
- **No test spec / run tests** — the meta-repo has no code to test
|
||||
- **`implement` is scoped to suite-level work only** — cross-repo concerns, repo/folder renames, suite-root infra additions (e.g., `.gitmodules`, `_infra/`, suite `e2e/`). Per-component implementation lives in each component's own workspace `/autodev` cycle. The meta-repo's implement step (Step 3.5) executes only when `_docs/tasks/todo/` is non-empty AND the user explicitly opts in; placement is **before** the sync skills so subsequent Doc/E2E/CICD sync propagates the post-implementation state.
|
||||
- **No `_docs/00_problem/` artifacts** — documentation target is `_docs/*.md` unified docs, not per-feature `_docs/NN_feature/` folders
|
||||
- **Primary artifact is `_docs/_repo-config.yaml`** — generated by `monorepo-discover`, read by every other step
|
||||
|
||||
@@ -15,8 +16,11 @@ This flow differs fundamentally from `greenfield` and `existing-code`:
|
||||
|------|------|-----------|-------------------|
|
||||
| 1 | Discover | monorepo-discover/SKILL.md | Phase 1–10 |
|
||||
| 2 | Config Review | (human checkpoint, no sub-skill) | — |
|
||||
| 2.5 | Glossary & Architecture Vision | (inline, no sub-skill) | Steps 1–5 |
|
||||
| 3 | Status | monorepo-status/SKILL.md | Sections 1–5 |
|
||||
| 3.5 | Suite Implement | implement/SKILL.md (suite-level invocation context) | Steps 1–14 + 16 (Step 14.5 + Step 15 skipped); conditional on `_docs/tasks/todo/` non-empty AND user opt-in |
|
||||
| 4 | Document Sync | monorepo-document/SKILL.md | Phase 1–7 (conditional on doc drift) |
|
||||
| 4.5 | Integration Test Sync | monorepo-e2e/SKILL.md | Phase 1–6 (conditional on suite-e2e drift; skipped if `suite_e2e:` block absent in config) |
|
||||
| 5 | CICD Sync | monorepo-cicd/SKILL.md | Phase 1–7 (conditional on CI drift) |
|
||||
| 6 | Loop | (auto-return to Step 3 on next invocation) | — |
|
||||
|
||||
@@ -58,17 +62,121 @@ Action: This is a **hard session boundary**. The skill cannot proceed until a hu
|
||||
══════════════════════════════════════
|
||||
```
|
||||
|
||||
- If user picks A → verify `confirmed_by_user: true` is now set in the config. If still `false`, re-ask. If true, auto-chain to **Step 3 (Status)**.
|
||||
- If user picks A → verify `confirmed_by_user: true` is now set in the config. If still `false`, re-ask. If true, auto-chain to **Step 2.5 (Glossary & Architecture Vision)**.
|
||||
- If user picks B → mark Step 2 as `in_progress`, update state file, end the session. Tell the user to invoke `/autodev` again after reviewing.
|
||||
|
||||
**Do NOT auto-flip `confirmed_by_user`.** Only the human does that.
|
||||
|
||||
---
|
||||
|
||||
**Step 2.5 — Glossary & Architecture Vision** (one-shot)
|
||||
|
||||
Condition (folder fallback): `_docs/_repo-config.yaml` exists AND `confirmed_by_user: true` AND (`_docs/glossary.md` does NOT exist OR the cross-cutting architecture doc identified in `docs.cross_cutting` does NOT contain a `## Architecture Vision` section).
|
||||
State-driven: reached by auto-chain from Step 2 (user picked A).
|
||||
|
||||
**Goal**: Capture meta-repo-wide terminology and the user's architecture vision **once**, after the config is confirmed but before any sync skill runs. Without this, `monorepo-document` will faithfully propagate per-component changes but never surface a unified mental model of the meta-repo to the user, and the AI will keep re-inferring the same project terminology on every invocation.
|
||||
|
||||
**Why inline (no sub-skill)**: `monorepo-discover` is hard-guarded to write only `_repo-config.yaml`; `monorepo-document` only edits *existing* docs. Glossary and architecture-vision creation is a first-time, user-confirmed write that crosses both guarantees, so it lives directly in the flow.
|
||||
|
||||
**Inputs**:
|
||||
- `_docs/_repo-config.yaml` (component list, doc map, conventions, assumptions log)
|
||||
- Cross-cutting docs listed under `docs.cross_cutting` (existing architecture doc, if any)
|
||||
- Each component's `primary_doc` (read-only, for terminology + responsibility extraction)
|
||||
- Root `README.md` if `repo.root_readme` is referenced
|
||||
|
||||
**Outputs**:
|
||||
- `_docs/glossary.md` (or `<docs.root>/glossary.md` if `docs.root` ≠ `_docs/`) — NEW
|
||||
- The cross-cutting architecture doc updated in place: a `## Architecture Vision` section is prepended (or merged into an existing "Vision" / "Overview" heading)
|
||||
- One new entry appended to `_docs/_repo-config.yaml` under `assumptions_log:` recording the run
|
||||
- A new top-level config entry: `glossary_doc: <path>` so future `monorepo-status` and `monorepo-document` runs treat the glossary as a known cross-cutting doc
|
||||
|
||||
**Procedure**:
|
||||
|
||||
1. **Draft glossary** from `_repo-config.yaml` + each component's primary doc. Include:
|
||||
- Component codenames as they appear in the config (`name` field) and any rename pairs the user noted in `unresolved:` resolutions
|
||||
- Domain terms that recur across ≥2 component docs
|
||||
- Acronyms / abbreviations
|
||||
- Convention names from `conventions:` (e.g., commit prefix, deployment tier names)
|
||||
- Stakeholder personas if cross-cutting docs reference them
|
||||
Each entry: one-line definition + source (`source: components.<name>.primary_doc` or `source: _repo-config.yaml conventions`). Skip generic terms.
|
||||
|
||||
2. **Draft architecture vision** from the meta-repo perspective:
|
||||
- **One paragraph**: what the system as a whole is, what each component contributes, the runtime topology (one binary / N services / N clients + 1 server / hybrid), how components communicate (REST / gRPC / queue / DB-shared / file-shared)
|
||||
- **Components & responsibilities** (one-line each), pulled directly from `_repo-config.yaml` `components:` list
|
||||
- **Cross-cutting concerns ownership**: which doc owns which concern (auth, schema, deployment, etc.) — pulled from `docs.cross_cutting[].owns`
|
||||
- **Architectural principles / non-negotiables** the user has implied across components (e.g., "all components share a single Postgres", "submodules own their own CI", "deployment is per-tier, not per-component")
|
||||
- **Open questions / structural drift signals**: components missing from `docs.cross_cutting`, components in registry but not in config (registry mismatch), or contradictions between component primary docs
|
||||
|
||||
3. **Present condensed view** to the user (NOT the full draft files):
|
||||
|
||||
```
|
||||
══════════════════════════════════════
|
||||
REVIEW: Meta-Repo Glossary + Architecture Vision
|
||||
══════════════════════════════════════
|
||||
Glossary (N terms drafted from config + component docs):
|
||||
- <Term>: <one-line definition>
|
||||
- ...
|
||||
|
||||
Architecture Vision — meta-repo level:
|
||||
<one-paragraph synopsis>
|
||||
|
||||
Components / responsibilities:
|
||||
- <component>: <one-line>
|
||||
- ...
|
||||
|
||||
Cross-cutting ownership:
|
||||
- <concern> → <doc>
|
||||
- ...
|
||||
|
||||
Principles / non-negotiables:
|
||||
- <principle>
|
||||
- ...
|
||||
|
||||
Open questions / drift signals:
|
||||
- <q1>
|
||||
- <q2>
|
||||
══════════════════════════════════════
|
||||
A) Looks correct — write the files
|
||||
B) Add / correct entries (provide diffs)
|
||||
C) Resolve open questions / drift signals first
|
||||
══════════════════════════════════════
|
||||
Recommendation: pick C if drift signals exist;
|
||||
otherwise B if components or principles
|
||||
don't match your intent; A only when
|
||||
the inferred vision is exactly right.
|
||||
══════════════════════════════════════
|
||||
```
|
||||
|
||||
4. **Iterate**:
|
||||
- On B → integrate the user's diffs/additions, re-present, loop until A.
|
||||
- On C → ask the listed open questions in one batch, integrate answers, re-present.
|
||||
- **Do NOT proceed to step 5 until the user picks A.**
|
||||
|
||||
5. **Save**:
|
||||
- Write `_docs/glossary.md` (alphabetical) with `**Status**: confirmed-by-user` + date.
|
||||
- Update the cross-cutting architecture doc identified in `docs.cross_cutting` (or create one at `_docs/00_architecture.md` if none exists and the user's option-B input named one): prepend `## Architecture Vision` with the confirmed paragraph + components + ownership + principles. Preserve every existing H2 below verbatim.
|
||||
- Append to `_docs/_repo-config.yaml`:
|
||||
- Top-level `glossary_doc: <path-relative-to-repo-root>` (sibling of `docs.root`)
|
||||
- New `assumptions_log:` entry: `{ date: <today>, skill: autodev-meta-repo Step 2.5, run_notes: "Captured glossary + architecture vision", assumptions: [...] }`
|
||||
- Do NOT flip any `confirmed: false` → `confirmed: true` in the config; this step writes its own confirmed artifact, it does not retroactively confirm config inferences.
|
||||
|
||||
**Self-verification**:
|
||||
- [ ] Every glossary entry traces to either the config or a component primary doc
|
||||
- [ ] Every component listed in the vision matches a `components:` entry in the config
|
||||
- [ ] All open questions are answered or explicitly deferred (with the user's acknowledgement)
|
||||
- [ ] The cross-cutting architecture doc still contains every H2 it had before this step
|
||||
- [ ] User picked option A on the latest condensed view
|
||||
|
||||
**Idempotency**: if both `_docs/glossary.md` exists AND the architecture doc already has a `## Architecture Vision` section, this step is **skipped on re-invocation**. To refresh, the user invokes `/autodev` after deleting `glossary.md` (or running `monorepo-discover` with structural changes that justify a re-confirmation).
|
||||
|
||||
After completion, auto-chain to **Step 3 (Status)**.
|
||||
|
||||
---
|
||||
|
||||
**Step 3 — Status**
|
||||
|
||||
Condition (folder fallback): `_docs/_repo-config.yaml` exists AND `confirmed_by_user: true`.
|
||||
State-driven: reached by auto-chain from Step 2 (user picked A), or entered on any re-invocation after a completed cycle.
|
||||
Condition (folder fallback): `_docs/_repo-config.yaml` exists AND `confirmed_by_user: true` AND (`_docs/glossary.md` exists OR `glossary_doc:` is recorded in the config).
|
||||
State-driven: reached by auto-chain from Step 2.5, or entered on any re-invocation after a completed cycle.
|
||||
|
||||
Action: Read and execute `.cursor/skills/monorepo-status/SKILL.md`.
|
||||
|
||||
@@ -78,11 +186,16 @@ The status report identifies:
|
||||
- Registry/config mismatches
|
||||
- Unresolved questions
|
||||
|
||||
Based on the report, auto-chain branches:
|
||||
Based on the report, auto-chain branches in this evaluation order (first match wins):
|
||||
|
||||
- If **doc drift** found → auto-chain to **Step 4 (Document Sync)**
|
||||
- Else if **CI drift** (only) found → auto-chain to **Step 5 (CICD Sync)**
|
||||
- Else if **registry mismatch** found (new components not in config) → present Choose format:
|
||||
1. **Registry mismatch** (new components not in config, or config component not in registry) → present the Choose format below FIRST. After the user resolves it (A: refresh discover, B: onboard, C: continue with mismatch acknowledged), proceed to the next rule. This rule has priority because a stale config would mislead Step 3.5's ownership-envelope synthesis and any sync skill's component scope.
|
||||
2. **Pre-routing gate (Step 3.5 detection)** — check `_docs/tasks/todo/` for suite-level task files (`*.md` excluding files starting with `_`). If ≥1 task is present, auto-chain to **Step 3.5 (Suite Implement)**. After Step 3.5 returns (regardless of A/B outcome), the post-implement re-status applies rules 3–6 below to the post-implementation state.
|
||||
3. If **doc drift** found → auto-chain to **Step 4 (Document Sync)**
|
||||
4. Else if **CI drift** (only) found → auto-chain to **Step 5 (CICD Sync)**
|
||||
5. Else if **suite-e2e drift** (only) found → auto-chain to **Step 4.5 (Integration Test Sync)** (only when `suite_e2e:` block exists in config)
|
||||
6. Else → **workflow done for this cycle**.
|
||||
|
||||
**Registry mismatch Choose format** (rule 1):
|
||||
|
||||
```
|
||||
══════════════════════════════════════
|
||||
@@ -99,7 +212,134 @@ Based on the report, auto-chain branches:
|
||||
══════════════════════════════════════
|
||||
```
|
||||
|
||||
- Else → **workflow done for this cycle**. Report "No drift. Meta-repo is in sync." Loop waits for next invocation.
|
||||
When rule 6 fires (no drift, no todo tasks), report "No drift. Meta-repo is in sync." and end the cycle. Loop waits for next invocation.
|
||||
|
||||
---
|
||||
|
||||
**Step 3.5 — Suite Implement**
|
||||
|
||||
Condition (folder fallback): `_docs/tasks/todo/` exists AND contains ≥1 file matching `*.md` excluding files starting with `_` (e.g., `_dependencies_table.md` is excluded by convention).
|
||||
|
||||
State-driven: reached by auto-chain from Step 3 when the pre-routing gate detected todo tasks. Inserted **before** the sync skills (Step 4 / 4.5 / 5) by deliberate design: implementing renames + cross-repo edits first means the subsequent sync skills propagate the actual landed state rather than the pre-change state, avoiding a second cycle to fix downstream drift.
|
||||
|
||||
**Skip condition**: `_docs/tasks/todo/` is empty, missing, or contains only `_*` files. In that case Step 3.5 is skipped entirely and the cycle proceeds with Step 3's existing drift-based routing.
|
||||
|
||||
**Goal**: Execute suite-level implementation tasks — cross-repo concerns (e.g., `autopilot` + `ui` + suite `e2e/` cutover in a coordinated change-set), folder renames (e.g., `git mv flights missions` + `.gitmodules` edit + `_infra/` path refs), and suite-root infrastructure additions (e.g., `_infra/dev/docker-compose.dev.yml`). Per-component implementation work stays in each component's own workspace `/autodev` cycle.
|
||||
|
||||
**Why this exists**: the meta-repo's existing sync skills (`monorepo-document`, `monorepo-cicd`, `monorepo-e2e`) only **propagate** changes that already landed. They cannot **execute** a task spec. Without Step 3.5, suite-level tickets like AZ-543 (B4 repo rename) or AZ-506 (new dev compose) have no flow path forward — they require operator action outside autodev.
|
||||
|
||||
**Inputs**:
|
||||
|
||||
- `_docs/tasks/todo/*.md` (excluding `_*`) — task specs in the existing format (`Task` / `Component` / `Dependencies` / `Acceptance criteria` headers)
|
||||
- `_docs/_repo-config.yaml` — `components[].path` list, used to compute the suite-level OWNED envelope (workspace root EXCLUDING any path under a component's folder)
|
||||
- `_docs/tasks/_dependencies_table.md` — synthesized by this step if missing (see Procedure)
|
||||
- `_docs/tasks/_suite_module_layout.md` — synthesized by this step if missing (see Procedure)
|
||||
|
||||
**Procedure**:
|
||||
|
||||
1. **Detection (already done by Step 3 pre-routing gate)**. List task files in `_docs/tasks/todo/` (excluding `_*`). If 0 → skip Step 3.5. If ≥1 → continue.
|
||||
|
||||
2. **Present Choose**:
|
||||
|
||||
```
|
||||
══════════════════════════════════════
|
||||
DECISION REQUIRED: <N> suite-level task(s) in _docs/tasks/todo/
|
||||
══════════════════════════════════════
|
||||
Task(s) detected:
|
||||
- AZ-XXX: <title> (deps: <list or "—">)
|
||||
- AZ-YYY: <title> (deps: <list or "—">)
|
||||
...
|
||||
|
||||
A) Run implement skill on these task(s) now (then continue to Doc / E2E / CICD sync)
|
||||
B) Skip implement this cycle — continue to Doc / E2E / CICD sync without executing tasks
|
||||
C) Pause — review the tasks before deciding (end session, no state changes)
|
||||
══════════════════════════════════════
|
||||
Recommendation: A — running implement BEFORE syncs means subsequent
|
||||
sync skills propagate the post-implementation state.
|
||||
B is appropriate when tasks are blocked on user input
|
||||
or external coordination. C when the tasks themselves
|
||||
need owner clarification before execution.
|
||||
══════════════════════════════════════
|
||||
```
|
||||
|
||||
3. **On user A — Pre-flight**:
|
||||
|
||||
a. **Working tree clean check**. Run `git status --porcelain`. If non-empty, surface to the user with a Choose A/B/C identical to the implement skill's prerequisite gate (commit/stash manually; agent commits as `chore: WIP pre-implement`; abort).
|
||||
|
||||
b. **Synthesize `_docs/tasks/_dependencies_table.md`** if missing. Parse each in-scope task's `Dependencies:` field. Write a minimal table of the form:
|
||||
|
||||
```markdown
|
||||
# Suite-Level Task Dependencies
|
||||
|
||||
| Task ID | Depends on | Notes |
|
||||
|---------|------------|-------|
|
||||
| AZ-XXX | (none) | — |
|
||||
| AZ-YYY | AZ-XXX | — |
|
||||
```
|
||||
|
||||
If a task lists a dependency that is neither in `todo/` nor `done/`, log a warning in the synthesized file but do not block — implement skill's Step 1 (Parse) will surface the issue if it actually blocks execution.
|
||||
|
||||
c. **Synthesize `_docs/tasks/_suite_module_layout.md`** if missing. Default content:
|
||||
|
||||
```markdown
|
||||
# Suite-Level Module Layout (synthetic)
|
||||
|
||||
Generated by autodev meta-repo Step 3.5. The suite root has no per-feature decomposition; ownership is defined at the component-boundary level only.
|
||||
|
||||
## Per-Component Mapping
|
||||
|
||||
| Component | Owns | Imports from |
|
||||
|-----------|----------------------------------|--------------|
|
||||
| suite | (workspace root) excluding any path listed under `_repo-config.yaml.components[].path` | (read-only) every component's primary doc + `_docs/*.md` |
|
||||
|
||||
Suite-level tasks operate on: `.gitmodules`, `_infra/**`, `_docs/**` (excluding `_docs/tasks/_*` regenerated files), root `README.md`, `e2e/**` (suite e2e harness only).
|
||||
|
||||
Forbidden paths for suite-level tasks: `<component>/**` for every component listed in `_repo-config.yaml.components[].path` — those edits live in the component's own workspace `/autodev` cycle.
|
||||
```
|
||||
|
||||
d. **Prepare invocation context**:
|
||||
|
||||
```
|
||||
suite_level: true
|
||||
TASKS_DIR: _docs/tasks/
|
||||
module_layout_path: _docs/tasks/_suite_module_layout.md
|
||||
```
|
||||
|
||||
4. **Invoke implement skill**. Read and execute `.cursor/skills/implement/SKILL.md` with the prepared context. The skill's "Suite-level invocation context" subsection (added in tandem with this flow change) honors the three flags above and skips:
|
||||
|
||||
- Step 14.5 (cumulative code review) — no `architecture_compliance_baseline.md` exists at the suite level; cross-task drift is captured by the next `monorepo-status` cycle instead.
|
||||
- Step 15 (Product Implementation Completeness Gate) — the gate's inputs (`_docs/02_document/architecture.md`, `system-flows.md`, `components/*/description.md`) do not exist in the meta-repo artifact layout. Suite tasks are infrastructure / coordination work, not feature implementation.
|
||||
|
||||
All other implement skill steps (1–14, 16) execute unchanged. Tracker integration (Step 5: In Progress, Step 12: In Testing) runs normally.
|
||||
|
||||
5. **Post-implement re-status**. After the implement skill completes (last batch committed, all originally-todo tasks moved to `_docs/tasks/done/`), silently re-run Step 3's drift detection logic — do NOT re-render the full Status report; just re-evaluate the drift signals against the post-implementation tree. Then auto-chain per the post-implementation drift findings:
|
||||
|
||||
- Doc drift → Step 4 (Document Sync)
|
||||
- Suite-e2e drift only → Step 4.5
|
||||
- CI drift only → Step 5
|
||||
- No drift → cycle complete
|
||||
|
||||
Note: the post-implement re-status is exactly why Step 3.5 is placed before sync. A repo rename will typically introduce doc + CI drift; the next invocation of Step 4 / Step 5 catches it on the same cycle.
|
||||
|
||||
6. **On user B (skip)** → mark Step 3.5 `skipped` in state file. Apply Step 3's original drift-based routing (compute from the pre-Step-3.5 Status report).
|
||||
|
||||
7. **On user C (pause)** → end session. Update state to `step: 3.5, status: in_progress, sub_step: {phase: 0, name: awaiting-task-review, detail: "<N> tasks pending review"}`. Tell the user to invoke `/autodev` again after deciding. **Do NOT modify any files** — pre-flight has not run yet.
|
||||
|
||||
**Self-verification** (executed before invoking implement):
|
||||
|
||||
- [ ] Working tree is clean (or user explicitly chose B in the WIP-stash sub-Choose)
|
||||
- [ ] `_docs/tasks/_dependencies_table.md` exists (synthesized if it didn't)
|
||||
- [ ] `_docs/tasks/_suite_module_layout.md` exists (synthesized if it didn't)
|
||||
- [ ] All in-scope task files have a `Component:` field (skip + report any that don't — don't guess ownership)
|
||||
- [ ] Tracker availability gate satisfied per `protocols.md` (or `tracker: local` previously chosen)
|
||||
|
||||
**Failure handling**:
|
||||
|
||||
- If implement returns FAILED → standard Failure Handling (`protocols.md`): retry up to 3 times, then escalate.
|
||||
- If implement is interrupted mid-batch → next invocation re-detects via the implement skill's resumability protocol (read latest `_docs/03_implementation/suite_batch_*.md`). Step 3.5 itself is reentrant: on re-entry, if `todo/` still has tasks, it presents the Choose again with the remaining set.
|
||||
- **Half-applied state risk** (acknowledged): if implement is interrupted between commits, the working tree is clean at the last commit boundary but the in-flight batch is lost. The user is responsible for inspecting and re-invoking. This is intentional — automated rollback of suite-level renames + `.gitmodules` edits is more dangerous than a human-driven recovery.
|
||||
|
||||
**Idempotency**: if `_docs/tasks/todo/` becomes empty after this step (all tasks moved to `done/`), the next `/autodev` invocation skips Step 3.5 entirely and proceeds with normal Status → sync flow.
|
||||
|
||||
---
|
||||
|
||||
@@ -115,6 +355,28 @@ The skill:
|
||||
3. Applies doc edits
|
||||
4. Skips any component with unconfirmed mapping (M5), reports
|
||||
|
||||
After completion:
|
||||
- If the status report ALSO flagged suite-e2e drift → auto-chain to **Step 4.5 (Integration Test Sync)**
|
||||
- Else if the status report ALSO flagged CI drift → auto-chain to **Step 5 (CICD Sync)**
|
||||
- Else → end cycle, report done
|
||||
|
||||
---
|
||||
|
||||
**Step 4.5 — Integration Test Sync**
|
||||
|
||||
State-driven: reached by auto-chain from Step 3 (when status report flagged suite-e2e drift and no doc drift) or from Step 4 (when both doc and suite-e2e drift were flagged).
|
||||
|
||||
**Skip condition**: if `_docs/_repo-config.yaml` has no `suite_e2e:` block, this step is skipped entirely — there's no harness to sync. The status report should not flag suite-e2e drift in that case; if it does, that's a status-skill bug.
|
||||
|
||||
Action: Read and execute `.cursor/skills/monorepo-e2e/SKILL.md` with scope = components flagged by status.
|
||||
|
||||
The skill:
|
||||
1. Verifies every path under `suite_e2e.*` exists (binary fixtures excepted — see the skill's Phase 1)
|
||||
2. Classifies each flagged change against the suite-e2e impact table
|
||||
3. Applies edits to `e2e/docker-compose.suite-e2e.yml`, `e2e/fixtures/init.sql`, `e2e/fixtures/expected_detections.json` metadata, and `e2e/runner/tests/*.spec.ts` selectors as needed
|
||||
4. Bumps baseline `fixture_version` with a `-stale` suffix and appends a `_docs/_process_leftovers/` entry whenever the detection model revision changes (binary fixture cannot be regenerated automatically)
|
||||
5. Reports synced files; does not run the suite e2e itself
|
||||
|
||||
After completion:
|
||||
- If the status report ALSO flagged CI drift → auto-chain to **Step 5 (CICD Sync)**
|
||||
- Else → end cycle, report done
|
||||
@@ -123,11 +385,11 @@ After completion:
|
||||
|
||||
**Step 5 — CICD Sync**
|
||||
|
||||
State-driven: reached by auto-chain from Step 3 (when status report flagged CI drift and no doc drift) or from Step 4 (when both doc and CI drift were flagged).
|
||||
State-driven: reached by auto-chain from Step 3 (when status report flagged CI drift and no doc/suite-e2e drift), Step 4, or Step 4.5.
|
||||
|
||||
Action: Read and execute `.cursor/skills/monorepo-cicd/SKILL.md` with scope = components flagged by status.
|
||||
|
||||
After completion, end cycle. Report files updated across both doc and CI sync.
|
||||
After completion, end cycle. Report files updated across doc, suite-e2e, and CI sync.
|
||||
|
||||
---
|
||||
|
||||
@@ -156,14 +418,24 @@ After onboarding completes, the config is updated. Auto-chain back to **Step 3 (
|
||||
| Completed Step | Next Action |
|
||||
|---------------|-------------|
|
||||
| Discover (1) | Auto-chain → Config Review (2) |
|
||||
| Config Review (2, user picked A, confirmed_by_user: true) | Auto-chain → Status (3) |
|
||||
| Config Review (2, user picked A, confirmed_by_user: true) | Auto-chain → Glossary & Architecture Vision (2.5) |
|
||||
| Config Review (2, user picked B) | **Session boundary** — end session, await re-invocation |
|
||||
| Status (3, doc drift) | Auto-chain → Document Sync (4) |
|
||||
| Status (3, CI drift only) | Auto-chain → CICD Sync (5) |
|
||||
| Status (3, no drift) | **Cycle complete** — end session, await re-invocation |
|
||||
| Glossary & Architecture Vision (2.5) | Auto-chain → Status (3) |
|
||||
| Status (3, todo tasks present) | Auto-chain → Suite Implement (3.5) — pre-routing gate fires before drift-based routing |
|
||||
| Status (3, no todo tasks, doc drift) | Auto-chain → Document Sync (4) |
|
||||
| Status (3, no todo tasks, suite-e2e drift only) | Auto-chain → Integration Test Sync (4.5) |
|
||||
| Status (3, no todo tasks, CI drift only) | Auto-chain → CICD Sync (5) |
|
||||
| Status (3, no todo tasks, no drift) | **Cycle complete** — end session, await re-invocation |
|
||||
| Status (3, registry mismatch) | Ask user (A: discover, B: onboard, C: continue) |
|
||||
| Document Sync (4) + CI drift pending | Auto-chain → CICD Sync (5) |
|
||||
| Document Sync (4) + no CI drift | **Cycle complete** |
|
||||
| Suite Implement (3.5, user picked A, success) | Silent re-status; auto-chain per post-implementation drift (Step 4 / 4.5 / 5 / cycle complete) |
|
||||
| Suite Implement (3.5, user picked B) | Mark `skipped`; auto-chain per Step 3's original drift findings |
|
||||
| Suite Implement (3.5, user picked C) | **Session boundary** — end session, await re-invocation |
|
||||
| Suite Implement (3.5, FAILED ×3) | Standard Failure Handling escalation (`protocols.md`) |
|
||||
| Document Sync (4) + suite-e2e drift pending | Auto-chain → Integration Test Sync (4.5) |
|
||||
| Document Sync (4) + CI drift only pending | Auto-chain → CICD Sync (5) |
|
||||
| Document Sync (4) + no further drift | **Cycle complete** |
|
||||
| Integration Test Sync (4.5) + CI drift pending | Auto-chain → CICD Sync (5) |
|
||||
| Integration Test Sync (4.5) + no CI drift | **Cycle complete** |
|
||||
| CICD Sync (5) | **Cycle complete** |
|
||||
|
||||
## Status Summary — Step List
|
||||
@@ -178,30 +450,40 @@ Flow-specific slot values:
|
||||
Config: _docs/_repo-config.yaml [confirmed_by_user: <true|false>, last_updated: <date>]
|
||||
```
|
||||
|
||||
| # | Step Name | Extra state tokens (beyond the shared set) |
|
||||
|---|------------------|--------------------------------------------|
|
||||
| 1 | Discover | — |
|
||||
| 2 | Config Review | `IN PROGRESS (awaiting human)` |
|
||||
| 3 | Status | `DONE (no drift)`, `DONE (N drifts)` |
|
||||
| 4 | Document Sync | `DONE (N docs)`, `SKIPPED (no doc drift)` |
|
||||
| 5 | CICD Sync | `DONE (N files)`, `SKIPPED (no CI drift)` |
|
||||
| # | Step Name | Extra state tokens (beyond the shared set) |
|
||||
|---|------------------------------------|--------------------------------------------|
|
||||
| 1 | Discover | — |
|
||||
| 2 | Config Review | `IN PROGRESS (awaiting human)` |
|
||||
| 2.5 | Glossary & Architecture Vision | `SKIPPED (already captured)` |
|
||||
| 3 | Status | `DONE (no drift)`, `DONE (N drifts)` |
|
||||
| 3.5 | Suite Implement | `DONE (N tasks)`, `SKIPPED (no todo tasks)`, `SKIPPED (user picked B)`, `IN PROGRESS (batch M of ~N)`, `IN PROGRESS (awaiting-task-review)` |
|
||||
| 4 | Document Sync | `DONE (N docs)`, `SKIPPED (no doc drift)` |
|
||||
| 4.5 | Integration Test Sync | `DONE (N files)`, `SKIPPED (no suite-e2e drift)`, `SKIPPED (no suite_e2e config block)` |
|
||||
| 5 | CICD Sync | `DONE (N files)`, `SKIPPED (no CI drift)` |
|
||||
|
||||
All rows accept the shared state tokens (`DONE`, `IN PROGRESS`, `NOT STARTED`, `FAILED (retry N/3)`); rows 4 and 5 additionally accept `SKIPPED`.
|
||||
All rows accept the shared state tokens (`DONE`, `IN PROGRESS`, `NOT STARTED`, `FAILED (retry N/3)`); rows 2.5, 3.5, 4, 4.5, and 5 additionally accept `SKIPPED`.
|
||||
|
||||
Row rendering format:
|
||||
|
||||
```
|
||||
Step 1 Discover [<state token>]
|
||||
Step 2 Config Review [<state token>]
|
||||
Step 3 Status [<state token>]
|
||||
Step 4 Document Sync [<state token>]
|
||||
Step 5 CICD Sync [<state token>]
|
||||
Step 1 Discover [<state token>]
|
||||
Step 2 Config Review [<state token>]
|
||||
Step 2.5 Glossary & Architecture Vision [<state token>]
|
||||
Step 3 Status [<state token>]
|
||||
Step 3.5 Suite Implement [<state token>]
|
||||
Step 4 Document Sync [<state token>]
|
||||
Step 4.5 Integration Test Sync [<state token>]
|
||||
Step 5 CICD Sync [<state token>]
|
||||
```
|
||||
|
||||
## Notes for the meta-repo flow
|
||||
|
||||
- **No session boundary except Step 2**: unlike existing-code flow (which has boundaries around decompose), meta-repo flow only pauses at config review. Syncing is fast enough to complete in one session.
|
||||
- **Session boundaries**: Step 2 (Config Review pending), Step 2.5 (one-shot glossary/vision review), and Step 3.5 (when user picks C "Pause"). Step 3.5's A/B picks do NOT cross a session boundary — they auto-chain to syncs in the same session.
|
||||
- **Cyclical, not terminal**: no "done forever" state. Each invocation completes a drift cycle; next invocation starts fresh.
|
||||
- **No tracker integration**: this flow does NOT create Jira/ADO tickets. Maintenance is not a feature — if a feature-level ticket spans the meta-repo's concerns, it lives in the per-component workspace.
|
||||
- **Tracker integration scope**: this flow does NOT create Jira/ADO tickets in its sync skills (Status / Document Sync / E2E / CICD). Step 3.5 (Suite Implement) IS tracker-integrated — it transitions existing tickets In Progress → In Testing per the implement skill's standard tracker handling. Suite-level tickets are authored manually by the operator (typically as children of an Epic that spans multiple components, like AZ-539); the flow doesn't auto-create them.
|
||||
- **Per-component vs. suite-level work**:
|
||||
- Tickets that touch component source code (`<component>/src/**`) belong in that component's own workspace `/autodev` cycle. The meta-repo flow does NOT execute them.
|
||||
- Tickets that touch suite-root paths only (`.gitmodules`, `_infra/**`, suite `e2e/**`, root `README.md`, suite `_docs/**` outside `tasks/_*`) are eligible for Step 3.5.
|
||||
- Tickets that span both (e.g., AZ-550 B11 consumer cutover, which touches `autopilot/`, `ui/`, AND suite `e2e/`) are NOT executable from a single workspace by design — split the ticket so the suite-level slice can run in Step 3.5 and the component slices run in their owning workspaces.
|
||||
- **Onboarding is opt-in**: never auto-onboarded. User must explicitly request.
|
||||
- **Failure handling**: uses the same retry/escalation protocol as other flows (see `protocols.md`).
|
||||
|
||||
@@ -110,9 +110,11 @@ Before entering a step from this table for the first time in a session, verify t
|
||||
| Flow | Step | Sub-Step | Tracker Action |
|
||||
|------|------|----------|----------------|
|
||||
| greenfield | Plan | Step 6 — Epics | Create epics for each component |
|
||||
| greenfield | Decompose | Step 1 + Step 2 + Step 3 — All tasks | Create ticket per task, link to epic |
|
||||
| greenfield | Decompose | Implementation decomposition Step 1 + Step 2 — Product tasks | Create ticket per product task, link to epic |
|
||||
| greenfield | Decompose Tests | Step 1t + Step 3 — All test tasks | Create ticket per task, link to epic |
|
||||
| existing-code | Decompose Tests | Step 1t + Step 3 — All test tasks | Create ticket per task, link to epic |
|
||||
| existing-code | New Task | Step 7 — Ticket | Create ticket per task, link to epic |
|
||||
| meta-repo | Suite Implement | Step 3.5 — implement skill Step 5 / Step 12 | Transition existing tickets In Progress → In Testing per implement skill (does NOT create new tickets — operator authors them) |
|
||||
|
||||
### State File Marker
|
||||
|
||||
@@ -138,7 +140,7 @@ One retry ladder covers all failure modes: explicit failure returned by a sub-sk
|
||||
|
||||
Treat the sub-skill as **failed** when ANY of the following is observed:
|
||||
|
||||
- The sub-skill explicitly returns a failed result (including blocked subagents, auto-fix loop exhaustion, prerequisite violations).
|
||||
- The sub-skill explicitly returns a failed result (including blocked tasks, auto-fix loop exhaustion, prerequisite violations).
|
||||
- **Stuck signals**: the same artifact is rewritten 3+ times without meaningful change; the sub-skill re-asks a question that was already answered; no new artifact has been saved despite active execution.
|
||||
|
||||
### Retry ladder
|
||||
@@ -291,7 +293,7 @@ For steps that produce `_docs/` artifacts (problem, research, plan, decompose, d
|
||||
|
||||
## Debug Protocol
|
||||
|
||||
When the implement skill's auto-fix loop fails (code review FAIL after 2 auto-fix attempts) or an implementer subagent reports a blocker, the user is asked to intervene. This protocol guides the debugging process. (Retry budget and escalation are covered by Failure Handling above; this section is about *how* to diagnose once the user has been looped in.)
|
||||
When the implement skill's auto-fix loop fails (code review FAIL after 2 auto-fix attempts) or a task reports a blocker, the user is asked to intervene. This protocol guides the debugging process. (Retry budget and escalation are covered by Failure Handling above; this section is about *how* to diagnose once the user has been looped in.)
|
||||
|
||||
### Structured Debugging Workflow
|
||||
|
||||
@@ -387,7 +389,7 @@ The banner shell is defined here once. Each flow file contributes only its step-
|
||||
where `<state token>` comes from the state-token set defined per row in the flow's step-list table.
|
||||
- `<current-suffix>` — optional, flow-specific. The existing-code flow appends ` (cycle <N>)` when `state.cycle > 1`; other flows leave it empty.
|
||||
- `Retry:` row — omit entirely when `retry_count` is 0. Include it with `<N>/3` otherwise.
|
||||
- `<footer-extras>` — optional, flow-specific. The meta-repo flow adds a `Config:` line with `_docs/_repo-config.yaml` state; other flows leave it empty.
|
||||
- `<footer-extras>` — optional, flow-specific. The meta-repo flow adds a `Config:` line with `_docs/_repo-config.yaml` state; other flows leave it empty unless **parent suite docs** apply: if `<workspace-root>/../docs` exists and is a directory, append `Suite docs (parent): <absolute path>` on its own line (or `Suite docs (parent): absent` is **not** required — omit when missing). This line is orthogonal to flow-specific footer lines; both may appear.
|
||||
|
||||
### State token set (shared)
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ The autodev persists its position to `_docs/_autodev_state.md`. This is a lightw
|
||||
|
||||
## Current Step
|
||||
flow: [greenfield | existing-code | meta-repo]
|
||||
step: [1-11 for greenfield, 1-17 for existing-code, 1-6 for meta-repo, or "done"]
|
||||
step: [1-17 for greenfield, 1-17 for existing-code, 1-6 for meta-repo (incl. fractional 2.5 and 3.5), or "done"]
|
||||
name: [step name from the active flow's Step Reference Table]
|
||||
status: [not_started / in_progress / completed / skipped / failed]
|
||||
sub_step:
|
||||
@@ -82,6 +82,19 @@ retry_count: 0
|
||||
cycle: 1
|
||||
```
|
||||
|
||||
```
|
||||
flow: meta-repo
|
||||
step: 3.5
|
||||
name: Suite Implement
|
||||
status: in_progress
|
||||
sub_step:
|
||||
phase: 7
|
||||
name: batch-loop
|
||||
detail: "AZ-543 batch 1 of 1; suite-level"
|
||||
retry_count: 0
|
||||
cycle: 1
|
||||
```
|
||||
|
||||
```
|
||||
flow: existing-code
|
||||
step: 10
|
||||
@@ -100,7 +113,7 @@ cycle: 3
|
||||
1. **Create** on the first autodev invocation (after state detection determines Step 1)
|
||||
2. **Update** after every change — this includes: batch completion, sub-step progress, step completion, session boundary, failed retry, or any meaningful state transition. The state file must always reflect the current reality.
|
||||
3. **Read** as the first action on every invocation — before folder scanning
|
||||
4. **Cross-check**: verify against actual `_docs/` folder contents. If they disagree, trust the folder structure and update the state file
|
||||
4. **Cross-check**: verify against actual `_docs/` folder contents. If they disagree, trust the folder structure and update the state file. **Parent suite `docs/`**: on every invocation, also probe `<workspace-root>/../docs` (the parent directory’s `docs` folder — typical suite-level shared documentation next to a component repo). If it exists, mention it in the Status Summary footer per `protocols.md`; use it only as supplemental reading context unless a flow step explicitly ties detection to it. It never replaces workspace `_docs/` for step detection by default.
|
||||
5. **Never delete** the state file
|
||||
6. **Retry tracking**: increment `retry_count` on each failed auto-retry; reset to `0` on success. If `retry_count` reaches 3, set `status: failed`
|
||||
7. **Failed state on re-entry**: if `status: failed` with `retry_count: 3`, do NOT auto-retry — present the issue to the user first
|
||||
|
||||
@@ -209,7 +209,7 @@ Bug, Spec-Gap, Security, Performance, Maintainability, Style, Scope, Architectur
|
||||
|
||||
The `/implement` skill invokes this skill after each batch completes:
|
||||
|
||||
1. Collects changed files from all implementer agents in the batch
|
||||
1. Collects changed files from all tasks implemented in the batch
|
||||
2. Passes task spec paths + changed files to this skill
|
||||
3. If verdict is FAIL — presents findings to user (BLOCKING), user fixes or confirms
|
||||
4. If verdict is PASS or PASS_WITH_WARNINGS — proceeds automatically (findings shown as info)
|
||||
@@ -221,7 +221,7 @@ The `/implement` skill invokes this skill after each batch completes:
|
||||
| Input | Type | Source | Required |
|
||||
|-------|------|--------|----------|
|
||||
| `task_specs` | list of file paths | Task `.md` files from `_docs/02_tasks/todo/` for the current batch | Yes |
|
||||
| `changed_files` | list of file paths | Files modified by implementer agents (from `git diff` or agent reports) | Yes |
|
||||
| `changed_files` | list of file paths | Files modified by the tasks in the batch (from `git diff`) | Yes |
|
||||
| `batch_number` | integer | Current batch number (for report naming) | Yes |
|
||||
| `project_restrictions` | file path | `_docs/00_problem/restrictions.md` | If exists |
|
||||
| `solution_overview` | file path | `_docs/01_solution/solution.md` | If exists |
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
name: decompose
|
||||
description: |
|
||||
Decompose planned components into atomic implementable tasks with bootstrap structure plan.
|
||||
4-step workflow: bootstrap structure plan, component task decomposition, blackbox test task decomposition, and cross-task verification.
|
||||
Supports full decomposition (_docs/ structure), single component mode, and tests-only mode.
|
||||
Workflow entrypoints: implementation task decomposition, single component decomposition, and tests-only decomposition.
|
||||
The invoking flow decides which entrypoint to run; this skill executes that selected sequence.
|
||||
Trigger phrases:
|
||||
- "decompose", "decompose features", "feature decomposition"
|
||||
- "task decomposition", "break down components"
|
||||
@@ -20,7 +20,7 @@ Decompose planned components into atomic, implementable task specs with a bootst
|
||||
|
||||
## Core Principles
|
||||
|
||||
- **Atomic tasks**: each task does one thing; if it exceeds 8 complexity points, split it
|
||||
- **Atomic tasks**: each task does one thing; if it exceeds 5 complexity points, split it
|
||||
- **Behavioral specs, not implementation plans**: describe what the system should do, not how to build it
|
||||
- **Flat structure**: all tasks are tracker-ID-prefixed files in TASKS_DIR — no component subdirectories
|
||||
- **Save immediately**: write artifacts to disk after each task; never accumulate unsaved work
|
||||
@@ -30,14 +30,15 @@ Decompose planned components into atomic, implementable task specs with a bootst
|
||||
|
||||
## Context Resolution
|
||||
|
||||
Determine the operating mode based on invocation before any other logic runs.
|
||||
Resolve the selected entrypoint from the invocation context before any other logic runs. The caller decides whether this is implementation, single component, or tests-only decomposition; this skill only executes the selected sequence.
|
||||
|
||||
**Default** (no explicit input file provided):
|
||||
**Implementation task decomposition** (default; selected by flows before invoking this skill):
|
||||
|
||||
- DOCUMENT_DIR: `_docs/02_document/`
|
||||
- TASKS_DIR: `_docs/02_tasks/`
|
||||
- TASKS_TODO: `_docs/02_tasks/todo/`
|
||||
- Reads from: `_docs/00_problem/`, `_docs/01_solution/`, DOCUMENT_DIR
|
||||
- Produces only implementation tasks. Blackbox/e2e test task files are produced only when the invoking flow selects tests-only decomposition.
|
||||
|
||||
**Single component mode** (provided file is within `_docs/02_document/` and inside a `components/` subdirectory):
|
||||
|
||||
@@ -55,24 +56,24 @@ Determine the operating mode based on invocation before any other logic runs.
|
||||
- TESTS_DIR: `DOCUMENT_DIR/tests/`
|
||||
- Reads from: `_docs/00_problem/`, `_docs/01_solution/`, TESTS_DIR
|
||||
|
||||
Announce the detected mode and resolved paths to the user before proceeding.
|
||||
Announce the selected entrypoint and resolved paths to the user before proceeding.
|
||||
|
||||
### Step Applicability by Mode
|
||||
|
||||
| Step | File | Default | Single | Tests-only |
|
||||
|------|------|:-------:|:------:|:----------:|
|
||||
| Step | File | Implementation | Single | Tests-only |
|
||||
|------|------|:--------------:|:------:|:----------:|
|
||||
| 1 Bootstrap Structure | `steps/01_bootstrap-structure.md` | ✓ | — | — |
|
||||
| 1t Test Infrastructure | `steps/01t_test-infrastructure.md` | — | — | ✓ |
|
||||
| 1.5 Module Layout | `steps/01-5_module-layout.md` | ✓ | — | — |
|
||||
| 2 Task Decomposition | `steps/02_task-decomposition.md` | ✓ | ✓ | — |
|
||||
| 3 Blackbox Test Tasks | `steps/03_blackbox-test-decomposition.md` | ✓ | — | ✓ |
|
||||
| 3 Blackbox Test Tasks | `steps/03_blackbox-test-decomposition.md` | — | — | ✓ |
|
||||
| 4 Cross-Verification | `steps/04_cross-verification.md` | ✓ | — | ✓ |
|
||||
|
||||
## Input Specification
|
||||
|
||||
### Required Files
|
||||
|
||||
**Default:**
|
||||
**Implementation task decomposition:**
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
@@ -80,10 +81,11 @@ Announce the detected mode and resolved paths to the user before proceeding.
|
||||
| `_docs/00_problem/restrictions.md` | Constraints and limitations |
|
||||
| `_docs/00_problem/acceptance_criteria.md` | Measurable acceptance criteria |
|
||||
| `_docs/01_solution/solution.md` | Finalized solution |
|
||||
| `DOCUMENT_DIR/architecture.md` | Architecture from plan skill |
|
||||
| `DOCUMENT_DIR/architecture.md` | Architecture from plan/document skill (must contain a `## Architecture Vision` H2 — confirmed user intent) |
|
||||
| `DOCUMENT_DIR/glossary.md` | Project terminology (confirmed by user in plan Phase 2a.0 or document Step 4.5). Use it to keep task names, component references, and AC wording consistent with the user's vocabulary |
|
||||
| `DOCUMENT_DIR/system-flows.md` | System flows from plan skill |
|
||||
| `DOCUMENT_DIR/components/[##]_[name]/description.md` | Component specs from plan skill |
|
||||
| `DOCUMENT_DIR/tests/` | Blackbox test specs from plan skill |
|
||||
| `DOCUMENT_DIR/tests/` | Optional product acceptance context from test-spec skill; do not create test task files from it in this entrypoint |
|
||||
|
||||
**Single component mode:**
|
||||
|
||||
@@ -110,7 +112,7 @@ Announce the detected mode and resolved paths to the user before proceeding.
|
||||
|
||||
### Prerequisite Checks (BLOCKING)
|
||||
|
||||
**Default:**
|
||||
**Implementation task decomposition:**
|
||||
|
||||
1. DOCUMENT_DIR contains `architecture.md` and `components/` — **STOP if missing**
|
||||
2. Create TASKS_DIR and TASKS_TODO if they do not exist
|
||||
@@ -144,6 +146,8 @@ TASKS_DIR/
|
||||
|
||||
**Naming convention**: Each task file is initially saved in `TASKS_TODO/` with a temporary numeric prefix (`[##]_[short_name].md`). After creating the work item ticket, rename the file to use the work item ticket ID as prefix (`[TRACKER-ID]_[short_name].md`). For example: `todo/01_initial_structure.md` → `todo/AZ-42_initial_structure.md`.
|
||||
|
||||
If tracker availability fails, follow `.cursor/rules/tracker.mdc` before continuing. Only when the user explicitly chooses `tracker: local` may the numeric prefix remain; in that mode set `Tracker: pending` and `Epic: pending` in the task header and keep the task eligible for later tracker sync.
|
||||
|
||||
### Save Timing
|
||||
|
||||
| Step | Save immediately after | Filename |
|
||||
@@ -165,11 +169,11 @@ If TASKS_DIR subfolders already contain task files:
|
||||
|
||||
## Progress Tracking
|
||||
|
||||
At the start of execution, create a TodoWrite with all applicable steps for the detected mode (see Step Applicability table). Update status as each step/component completes.
|
||||
At the start of execution, create a TodoWrite with all applicable steps for the selected entrypoint (see Step Applicability table). Update status as each step/component completes.
|
||||
|
||||
## Workflow
|
||||
|
||||
### Step 1: Bootstrap Structure Plan (default mode only)
|
||||
### Step 1: Bootstrap Structure Plan (implementation mode only)
|
||||
|
||||
Read and follow `steps/01_bootstrap-structure.md`.
|
||||
|
||||
@@ -181,25 +185,25 @@ Read and follow `steps/01t_test-infrastructure.md`.
|
||||
|
||||
---
|
||||
|
||||
### Step 1.5: Module Layout (default mode only)
|
||||
### Step 1.5: Module Layout (implementation mode only)
|
||||
|
||||
Read and follow `steps/01-5_module-layout.md`.
|
||||
|
||||
---
|
||||
|
||||
### Step 2: Task Decomposition (default and single component modes)
|
||||
### Step 2: Task Decomposition (implementation and single component modes)
|
||||
|
||||
Read and follow `steps/02_task-decomposition.md`.
|
||||
|
||||
---
|
||||
|
||||
### Step 3: Blackbox Test Task Decomposition (default and tests-only modes)
|
||||
### Step 3: Blackbox Test Task Decomposition (tests-only mode only)
|
||||
|
||||
Read and follow `steps/03_blackbox-test-decomposition.md`.
|
||||
|
||||
---
|
||||
|
||||
### Step 4: Cross-Task Verification (default and tests-only modes)
|
||||
### Step 4: Cross-Task Verification (implementation and tests-only modes)
|
||||
|
||||
Read and follow `steps/04_cross-verification.md`.
|
||||
|
||||
@@ -207,7 +211,7 @@ Read and follow `steps/04_cross-verification.md`.
|
||||
|
||||
- **Coding during decomposition**: this workflow produces specs, never code
|
||||
- **Over-splitting**: don't create many tasks if the component is simple — 1 task is fine
|
||||
- **Tasks exceeding 8 points**: split them; no task should be too complex for a single implementer
|
||||
- **Tasks exceeding 5 points**: split them; no task should be too complex for a single implementer
|
||||
- **Cross-component tasks**: each task belongs to exactly one component
|
||||
- **Skipping BLOCKING gates**: never proceed past a BLOCKING marker without user confirmation
|
||||
- **Creating git branches**: branch creation is an implementation concern, not a decomposition one
|
||||
@@ -220,7 +224,7 @@ Read and follow `steps/04_cross-verification.md`.
|
||||
| Situation | Action |
|
||||
|-----------|--------|
|
||||
| Ambiguous component boundaries | ASK user |
|
||||
| Task complexity exceeds 8 points after splitting | ASK user |
|
||||
| Task complexity exceeds 5 points after splitting | ASK user |
|
||||
| Missing component specs in DOCUMENT_DIR | ASK user |
|
||||
| Cross-component dependency conflict | ASK user |
|
||||
| Tracker epic not found for a component | ASK user for Epic ID |
|
||||
@@ -232,15 +236,14 @@ Read and follow `steps/04_cross-verification.md`.
|
||||
┌────────────────────────────────────────────────────────────────┐
|
||||
│ Task Decomposition (Multi-Mode) │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ CONTEXT: Resolve mode (default / single component / tests-only) │
|
||||
│ CONTEXT: Invoke the selected entrypoint (implementation / single / tests-only) │
|
||||
│ │
|
||||
│ DEFAULT MODE: │
|
||||
│ IMPLEMENTATION TASK DECOMPOSITION: │
|
||||
│ 1. Bootstrap Structure → steps/01_bootstrap-structure.md │
|
||||
│ [BLOCKING: user confirms structure] │
|
||||
│ 1.5 Module Layout → steps/01-5_module-layout.md │
|
||||
│ [BLOCKING: user confirms layout] │
|
||||
│ 2. Component Tasks → steps/02_task-decomposition.md │
|
||||
│ 3. Blackbox Tests → steps/03_blackbox-test-decomposition.md │
|
||||
│ 4. Cross-Verification → steps/04_cross-verification.md │
|
||||
│ [BLOCKING: user confirms dependencies] │
|
||||
│ │
|
||||
|
||||
@@ -26,7 +26,7 @@ For each component (or the single provided component):
|
||||
4. Do not create tasks for other components — only tasks for the current component
|
||||
5. Each task should be atomic, containing 1 API or a list of semantically connected APIs
|
||||
6. Write each task spec using `templates/task.md`
|
||||
7. Estimate complexity per task (1, 2, 3, 5, 8 points); no task should exceed 8 points — split if it does
|
||||
7. Estimate complexity per task (1, 2, 3, 5 points); no task should exceed 5 points — split if it does
|
||||
8. Note task dependencies (referencing tracker IDs of already-created dependency tasks, e.g., `AZ-42_initial_structure`)
|
||||
9. **Cross-cutting rule**: if a concern spans ≥2 components (logging, config loading, auth/authZ, error envelope, telemetry, feature flags, i18n), create ONE shared task under the cross-cutting epic. Per-component tasks declare it as a dependency and consume it; they MUST NOT re-implement it locally. Duplicate local implementations are an `Architecture` finding (High) in code-review Phase 7 and a `Maintainability` finding in Phase 6.
|
||||
10. **Shared-models / shared-API rule**: classify the task as shared if ANY of the following is true:
|
||||
@@ -43,16 +43,32 @@ For each component (or the single provided component):
|
||||
Consumers read the contract file, not the producer's task spec. This prevents interface drift when the producer's implementation detail leaks into consumers.
|
||||
11. **Immediately after writing each task file**: create a work item ticket, link it to the component's epic, write the work item ticket ID and Epic ID back into the task header, then rename the file from `todo/[##]_[short_name].md` to `todo/[TRACKER-ID]_[short_name].md`.
|
||||
|
||||
## Runtime Completeness Decomposition Gate
|
||||
|
||||
Before Step 2 is considered complete, scan `architecture.md`, `system-flows.md`, component descriptions, and the solution for named internal runtime capabilities and dependencies. Examples include BASALT/OpenVINS/Kimera, FAISS, DINOv2, ONNX/TensorRT, ALIKED/DISK, LightGlue, RANSAC, PostGIS, MAVLink emission, FDR rollover, and any "A-Z" user-visible pipeline.
|
||||
|
||||
For every named internal capability:
|
||||
|
||||
1. Ensure at least one implementation task explicitly owns the production integration or production algorithm.
|
||||
2. Do not treat "define protocol", "create adapter boundary", "add deterministic fallback", "create scaffold", or "prepare native bridge" as implementation of the capability unless the architecture explicitly says the real capability is out of scope.
|
||||
3. If a capability needs external hardware/data to verify, still create the production implementation task. Verification may be hardware-gated later; implementation must not be omitted.
|
||||
4. Add a `## Runtime Completeness` section to any affected task with:
|
||||
- named capability/dependency,
|
||||
- production code that must exist,
|
||||
- allowed external stubs, if any,
|
||||
- unacceptable substitutes such as fake/deterministic/internal stubs.
|
||||
|
||||
## Self-verification (per component)
|
||||
|
||||
- [ ] Every task is atomic (single concern)
|
||||
- [ ] No task exceeds 8 complexity points
|
||||
- [ ] No task exceeds 5 complexity points
|
||||
- [ ] Task dependencies reference correct tracker IDs
|
||||
- [ ] Tasks cover all interfaces defined in the component spec
|
||||
- [ ] No tasks duplicate work from other components
|
||||
- [ ] Every task has a work item ticket linked to the correct epic
|
||||
- [ ] Every shared-models / shared-API task has a contract file at `_docs/02_document/contracts/<component>/<name>.md` and a `## Contract` section linking to it
|
||||
- [ ] Every cross-cutting concern appears exactly once as a shared task, not N per-component copies
|
||||
- [ ] Every named internal runtime capability has a production implementation task, not only an interface/scaffold/fallback task
|
||||
|
||||
## Save action
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Step 3: Blackbox Test Task Decomposition (default and tests-only modes)
|
||||
# Step 3: Blackbox Test Task Decomposition (tests-only mode only)
|
||||
|
||||
**Role**: Professional Quality Assurance Engineer
|
||||
**Goal**: Decompose blackbox test specs into atomic, implementable task specs.
|
||||
@@ -6,7 +6,6 @@
|
||||
|
||||
## Numbering
|
||||
|
||||
- In default mode: continue sequential numbering from where Step 2 left off.
|
||||
- In tests-only mode: start from 02 (01 is the test infrastructure bootstrap from Step 1t).
|
||||
|
||||
## Steps
|
||||
@@ -14,21 +13,26 @@
|
||||
1. Read all test specs from `DOCUMENT_DIR/tests/` (`blackbox-tests.md`, `performance-tests.md`, `resilience-tests.md`, `security-tests.md`, `resource-limit-tests.md`)
|
||||
2. Group related test scenarios into atomic tasks (e.g., one task per test category or per component under test)
|
||||
3. Each task should reference the specific test scenarios it implements and the environment/test-data specs
|
||||
4. Dependencies:
|
||||
- In default mode: blackbox test tasks depend on the component implementation tasks they exercise
|
||||
4. Add a **System Under Test Boundary** section to every e2e/blackbox test task:
|
||||
- The test must drive the product through public runtime boundaries and compare actual outputs to `_docs/00_problem/input_data/expected_results/results_report.md` and any referenced machine-readable expected-result files.
|
||||
- Stubs are allowed only for external systems outside the product boundary: flight controller/SITL, QGC observer, satellite-provider/Suite service, physical Jetson hardware, physical camera, licensed public datasets, and network services.
|
||||
- Stubs, fakes, deterministic fallbacks, monkeypatches, or direct imports are not allowed for internal product modules that the scenario is meant to validate, such as VIO, safety/anchor wrapper, satellite retrieval, anchor verification, tile manager, MAVLink output adapter, or FDR.
|
||||
- If an internal module is not implemented, the test must fail/block as missing product implementation; it must not pass by replacing that module with a test stub.
|
||||
5. Dependencies:
|
||||
- In tests-only mode: blackbox test tasks depend on the test infrastructure bootstrap task (Step 1t)
|
||||
5. Write each task spec using `templates/task.md`
|
||||
6. Estimate complexity per task (1, 2, 3, 5, 8 points); no task should exceed 8 points — split if it does
|
||||
7. Note task dependencies (referencing tracker IDs of already-created dependency tasks)
|
||||
8. **Immediately after writing each task file**: create a work item ticket under the "Blackbox Tests" epic, write the work item ticket ID and Epic ID back into the task header, then rename the file from `todo/[##]_[short_name].md` to `todo/[TRACKER-ID]_[short_name].md`.
|
||||
6. Write each task spec using `templates/task.md`
|
||||
7. Estimate complexity per task (1, 2, 3, 5 points); no task should exceed 5 points — split if it does
|
||||
8. Note task dependencies (referencing tracker IDs of already-created dependency tasks)
|
||||
9. **Immediately after writing each task file**: create a work item ticket under the "Blackbox Tests" epic, write the work item ticket ID and Epic ID back into the task header, then rename the file from `todo/[##]_[short_name].md` to `todo/[TRACKER-ID]_[short_name].md`.
|
||||
|
||||
## Self-verification
|
||||
|
||||
- [ ] Every scenario from `tests/blackbox-tests.md` is covered by a task
|
||||
- [ ] Every scenario from `tests/performance-tests.md`, `tests/resilience-tests.md`, `tests/security-tests.md`, and `tests/resource-limit-tests.md` is covered by a task
|
||||
- [ ] No task exceeds 8 complexity points
|
||||
- [ ] Dependencies correctly reference the dependency tasks (component tasks in default mode, test infrastructure in tests-only mode)
|
||||
- [ ] No task exceeds 5 complexity points
|
||||
- [ ] Dependencies correctly reference the test infrastructure task
|
||||
- [ ] Every task has a work item ticket linked to the "Blackbox Tests" epic
|
||||
- [ ] Every e2e/blackbox task forbids internal product stubs/fakes and requires comparison against expected-results artifacts
|
||||
|
||||
## Save action
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Step 4: Cross-Task Verification (default and tests-only modes)
|
||||
# Step 4: Cross-Task Verification (implementation and tests-only modes)
|
||||
|
||||
**Role**: Professional software architect and analyst
|
||||
**Goal**: Verify task consistency and produce `_dependencies_table.md`.
|
||||
@@ -8,17 +8,20 @@
|
||||
|
||||
1. Verify task dependencies across all tasks are consistent
|
||||
2. Check no gaps:
|
||||
- In default mode: every interface in `architecture.md` has tasks covering it
|
||||
- In implementation mode: every product interface in `architecture.md` has implementation task coverage
|
||||
- In tests-only mode: every test scenario in `traceability-matrix.md` is covered by a task
|
||||
- In implementation mode: every named internal runtime capability/dependency from architecture, solution, system flows, and component descriptions has a production implementation task, not only an interface/scaffold/fallback task
|
||||
- In tests-only mode: every e2e/blackbox task has a System Under Test Boundary section that forbids stubbing internal product modules and requires comparison to expected-results artifacts
|
||||
3. Check no overlaps: tasks don't duplicate work
|
||||
4. Check no circular dependencies in the task graph
|
||||
5. Produce `_dependencies_table.md` using `templates/dependencies-table.md`
|
||||
|
||||
## Self-verification
|
||||
|
||||
### Default mode
|
||||
### Implementation mode
|
||||
|
||||
- [ ] Every architecture interface is covered by at least one task
|
||||
- [ ] Every product interface in `architecture.md` is covered by at least one implementation task
|
||||
- [ ] Every named internal runtime capability has a production implementation task
|
||||
- [ ] No circular dependencies in the task graph
|
||||
- [ ] Cross-component dependencies are explicitly noted in affected task specs
|
||||
- [ ] `_dependencies_table.md` contains every task with correct dependencies
|
||||
@@ -26,6 +29,7 @@
|
||||
### Tests-only mode
|
||||
|
||||
- [ ] Every test scenario from `traceability-matrix.md` "Covered" entries has a corresponding task
|
||||
- [ ] Every e2e/blackbox task validates actual product behavior and allows stubs only for external systems
|
||||
- [ ] No circular dependencies in the task graph
|
||||
- [ ] Test task dependencies reference the test infrastructure bootstrap
|
||||
- [ ] `_dependencies_table.md` contains every task with correct dependencies
|
||||
|
||||
@@ -28,4 +28,4 @@ Use this template after cross-task verification. Save as `TASKS_DIR/_dependencie
|
||||
- Dependencies column lists tracker IDs (e.g., "AZ-43, AZ-44") or "None"
|
||||
- No circular dependencies allowed
|
||||
- Tasks should be listed in recommended execution order
|
||||
- The `/implement` skill reads this table to compute parallel batches
|
||||
- The `/implement` skill reads this table to compute dependency-aware batches; task execution remains sequential
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Module Layout Template
|
||||
|
||||
The module layout is the **authoritative file-ownership map** used by the `/implement` skill to assign OWNED / READ-ONLY / FORBIDDEN files to implementer subagents. It is derived from `_docs/02_document/architecture.md` and the component specs at `_docs/02_document/components/`, and it follows the target language's standard project-layout conventions.
|
||||
The module layout is the **authoritative file-ownership map** used by the `/implement` skill to assign OWNED / READ-ONLY / FORBIDDEN files to each task. It is derived from `_docs/02_document/architecture.md` and the component specs at `_docs/02_document/components/`, and it follows the target language's standard project-layout conventions.
|
||||
|
||||
Save as `_docs/02_document/module-layout.md`. This file is produced by the decompose skill (Step 1.5 module layout) and consumed by the implement skill (Step 4 file ownership). Task specs remain purely behavioral — they do NOT carry file paths. The layout is the single place where component → filesystem mapping lives.
|
||||
|
||||
@@ -104,4 +104,4 @@ The implement skill's Step 4 (File Ownership) reads this file and, for each task
|
||||
3. Set READ-ONLY = the Public API files of every component listed in `Imports from`, plus `shared/*` Public API files.
|
||||
4. Set FORBIDDEN = every other component's Owns glob.
|
||||
|
||||
If two tasks in the same batch map to the same component, the implement skill schedules them sequentially (one implementer at a time for that component) to avoid file conflicts on shared internal files.
|
||||
Execution inside a batch is already sequential (one task at a time). This mapping is still required because it enforces scope discipline per task — preventing a task from drifting into files that belong to another component.
|
||||
|
||||
@@ -11,7 +11,7 @@ Save as `TASKS_DIR/[##]_[short_name].md` initially, then rename to `TASKS_DIR/[T
|
||||
**Task**: [TRACKER-ID]_[short_name]
|
||||
**Name**: [short human name]
|
||||
**Description**: [one-line description of what this task delivers]
|
||||
**Complexity**: [1|2|3|5|8] points
|
||||
**Complexity**: [1|2|3|5] points
|
||||
**Dependencies**: [AZ-43_shared_models, AZ-44_db_migrations] or "None"
|
||||
**Component**: [component name for context]
|
||||
**Tracker**: [TASK-ID]
|
||||
@@ -102,8 +102,7 @@ Consumers MUST read that file — not this task spec — to discover the interfa
|
||||
- 2 points: Non-trivial, low complexity, minimal coordination
|
||||
- 3 points: Multi-step, moderate complexity, potential alignment needed
|
||||
- 5 points: Difficult, interconnected logic, medium-high risk
|
||||
- 8 points: High difficulty, high ambiguity or coordination, multiple components
|
||||
- 13 points: Too complex — split into smaller tasks
|
||||
- 8+ points: Too complex — split into smaller tasks
|
||||
|
||||
## Output Guidelines
|
||||
|
||||
|
||||
@@ -26,7 +26,8 @@
|
||||
- Application components under test
|
||||
- Test runner container (black-box, no internal imports)
|
||||
- Isolated database with seed data
|
||||
- All tests runnable via `docker compose -f docker-compose.test.yml up --abort-on-container-exit`
|
||||
- All tests runnable via `docker compose -f docker-compose.test.yml up --abort-on-container-exit --exit-code-from e2e-runner`
|
||||
- See the Woodpecker two-workflow contract in [`../templates/ci_cd_pipeline.md`](../templates/ci_cd_pipeline.md) — the test runner entry point defined here becomes the first step of `.woodpecker/01-test.yml`.
|
||||
7. Define image tagging strategy: `<registry>/<project>/<component>:<git-sha>` for CI, `latest` for local dev only
|
||||
|
||||
## Self-verification
|
||||
|
||||
@@ -85,3 +85,140 @@ Save as `_docs/04_deploy/ci_cd_pipeline.md`.
|
||||
| Deploy success | [Slack] | [team] |
|
||||
| Deploy failure | [Slack/email + PagerDuty] | [on-call] |
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Reference Implementation: Woodpecker CI two-workflow contract
|
||||
|
||||
Use this when the project's CI is **Woodpecker** and the test layout follows the autodev e2e contract from [`../../decompose/templates/test-infrastructure-task.md`](../../decompose/templates/test-infrastructure-task.md) (an `e2e/` folder containing `Dockerfile`, `docker-compose.test.yml`, `conftest.py`, `requirements.txt`, `mocks/`, `fixtures/`, `tests/`).
|
||||
|
||||
The contract is **two workflows in `.woodpecker/`**, scheduled on the same agent label, with the build workflow gated on a successful test run:
|
||||
|
||||
- `.woodpecker/01-test.yml` — runs the e2e contract, publishes `results/report.csv` as an artifact, fails the pipeline on any test failure.
|
||||
- `.woodpecker/02-build-push.yml` — `depends_on: [01-test]`. Builds the image, tags it `${CI_COMMIT_BRANCH}-${TAG_SUFFIX}`, pushes it to the registry. Skipped automatically if test failed.
|
||||
|
||||
The agent label is parameterized via `matrix:` so a single workflow file fans out across architectures: `labels: platform: ${PLATFORM}` routes each matrix entry to the matching agent. Both workflows for a repo must use the same matrix so test and build run on the same machine and share Docker layer cache. New architectures = new matrix entries; never new files.
|
||||
|
||||
### Multi-arch matrix conventions
|
||||
|
||||
| Variable | Meaning | Typical values |
|
||||
|----------|---------|----------------|
|
||||
| `PLATFORM` | Woodpecker agent label — selects which physical machine runs the entry. | `arm64`, `amd64` |
|
||||
| `TAG_SUFFIX` | Image tag suffix appended after the branch name. | `arm`, `amd` |
|
||||
| `DOCKERFILE` *(only when arches need different Dockerfiles)* | Path to the Dockerfile for this entry. | `Dockerfile`, `Dockerfile.jetson` |
|
||||
|
||||
Most repos use the same `Dockerfile` for both arches (multi-arch base images handle the rest), so `DOCKERFILE` can be omitted from the matrix and hardcoded in the build command. Repos with split per-arch Dockerfiles (e.g., `detections` uses `Dockerfile.jetson` on Jetson with TensorRT/CUDA-on-L4T) declare `DOCKERFILE` as a matrix var.
|
||||
|
||||
When only one architecture is currently in use, keep the matrix block with a single entry and the second entry commented out — adding a new arch is then a one-line uncomment, not a structural change.
|
||||
|
||||
### `.woodpecker/01-test.yml`
|
||||
|
||||
```yaml
|
||||
when:
|
||||
event: [push, pull_request, manual]
|
||||
branch: [dev, stage, main]
|
||||
|
||||
matrix:
|
||||
include:
|
||||
- PLATFORM: arm64
|
||||
TAG_SUFFIX: arm
|
||||
# - PLATFORM: amd64
|
||||
# TAG_SUFFIX: amd
|
||||
|
||||
labels:
|
||||
platform: ${PLATFORM}
|
||||
|
||||
steps:
|
||||
- name: e2e
|
||||
image: docker
|
||||
commands:
|
||||
- cd e2e
|
||||
- docker compose -f docker-compose.test.yml up --abort-on-container-exit --exit-code-from e2e-runner --build
|
||||
- docker compose -f docker-compose.test.yml down -v
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
- name: report
|
||||
image: docker
|
||||
when:
|
||||
status: [success, failure]
|
||||
commands:
|
||||
- test -f e2e/results/report.csv && cat e2e/results/report.csv || echo "no report"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
```
|
||||
|
||||
Notes:
|
||||
- `--abort-on-container-exit` shuts the whole compose down as soon as ANY service exits, so a crashed dependency surfaces immediately instead of hanging the runner.
|
||||
- `--exit-code-from e2e-runner` ensures the pipeline's exit code reflects the test runner's, not the SUT's.
|
||||
- The `report` step runs on `[success, failure]` so the report is always published; without this the CSV is lost on red builds.
|
||||
- `down -v` between runs drops mock state and DB volumes — every test run starts clean.
|
||||
|
||||
### `.woodpecker/02-build-push.yml`
|
||||
|
||||
```yaml
|
||||
when:
|
||||
event: [push, manual]
|
||||
branch: [dev, stage, main]
|
||||
|
||||
depends_on:
|
||||
- 01-test
|
||||
|
||||
matrix:
|
||||
include:
|
||||
- PLATFORM: arm64
|
||||
TAG_SUFFIX: arm
|
||||
# - PLATFORM: amd64
|
||||
# TAG_SUFFIX: amd
|
||||
|
||||
labels:
|
||||
platform: ${PLATFORM}
|
||||
|
||||
steps:
|
||||
- name: build-push
|
||||
image: docker
|
||||
environment:
|
||||
REGISTRY_HOST:
|
||||
from_secret: registry_host
|
||||
REGISTRY_USER:
|
||||
from_secret: registry_user
|
||||
REGISTRY_TOKEN:
|
||||
from_secret: registry_token
|
||||
commands:
|
||||
- echo "$REGISTRY_TOKEN" | docker login "$REGISTRY_HOST" -u "$REGISTRY_USER" --password-stdin
|
||||
- export TAG=${CI_COMMIT_BRANCH}-${TAG_SUFFIX}
|
||||
- export BUILD_DATE=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
- |
|
||||
docker build -f Dockerfile \
|
||||
--build-arg CI_COMMIT_SHA=$CI_COMMIT_SHA \
|
||||
--label org.opencontainers.image.revision=$CI_COMMIT_SHA \
|
||||
--label org.opencontainers.image.created=$BUILD_DATE \
|
||||
--label org.opencontainers.image.source=$CI_REPO_URL \
|
||||
-t $REGISTRY_HOST/azaion/<service>:$TAG .
|
||||
- docker push $REGISTRY_HOST/azaion/<service>:$TAG
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
```
|
||||
|
||||
Notes:
|
||||
- `depends_on: [01-test]` is enforced by Woodpecker — a failed `01-test` (any matrix entry) skips this workflow.
|
||||
- The build workflow does NOT trigger on `pull_request` events: PRs get test signal only; pushes to `dev`/`stage`/`main` produce images. Avoids polluting the registry with PR images.
|
||||
- Replace `<service>` with the actual service name (matches the registry namespace pattern `azaion/<service>`).
|
||||
- For repos with split per-arch Dockerfiles, add `DOCKERFILE: Dockerfile.jetson` (or similar) to the matrix entry and substitute `${DOCKERFILE}` for `Dockerfile` in the `docker build -f` line.
|
||||
|
||||
### Variations by stack
|
||||
|
||||
The contract is language-agnostic because the runner is `docker compose`. The Dockerfile inside `e2e/` selects the test framework:
|
||||
|
||||
| Stack | `e2e/Dockerfile` runs |
|
||||
|-------|----------------------|
|
||||
| Python | `pytest --csv=/results/report.csv -v` |
|
||||
| .NET | `dotnet test --logger:"trx;LogFileName=/results/report.trx"` (convert to CSV in a final step if needed) |
|
||||
| Node/UI | `npm test -- --reporters=default --reporters=jest-junit --outputDirectory=/results` |
|
||||
| Rust | `cargo test --no-fail-fast -- --format json > /results/report.json` |
|
||||
|
||||
When the repo has **only unit tests** (no `e2e/docker-compose.test.yml`), drop the compose orchestration and run the native test command directly inside a stack-appropriate image. Keep the same two-workflow split — `01-test.yml` runs unit tests, `02-build-push.yml` is unchanged.
|
||||
|
||||
### Manual-trigger override (test infrastructure not yet validated)
|
||||
|
||||
If a repo ships a complete `e2e/` layout but the test fixtures are not yet validated end-to-end (e.g., expected-results data is still being authored), gate `01-test.yml` on `event: [manual]` only and add a TODO comment pointing to the unblocking task. The `02-build-push.yml` workflow drops its `depends_on` clause for the manual-only window — an explicit and reversible exception, not a permanent split.
|
||||
|
||||
@@ -31,6 +31,7 @@ _docs/
|
||||
│ ├── components.md
|
||||
│ └── flows/
|
||||
├── 04_verification_log.md # Step 4
|
||||
├── glossary.md # Step 4.5 (confirmed-by-user)
|
||||
├── FINAL_report.md # Step 7
|
||||
└── state.json # Resumability
|
||||
```
|
||||
@@ -49,6 +50,7 @@ Maintained in `DOCUMENT_DIR/state.json` for resumability:
|
||||
"modules_remaining": ["services/auth", "api/endpoints"],
|
||||
"module_batch": 1,
|
||||
"components_written": [],
|
||||
"step_4_5_glossary_vision": "not_started",
|
||||
"last_updated": "2026-03-21T14:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
@@ -15,7 +15,7 @@ Covers three related modes that share the same 8-step pipeline:
|
||||
|
||||
## Progress Tracking
|
||||
|
||||
Create a TodoWrite with all steps (0 through 7). Update status as each step completes.
|
||||
Create a TodoWrite with all steps (0 through 7, including the inline Step 2.5 Module Layout Derivation and Step 4.5 Glossary & Architecture Vision). Update status as each step completes.
|
||||
|
||||
## Steps
|
||||
|
||||
@@ -251,7 +251,107 @@ Apply corrections inline to the documents that need them.
|
||||
|
||||
**BLOCKING**: Present verification summary to user. Do NOT proceed until user confirms corrections are acceptable or requests additional fixes.
|
||||
|
||||
**Session boundary**: After verification is confirmed, suggest a session break before proceeding to the synthesis steps (5–7). These steps produce different artifact types and benefit from fresh context:
|
||||
---
|
||||
|
||||
### Step 4.5: Glossary & Architecture Vision (BLOCKING)
|
||||
|
||||
**Role**: Software architect + business analyst
|
||||
**Goal**: Reconcile the AI's verified understanding of the codebase with the user's intended terminology and architecture vision. Existing-code projects often carry domain language and structural intent that is invisible from code alone (synonyms, deprecated names, modules that are "supposed to" be split, components the user thinks of as one logical unit even though they live in two folders). This step makes that intent explicit before any downstream skill (refactor, decompose, new-task) acts on the docs.
|
||||
|
||||
**When this step runs**:
|
||||
- Always, after Step 4 (Verification Pass) — for Full and Resume modes.
|
||||
- **Skipped** in Focus Area mode (the glossary/vision is system-wide; running it on a partial scan would produce a partial glossary). Resume the user once a full pass exists.
|
||||
|
||||
**Inputs** (already on disk after Step 4):
|
||||
- `DOCUMENT_DIR/architecture.md`, `system-flows.md`, `data_model.md`, `deployment/*`
|
||||
- `DOCUMENT_DIR/components/*/description.md`
|
||||
- `DOCUMENT_DIR/modules/*.md`
|
||||
- `DOCUMENT_DIR/04_verification_log.md` (so the AI knows which doc parts are confirmed vs. flagged)
|
||||
|
||||
**Outputs**:
|
||||
- `DOCUMENT_DIR/glossary.md` (NEW)
|
||||
- `DOCUMENT_DIR/architecture.md` updated in place: a new `## Architecture Vision` section is prepended (or merged into an existing "Overview" / "Vision" heading if already present); existing technical sections are preserved verbatim
|
||||
|
||||
**Procedure**:
|
||||
|
||||
1. **Draft glossary** from verified docs:
|
||||
- Domain entities, processes, roles named in module/component docs
|
||||
- Acronyms / abbreviations
|
||||
- Internal codenames (project, service, model names) that recur in the codebase
|
||||
- Synonym pairs the AI noticed (e.g., the codebase uses "flight" but module comments say "mission")
|
||||
- Stakeholder personas if any docs reference them
|
||||
Each entry: one-line definition + source reference (`source: components/03_flights/description.md`). Skip generic CS/industry terms.
|
||||
|
||||
2. **Draft architecture vision** as the AI currently understands the codebase:
|
||||
- **One paragraph**: what the system is, who runs it, the runtime topology shape (monolith / services / pipeline / library / hybrid), and the dominant pattern (e.g., "submodule-based meta-repo with REST + SSE between UI and backend").
|
||||
- **Components & responsibilities** (one-line each), pulled from `components/*/description.md`.
|
||||
- **Major data flows** (one or two sentences each), pulled from `system-flows.md`.
|
||||
- **Architectural principles / non-negotiables** the AI inferred from the code (e.g., "DB-driven config", "all UI traffic via REST + SSE only", "no per-component shared state"). Mark each with `inferred-from: <source>`.
|
||||
- **Open questions / drift signals**: places where the code disagrees with itself, or where the AI cannot tell intent from implementation (e.g., two components doing similar work — is that legacy duplication or deliberate?).
|
||||
|
||||
3. **Present condensed view** to the user (NOT the full draft files — a synopsis only):
|
||||
|
||||
```
|
||||
══════════════════════════════════════
|
||||
REVIEW: Glossary + Architecture Vision (existing code)
|
||||
══════════════════════════════════════
|
||||
Glossary (N terms drafted from verified docs):
|
||||
- <Term>: <one-line definition>
|
||||
- ...
|
||||
|
||||
Architecture Vision — as inferred from the codebase:
|
||||
<one-paragraph synopsis>
|
||||
|
||||
Components / responsibilities:
|
||||
- <component>: <one-line>
|
||||
- ...
|
||||
|
||||
Principles / non-negotiables (inferred):
|
||||
- <principle> [inferred-from: <source>]
|
||||
- ...
|
||||
|
||||
Open questions / drift signals:
|
||||
- <q1>
|
||||
- <q2>
|
||||
══════════════════════════════════════
|
||||
A) Inferred vision matches my intent — write the files
|
||||
B) Add / correct entries (provide diffs — terms, components,
|
||||
principles, or rename pairs)
|
||||
C) Resolve the open questions / drift signals first
|
||||
══════════════════════════════════════
|
||||
Recommendation: pick C if any drift signals exist;
|
||||
otherwise B if the vision misses
|
||||
project-specific intent; A only when
|
||||
the inferred vision is exactly right.
|
||||
══════════════════════════════════════
|
||||
```
|
||||
|
||||
4. **Iterate**:
|
||||
- On B → integrate the user's diffs/additions, re-present, loop until A.
|
||||
- On C → ask the listed open questions in one batch (M4-style), integrate answers, re-present.
|
||||
- **Do NOT proceed to step 5 until the user picks A.**
|
||||
|
||||
5. **Save**:
|
||||
- Write `DOCUMENT_DIR/glossary.md`, alphabetical, with a top-line `**Status**: confirmed-by-user` and the date.
|
||||
- Update `DOCUMENT_DIR/architecture.md`:
|
||||
- If a `## Architecture Vision` (or `## Vision` / `## Overview`) section already exists at the top, replace its body with the confirmed paragraph + components + principles.
|
||||
- Otherwise, insert `## Architecture Vision` as the first H2 after the title; preserve every existing H2 below.
|
||||
- Do NOT delete or re-order existing technical sections (Tech Stack, Deployment Model, Data Model, NFRs, ADRs).
|
||||
|
||||
6. **Update `state.json`**: mark `step_4_5_glossary_vision: confirmed`. Resume on rerun must skip this step unless the user explicitly invokes `/document --refresh-vision`.
|
||||
|
||||
**Self-verification**:
|
||||
- [ ] Every glossary entry traces to at least one file under `DOCUMENT_DIR/`
|
||||
- [ ] Every component listed in the vision matches a folder under `DOCUMENT_DIR/components/`
|
||||
- [ ] All open questions are answered or explicitly deferred (with the user's acknowledgement)
|
||||
- [ ] `architecture.md` still contains all H2 sections it had before this step
|
||||
- [ ] User picked option A on the latest condensed view
|
||||
|
||||
**BLOCKING**: Do NOT proceed to the session boundary / Step 5 until both files are saved and the user has picked A.
|
||||
|
||||
---
|
||||
|
||||
**Session boundary**: After Step 4.5 is confirmed, suggest a session break before proceeding to the synthesis steps (5–7). These steps produce different artifact types and benefit from fresh context:
|
||||
|
||||
```
|
||||
══════════════════════════════════════
|
||||
|
||||
@@ -1,41 +1,59 @@
|
||||
---
|
||||
name: implement
|
||||
description: |
|
||||
Orchestrate task implementation with dependency-aware batching, parallel subagents, and integrated code review.
|
||||
Implement tasks sequentially with dependency-aware batching and integrated code review.
|
||||
Reads flat task files and _dependencies_table.md from TASKS_DIR, computes execution batches via topological sort,
|
||||
launches up to 4 implementer subagents in parallel, runs code-review skill after each batch, and loops until done.
|
||||
implements tasks one at a time in dependency order, runs code-review skill after each batch, and loops until done.
|
||||
Use after /decompose has produced task files.
|
||||
Trigger phrases:
|
||||
- "implement", "start implementation", "implement tasks"
|
||||
- "run implementers", "execute tasks"
|
||||
- "execute tasks"
|
||||
category: build
|
||||
tags: [implementation, orchestration, batching, parallel, code-review]
|
||||
tags: [implementation, batching, code-review]
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Implementation Orchestrator
|
||||
# Implementation Runner
|
||||
|
||||
Orchestrate the implementation of all tasks produced by the `/decompose` skill. This skill is a **pure orchestrator** — it does NOT write implementation code itself. It reads task specs, computes execution order, delegates to `implementer` subagents, validates results via the `/code-review` skill, and escalates issues.
|
||||
Implement all tasks produced by the `/decompose` skill. This skill reads task specs, computes execution order, writes the code and tests for each task **sequentially** (no subagents, no parallel execution), validates results via the `/code-review` skill, and escalates issues.
|
||||
|
||||
The `implementer` agent is the specialist that writes all the code — it receives a task spec, analyzes the codebase, implements the feature, writes tests, and verifies acceptance criteria.
|
||||
For each task the main agent receives a task spec, analyzes the codebase, implements the feature, writes tests, and verifies acceptance criteria — then moves on to the next task.
|
||||
|
||||
## Core Principles
|
||||
|
||||
- **Orchestrate, don't implement**: this skill delegates all coding to `implementer` subagents
|
||||
- **Dependency-aware batching**: tasks run only when all their dependencies are satisfied
|
||||
- **Max 4 parallel agents**: never launch more than 4 implementer subagents simultaneously
|
||||
- **File isolation**: no two parallel agents may write to the same file
|
||||
- **Sequential execution**: implement one task at a time. Do NOT spawn subagents and do NOT run tasks in parallel. (See `.cursor/rules/no-subagents.mdc`.)
|
||||
- **Dependency-aware ordering**: tasks run only when all their dependencies are satisfied
|
||||
- **Batching for review, not parallelism**: tasks are grouped into batches so `/code-review` and commits operate on a coherent unit of work — all tasks inside a batch are still implemented one after the other
|
||||
- **Integrated review**: `/code-review` skill runs automatically after each batch
|
||||
- **Auto-start**: batches launch immediately — no user confirmation before a batch
|
||||
- **Completeness before testing**: product implementation is not done until code is checked against task outcomes, included scope, architecture/component promises, named runtime dependencies, and unresolved scaffold/native placeholders — not just task AC tests
|
||||
- **Runtime dependency reality**: production code cannot satisfy a task by exposing only a protocol, fake runner, deterministic fallback, or "native bridge" placeholder when the task/architecture promises a concrete internal capability such as BASALT VIO, FAISS retrieval, LightGlue matching, or a full A-Z localization pipeline. Stubs are allowed only for external systems and tests.
|
||||
- **Auto-start**: batches start immediately — no user confirmation before a batch
|
||||
- **Gate on failure**: user confirmation is required only when code review returns FAIL
|
||||
- **Commit per batch**: after each batch is confirmed, commit. Ask the user whether to push to remote unless the user previously opted into auto-push for this session.
|
||||
|
||||
## Context Resolution
|
||||
|
||||
- TASKS_DIR: `_docs/02_tasks/`
|
||||
- Task files: all `*.md` files in `TASKS_DIR/todo/` (excluding files starting with `_`)
|
||||
- Task files: selected `*.md` files in `TASKS_DIR/todo/` (excluding files starting with `_`)
|
||||
- Dependency table: `TASKS_DIR/_dependencies_table.md`
|
||||
|
||||
### Task Selection Context
|
||||
|
||||
The invoking flow decides which task category this run should execute. The implement skill must honor that selected context instead of consuming every file in `todo/`.
|
||||
|
||||
| Context | Selected task files |
|
||||
|---------|---------------------|
|
||||
| Product implementation | Task specs that are not test-only and not refactoring specs |
|
||||
| Test implementation | `*_test_infrastructure.md` plus task specs whose `Component` or `Epic` identifies `Blackbox Tests` |
|
||||
| Refactoring | Task specs whose filename or task ID includes `_refactor_` |
|
||||
|
||||
If no explicit context is provided, infer it from the active autodev step:
|
||||
- greenfield Step 7 or existing-code Step 10 → Product implementation
|
||||
- greenfield Step 10 or existing-code Step 6 → Test implementation
|
||||
- refactor Phase 4 → Refactoring
|
||||
|
||||
Unselected task files remain in `TASKS_DIR/todo/` for their later flow step.
|
||||
|
||||
### Task Lifecycle Folders
|
||||
|
||||
```
|
||||
@@ -46,9 +64,31 @@ TASKS_DIR/
|
||||
└── done/ ← completed tasks (moved here after implementation)
|
||||
```
|
||||
|
||||
### Suite-level invocation context (meta-repo flow)
|
||||
|
||||
When invoked from `.cursor/skills/autodev/flows/meta-repo.md` Step 3.5 (or any caller that supplies the same context envelope), the skill receives:
|
||||
|
||||
```
|
||||
suite_level: true
|
||||
TASKS_DIR: <override> # e.g., _docs/tasks/ (vs. default _docs/02_tasks/)
|
||||
module_layout_path: <override> # e.g., _docs/tasks/_suite_module_layout.md
|
||||
```
|
||||
|
||||
When `suite_level: true` is present, the following gate adjustments apply — and ONLY these. All other steps (1–14, 16) execute unchanged:
|
||||
|
||||
1. **TASKS_DIR override** is honored throughout the skill (Step 1 Parse, Step 13 Archive, Step 15 input paths if it ran). Default `_docs/02_tasks/` is replaced by the supplied path.
|
||||
2. **module_layout_path override** is read instead of the hardcoded `_docs/02_document/module-layout.md` in Step 4 (Assign File Ownership). The supplied file uses the same `Per-Component Mapping` schema. If both the override and the hardcoded path are missing, behavior is unchanged from default mode (STOP and instruct).
|
||||
3. **Step 14.5 (Cumulative Code Review) — SKIPPED**. The meta-repo has no `_docs/02_document/architecture_compliance_baseline.md`; cross-task drift is captured by the next `monorepo-status` cycle instead.
|
||||
4. **Step 15 (Product Implementation Completeness Gate) — SKIPPED**. The gate's hard inputs (`_docs/02_document/architecture.md`, `system-flows.md`, `components/*/description.md`) do not exist in the meta-repo artifact layout. Suite-level tasks are infrastructure / coordination work (renames, cross-repo edits, suite-root infra additions), not feature implementation; the equivalent completeness signal is the next `monorepo-status` drift report (which the meta-repo flow re-runs immediately after Step 3.5 returns).
|
||||
5. **Final report filename**: `_docs/03_implementation/suite_implementation_report_{run_name}.md` (in addition to the existing feature/test/refactor variants). Batch reports follow `_docs/03_implementation/suite_batch_{NN}_report.md`.
|
||||
6. **Tracker integration** (Step 5: In Progress, Step 12: In Testing) runs unchanged — suite-level tickets follow the same tracker rules as any other.
|
||||
|
||||
Without `suite_level: true`, none of these adjustments apply and the skill runs exactly as documented in default mode.
|
||||
|
||||
## Prerequisite Checks (BLOCKING)
|
||||
|
||||
1. `TASKS_DIR/todo/` exists and contains at least one task file — **STOP if missing**
|
||||
1. `TASKS_DIR/todo/` exists and contains at least one task file for the selected context — **STOP if missing**
|
||||
- Exception for Product implementation re-entry: if no selected product tasks remain in `todo/`, but the active autodev state is Step 7 or the latest product completeness report is missing/invalid/contains `FAIL`, skip directly to Step 15 (Product Implementation Completeness Gate). This gate may create remediation tasks and return to Step 1. Do not write a final implementation report from this state.
|
||||
2. `_dependencies_table.md` exists — **STOP if missing**
|
||||
3. At least one task is not yet completed — **STOP if all done**
|
||||
4. **Working tree is clean** — run `git status --porcelain`; the output must be empty.
|
||||
@@ -56,16 +96,16 @@ TASKS_DIR/
|
||||
- A) Commit or stash stray changes manually, then re-invoke `/implement`
|
||||
- B) Agent commits stray changes as a single `chore: WIP pre-implement` commit and proceeds
|
||||
- C) Abort
|
||||
- Rationale: implementer subagents edit files in parallel and commit per batch. Unrelated uncommitted changes get silently folded into batch commits otherwise.
|
||||
- Rationale: each batch ends with a commit. Unrelated uncommitted changes would get silently folded into batch commits otherwise.
|
||||
- This check is repeated at the start of each batch iteration (see step 6 / step 14 Loop).
|
||||
|
||||
## Algorithm
|
||||
|
||||
### 1. Parse
|
||||
|
||||
- Read all task `*.md` files from `TASKS_DIR/todo/` (excluding files starting with `_`)
|
||||
- Read selected task `*.md` files from `TASKS_DIR/todo/` (excluding files starting with `_`)
|
||||
- Read `_dependencies_table.md` — parse into a dependency graph (DAG)
|
||||
- Validate: no circular dependencies, all referenced dependencies exist
|
||||
- Validate: no circular dependencies in the selected task graph, all referenced selected-task dependencies exist or are already completed in `TASKS_DIR/done/`
|
||||
|
||||
### 2. Detect Progress
|
||||
|
||||
@@ -78,22 +118,23 @@ TASKS_DIR/
|
||||
|
||||
- Topological sort remaining tasks
|
||||
- Select tasks whose dependencies are ALL satisfied (completed)
|
||||
- If a ready task depends on any task currently being worked on in this batch, it must wait for the next batch
|
||||
- Cap the batch at 4 parallel agents
|
||||
- A batch is simply a coherent group of tasks for review + commit. Within the batch, tasks are implemented sequentially in topological order.
|
||||
- Cap the batch size at a reasonable review scope (default: 4 tasks)
|
||||
- If the batch would exceed 20 total complexity points, suggest splitting and let the user decide
|
||||
|
||||
### 4. Assign File Ownership
|
||||
|
||||
The authoritative file-ownership map is `_docs/02_document/module-layout.md` (produced by the decompose skill's Step 1.5). Task specs are purely behavioral — they do NOT carry file paths. Derive ownership from the layout, not from the task spec's prose.
|
||||
The authoritative file-ownership map is `_docs/02_document/module-layout.md` (produced by the decompose skill's Step 1.5), unless `suite_level: true` was supplied in the invocation context — in which case the `module_layout_path` override is read instead (see "Suite-level invocation context" above). Task specs are purely behavioral — they do NOT carry file paths. Derive ownership from the layout, not from the task spec's prose.
|
||||
|
||||
For each task in the batch:
|
||||
- Read the task spec's **Component** field.
|
||||
- Look up the component in `_docs/02_document/module-layout.md` → Per-Component Mapping.
|
||||
- Set **OWNED** = the component's `Owns` glob (exclusive write for the duration of the batch).
|
||||
- Set **OWNED** = the component's `Owns` glob (the files this task is allowed to write).
|
||||
- Set **READ-ONLY** = Public API files of every component in the component's `Imports from` list, plus all `shared/*` Public API files.
|
||||
- Set **FORBIDDEN** = every other component's `Owns` glob, and every other component's internal (non-Public API) files.
|
||||
- If the task is a shared / cross-cutting task (lives under `shared/*`), OWNED = that shared directory; READ-ONLY = nothing; FORBIDDEN = every component directory.
|
||||
- If two tasks in the same batch map to the same component or overlapping `Owns` globs, schedule them sequentially instead of in parallel.
|
||||
|
||||
Since execution is sequential, there is no parallel-write conflict to resolve; ownership here is a **scope discipline** check — it stops a task from drifting into unrelated components even when alone.
|
||||
|
||||
If `_docs/02_document/module-layout.md` is missing or the component is not found:
|
||||
- STOP the batch.
|
||||
@@ -102,31 +143,30 @@ If `_docs/02_document/module-layout.md` is missing or the component is not found
|
||||
|
||||
### 5. Update Tracker Status → In Progress
|
||||
|
||||
For each task in the batch, transition its ticket status to **In Progress** via the configured work item tracker (see `protocols.md` for tracker detection) before launching the implementer. If `tracker: local`, skip this step.
|
||||
For each task in the batch, transition its ticket status to **In Progress** via the configured work item tracker (see `protocols.md` for tracker detection) before starting work. If `tracker: local`, skip this step. If a tracker operation fails unexpectedly, follow `.cursor/rules/tracker.mdc`.
|
||||
|
||||
### 6. Launch Implementer Subagents
|
||||
### 6. Implement Tasks Sequentially
|
||||
|
||||
**Per-batch dirty-tree re-check**: before launching subagents, run `git status --porcelain`. On the first batch this is guaranteed clean by the prerequisite check. On subsequent batches, the previous batch ended with a commit so the tree should still be clean. If the tree is dirty at this point, STOP and surface the dirty files to the user using the same A/B/C choice as the prerequisite check. The most likely causes are a failed commit in the previous batch, a user who edited files mid-loop, or a pre-commit hook that re-wrote files and was not captured.
|
||||
**Per-batch dirty-tree re-check**: before starting the batch, run `git status --porcelain`. On the first batch this is guaranteed clean by the prerequisite check. On subsequent batches, the previous batch ended with a commit so the tree should still be clean. If the tree is dirty at this point, STOP and surface the dirty files to the user using the same A/B/C choice as the prerequisite check. The most likely causes are a failed commit in the previous batch, a user who edited files mid-loop, or a pre-commit hook that re-wrote files and was not captured.
|
||||
|
||||
For each task in the batch, launch an `implementer` subagent with:
|
||||
- Path to the task spec file
|
||||
- List of files OWNED (exclusive write access)
|
||||
- List of files READ-ONLY
|
||||
- List of files FORBIDDEN
|
||||
- **Explicit instruction**: the implementer must write or update tests that validate each acceptance criterion in the task spec. If a test cannot run in the current environment (e.g., TensorRT requires GPU), the test must still be written and skip with a clear reason.
|
||||
For each task in the batch **in topological order, one at a time**:
|
||||
1. Read the task spec file.
|
||||
2. Respect the file-ownership envelope computed in Step 4 (OWNED / READ-ONLY / FORBIDDEN).
|
||||
3. Implement the feature and write/update tests for every acceptance criterion in the spec. Tests for internal product behavior must exercise the production implementation path. If a test cannot run in the current environment (e.g., TensorRT requires GPU), the test must still exist and skip/block with a clear prerequisite reason, but that skip does not make missing production code complete.
|
||||
4. Run the relevant tests locally before moving on to the next task in the batch. If tests fail, fix in-place — do not defer.
|
||||
5. Capture a short per-task status line (files changed, tests pass/fail, any blockers) for the batch report.
|
||||
|
||||
Launch all subagents immediately — no user confirmation.
|
||||
Do NOT spawn subagents and do NOT attempt to implement two tasks simultaneously, even if they touch disjoint files. See `.cursor/rules/no-subagents.mdc`.
|
||||
|
||||
### 7. Monitor
|
||||
### 7. Collect Status
|
||||
|
||||
- Wait for all subagents to complete
|
||||
- Collect structured status reports from each implementer
|
||||
- If any implementer reports "Blocked", log the blocker and continue with others
|
||||
- After all tasks in the batch are finished, aggregate the per-task status lines into a structured batch status.
|
||||
- If any task reported "Blocked", log the blocker with the failing task's ID and continue — the batch report will surface it.
|
||||
|
||||
**Stuck detection** — while monitoring, watch for these signals per subagent:
|
||||
- Same file modified 3+ times without test pass rate improving → flag as stuck, stop the subagent, report as Blocked
|
||||
- Subagent has not produced new output for an extended period → flag as potentially hung
|
||||
- If a subagent is flagged as stuck, do NOT let it continue looping — stop it and record the blocker in the batch report
|
||||
**Stuck detection** — while implementing a task, watch for these signals in your own progress:
|
||||
- The same file has been rewritten 3+ times without tests going green → stop, mark the task Blocked, and move to the next task in the batch (the user will be asked at the end of the batch).
|
||||
- You have tried 3+ distinct approaches without evidence-driven progress → stop, mark Blocked, move on.
|
||||
- Do NOT loop indefinitely on a single task. Record the blocker and proceed.
|
||||
|
||||
### 8. AC Test Coverage Verification
|
||||
|
||||
@@ -139,8 +179,8 @@ Before code review, verify that every acceptance criterion in each task spec has
|
||||
- **Not covered**: no test exists for this AC
|
||||
|
||||
If any AC is **Not covered**:
|
||||
- This is a **BLOCKING** failure — the implementer must write the missing test before proceeding
|
||||
- Re-launch the implementer with the specific ACs that need tests
|
||||
- This is a **BLOCKING** failure — the missing test must be written before proceeding
|
||||
- Go back to the offending task, add tests for the specific ACs that lack coverage, then re-run this check
|
||||
- If the test cannot run in the current environment (GPU required, platform-specific, external service), the test must still exist and skip with `pytest.mark.skipif` or `pytest.skip()` explaining the prerequisite
|
||||
- A skipped test counts as **Covered** — the test exists and will run when the environment allows
|
||||
|
||||
@@ -189,18 +229,22 @@ Track `auto_fix_attempts` and `escalated_findings` in the batch report for retro
|
||||
|
||||
### 12. Update Tracker Status → In Testing
|
||||
|
||||
After the batch is committed and pushed, transition the ticket status of each task in the batch to **In Testing** via the configured work item tracker. If `tracker: local`, skip this step.
|
||||
After the batch is committed (and pushed if the user approved pushing), transition the ticket status of each task in the batch to **In Testing** via the configured work item tracker. If `tracker: local`, skip this step. If a tracker operation fails unexpectedly, follow `.cursor/rules/tracker.mdc`.
|
||||
|
||||
### 13. Archive Completed Tasks
|
||||
|
||||
Move each completed task file from `TASKS_DIR/todo/` to `TASKS_DIR/done/`.
|
||||
|
||||
For product implementation, this archive means "batch implementation accepted." The Product Implementation Completeness Gate can still require follow-up remediation tasks before the feature is complete; it does not move original task files back to `todo/`.
|
||||
|
||||
### 14. Loop
|
||||
|
||||
- Go back to step 2 until all tasks in `todo/` are done
|
||||
|
||||
### 14.5. Cumulative Code Review (every K batches)
|
||||
|
||||
**Skipped entirely when `suite_level: true`** (see "Suite-level invocation context" above) — the meta-repo has no `architecture_compliance_baseline.md` to evaluate against; cross-task drift is captured by the next `monorepo-status` cycle.
|
||||
|
||||
- **Trigger**: every K completed batches (default `K = 3`; configurable per run via a `cumulative_review_interval` knob in the invocation context)
|
||||
- **Purpose**: per-batch review (Step 9) catches batch-local issues; cumulative review catches issues that only appear when tasks are combined — architecture drift, cross-task inconsistency, duplicate symbols introduced across different batches, contracts that drifted across producer/consumer batches
|
||||
- **Scope**: the union of files changed since the **last** cumulative review (or since the start of the run if this is the first)
|
||||
@@ -216,22 +260,81 @@ Move each completed task file from `TASKS_DIR/todo/` to `TASKS_DIR/done/`.
|
||||
- **Interaction with Auto-Fix Gate**: Architecture findings (new category from code-review Phase 7) always escalate per the implement auto-fix matrix; they cannot silently auto-fix
|
||||
- **Resumability**: if interrupted, the next invocation checks for the latest `cumulative_review_batches_*.md` and computes the changed-file set from batch reports produced after that review
|
||||
|
||||
### 15. Final Test Run
|
||||
### 15. Product Implementation Completeness Gate
|
||||
|
||||
- After all batches are complete, run the full test suite once
|
||||
- Read and execute `.cursor/skills/test-run/SKILL.md` (detect runner, run suite, diagnose failures, present blocking choices)
|
||||
- Test failures are a **blocking gate** — do not proceed until the test-run skill completes with a user decision
|
||||
- When tests pass, report final summary
|
||||
Run this gate after all **product implementation** tasks are complete and before writing any final product implementation report or allowing autodev to proceed to testability/test decomposition. Skip this gate when (a) the remaining context is explicitly test implementation or refactoring (as determined by the task files and report filename rules), OR (b) `suite_level: true` was supplied in the invocation context (the gate's inputs do not exist in the meta-repo artifact layout — see "Suite-level invocation context" above).
|
||||
|
||||
**Goal**: catch the failure mode where narrow tests validate scaffold behavior while the task's actual outcome, included scope, architecture promise, or named integration remains unimplemented.
|
||||
|
||||
Inputs:
|
||||
|
||||
- Completed product task specs from `_docs/02_tasks/done/` for the current cycle
|
||||
- `_docs/02_document/architecture.md`
|
||||
- `_docs/02_document/system-flows.md`
|
||||
- Relevant `_docs/02_document/components/*/description.md` files
|
||||
- Current source code under each completed task's ownership envelope
|
||||
- Batch reports and code-review reports for the current cycle
|
||||
|
||||
For each completed product task:
|
||||
|
||||
1. Read these sections from the task spec: `Description`, `Outcome`, `Scope / Included`, `Acceptance Criteria`, `Non-Functional Requirements`, `Constraints`, and explicit named technologies or integrations.
|
||||
2. Compare those promises against actual source code, not only tests or report prose.
|
||||
3. Search the task's owned component files for unresolved implementation markers: `placeholder`, `stub`, `reserved`, `TODO`, `NotImplemented`, `pass`, `deterministic`, `fake`, `mock`, `scaffold`, `native bridge`, and empty native/readme-only integration directories. Ignore test fixtures/mocks only when they are under test-owned paths and not used as production behavior.
|
||||
4. Verify that each named runtime dependency in the task promise is integrated as production behavior, not merely represented by an interface. Examples: if a task promises FAISS, DINOv2, BASALT, LightGlue, OpenCV, RANSAC, a database, cloud service, or hardware SDK, the production code must either call that dependency or contain an adapter that loads and executes the real dependency package. A deterministic fallback, fake runner, empty `native/` package, or "bridge to be supplied later" is **FAIL** unless the task itself explicitly scoped the dependency out before implementation started.
|
||||
5. Distinguish internal implementation from external prerequisites:
|
||||
- Internal product capabilities (VIO, anchor verification, cache retrieval, safety wrapper, FDR, MAVLink emission) must be implemented in production code before the task can pass.
|
||||
- External systems/hardware/data (Jetson device, physical camera, ArduPilot process, QGC, third-party service credentials, unavailable licensed dataset) may be `BLOCKED` only when production code exists and the missing prerequisite is outside the product boundary.
|
||||
6. Verify tests exercise the real implementation path where local prerequisites exist. Environment-gated tests may skip only with an explicit prerequisite reason; they do not make missing production code complete.
|
||||
7. For any architecture promise that describes an end-to-end user outcome, verify there is an executable production pipeline connecting the relevant components. Isolated component contracts and test-only harness orchestration are not enough.
|
||||
8. Classify each task:
|
||||
- **PASS**: task promises are implemented or explicitly out of scope in the task itself.
|
||||
- **BLOCKED**: production code exists but cannot be fully verified due to external hardware/data/license/runtime prerequisites; the blocker is explicit and tests report blocked/skipped with reason.
|
||||
- **FAIL**: promised production behavior is missing, only scaffolded, or only represented in tests/reports.
|
||||
|
||||
Save the audit to `_docs/03_implementation/implementation_completeness_cycle[N]_report.md` with:
|
||||
|
||||
- Per-task classification
|
||||
- Evidence files/symbols checked
|
||||
- Any unresolved scaffold/native placeholders
|
||||
- Any named promised technologies not integrated
|
||||
- Required remediation task suggestions, each sized to 5 points or less
|
||||
|
||||
Gate:
|
||||
|
||||
- If every product task is `PASS` or `BLOCKED` with explicit prerequisite evidence, continue to Final Test Run.
|
||||
- If any product task is `FAIL`, STOP. Do not write the final product implementation report and do not proceed to any downstream autodev step. Completed original task files remain in `done/`; the missing work is represented by remediation tasks. Present a Choose block:
|
||||
- A) Create remediation tasks now and return to implementation
|
||||
- B) Mark the missing behavior explicitly out of scope in task/docs, then re-run this gate
|
||||
- C) Abort for manual correction
|
||||
- Recommendation must normally be A unless the user deliberately accepts reduced scope.
|
||||
|
||||
Remediation task creation:
|
||||
|
||||
1. For each `FAIL`, create one or more task specs using `.cursor/skills/decompose/templates/task.md`; each remediation task must be sized at 5 points or less.
|
||||
2. Save each task to `_docs/02_tasks/todo/` with a short name prefixed by `remediate_`.
|
||||
3. Set **Component** to the failed task's component and set **Dependencies** to the failed task ID plus any remediation prerequisites.
|
||||
4. Create or defer tracker tickets using the same tracker rules as decompose/new-task: if tracker is available, create tickets immediately; if the user explicitly chose `tracker: local`, keep numeric prefixes with `Tracker: pending` / `Epic: pending`.
|
||||
5. Append the remediation tasks to `_docs/02_tasks/_dependencies_table.md`.
|
||||
6. Return to Step 1 (Parse) in **Product implementation** context. The final product implementation report can be written only after remediation tasks complete and this gate reruns without `FAIL`.
|
||||
|
||||
### 16. Final Test Run
|
||||
|
||||
- After all batches are complete, run the full test suite once unless the invoking flow's immediate next step is `Run Tests`.
|
||||
- If the next flow step is `Run Tests`, record a handoff in the final implementation report and let `.cursor/skills/test-run/SKILL.md` own the full-suite gate to avoid duplicate full runs.
|
||||
- When this step does run, read and execute `.cursor/skills/test-run/SKILL.md` (detect runner, run suite, diagnose failures, present blocking choices).
|
||||
- Test failures are a **blocking gate** — do not proceed until the test-run skill completes with a user decision.
|
||||
- When tests pass, report final summary.
|
||||
|
||||
## Batch Report Persistence
|
||||
|
||||
After each batch completes, save the batch report to `_docs/03_implementation/batch_[NN]_cycle[N]_report.md` for feature implementation (or `batch_[NN]_report.md` for test/refactor runs). Create the directory if it doesn't exist. When all tasks are complete, produce a FINAL implementation report with a summary of all batches. The filename depends on context:
|
||||
After each batch completes, save the batch report to `_docs/03_implementation/batch_[NN]_cycle[N]_report.md` for feature implementation (or `batch_[NN]_report.md` for test/refactor runs). Create the directory if it doesn't exist. For product implementation, produce the FINAL implementation report only after the Product Implementation Completeness Gate passes. For test and refactor implementation, produce the FINAL report after all selected tasks complete and the full-suite gate is either run or handed off per Step 16. The filename depends on context:
|
||||
|
||||
- **Test implementation** (tasks from test decomposition): `_docs/03_implementation/implementation_report_tests.md`
|
||||
- **Feature implementation**: `_docs/03_implementation/implementation_report_{feature_slug}_cycle{N}.md` where `{feature_slug}` is derived from the batch task names (e.g., `implementation_report_core_api_cycle2.md`) and `{N}` is the current `state.cycle` from `_docs/_autodev_state.md`. If `state.cycle` is absent (pre-migration), default to `cycle1`.
|
||||
- **Refactoring**: `_docs/03_implementation/implementation_report_refactor_{run_name}.md`
|
||||
- **Suite-level** (when `suite_level: true` was supplied — see "Suite-level invocation context" above): `_docs/03_implementation/suite_implementation_report_{run_name}.md`. Batch reports use `_docs/03_implementation/suite_batch_{NN}_report.md`. `{run_name}` is derived from the batch task IDs (e.g., `suite_implementation_report_az543_az549_az550.md`).
|
||||
|
||||
Determine the context from the task files being implemented: if all tasks have test-related names or belong to a test epic, use the tests filename; otherwise derive the feature slug from the component names and append the cycle suffix.
|
||||
Determine the context from the task files being implemented: if all tasks have test-related names or belong to a test epic, use the tests filename; if `suite_level: true` was supplied, use the suite filename; otherwise derive the feature slug from the component names and append the cycle suffix.
|
||||
|
||||
Batch report filenames must also include the cycle counter when running feature implementation: `_docs/03_implementation/batch_{NN}_cycle{N}_report.md` (test and refactor runs may use the plain `batch_{NN}_report.md` form since they are not cycle-scoped).
|
||||
|
||||
@@ -264,9 +367,10 @@ After each batch, produce a structured report:
|
||||
|
||||
| Situation | Action |
|
||||
|-----------|--------|
|
||||
| Implementer fails same approach 3+ times | Stop it, escalate to user |
|
||||
| Same task rewritten 3+ times without green tests | Mark Blocked, continue batch, escalate at batch end |
|
||||
| Task blocked on external dependency (not in task list) | Report and skip |
|
||||
| File ownership conflict unresolvable | ASK user |
|
||||
| File ownership violated (task wrote outside OWNED) | ASK user |
|
||||
| Product completeness gate finds missing promised implementation | STOP — create remediation tasks or get explicit user scope reduction |
|
||||
| Test failure after final test run | Delegate to test-run skill — blocking gate |
|
||||
| All tasks complete | Report final summary, suggest final commit |
|
||||
| `_dependencies_table.md` missing | STOP — run `/decompose` first |
|
||||
@@ -281,7 +385,8 @@ Each batch commit serves as a rollback checkpoint. If recovery is needed:
|
||||
|
||||
## Safety Rules
|
||||
|
||||
- Never launch tasks whose dependencies are not yet completed
|
||||
- Never allow two parallel agents to write to the same file
|
||||
- If a subagent fails or is flagged as stuck, stop it and report — do not let it loop indefinitely
|
||||
- Always run the full test suite after all batches complete (step 15)
|
||||
- Never start a task whose dependencies are not yet completed
|
||||
- Never run tasks in parallel and never spawn subagents — see `.cursor/rules/no-subagents.mdc`
|
||||
- If a task is flagged as stuck, stop working on it and report — do not let it loop indefinitely
|
||||
- Always run the Product Implementation Completeness Gate before final product reports
|
||||
- Always run or hand off the full test suite after all batches complete (step 16)
|
||||
|
||||
@@ -3,29 +3,31 @@
|
||||
## Topological Sort with Batch Grouping
|
||||
|
||||
The `/implement` skill uses a topological sort to determine execution order,
|
||||
then groups tasks into batches for parallel execution.
|
||||
then groups tasks into batches for code review and commit. Execution within a
|
||||
batch is **sequential** — see `.cursor/rules/no-subagents.mdc`.
|
||||
|
||||
## Algorithm
|
||||
|
||||
1. Build adjacency list from `_dependencies_table.md`
|
||||
2. Compute in-degree for each task node
|
||||
3. Initialize batch 0 with all nodes that have in-degree 0
|
||||
3. Initialize the ready set with all nodes that have in-degree 0
|
||||
4. For each batch:
|
||||
a. Select up to 4 tasks from the ready set
|
||||
b. Check file ownership — if two tasks would write the same file, defer one to the next batch
|
||||
c. Launch selected tasks as parallel implementer subagents
|
||||
d. When all complete, remove them from the graph and decrement in-degrees of dependents
|
||||
e. Add newly zero-in-degree nodes to the next batch's ready set
|
||||
a. Select up to 4 tasks from the ready set (default batch size cap)
|
||||
b. Implement the selected tasks one at a time in topological order
|
||||
c. When all tasks in the batch complete, remove them from the graph and
|
||||
decrement in-degrees of dependents
|
||||
d. Add newly zero-in-degree nodes to the ready set
|
||||
5. Repeat until the graph is empty
|
||||
|
||||
## File Ownership Conflict Resolution
|
||||
## Ordering Inside a Batch
|
||||
|
||||
When two tasks in the same batch map to overlapping files:
|
||||
- Prefer to run the lower-numbered task first (it's more foundational)
|
||||
- Defer the higher-numbered task to the next batch
|
||||
- If both have equal priority, ask the user
|
||||
Tasks inside a batch are executed in topological order — a task is only
|
||||
started after every task it depends on (inside the batch or in a previous
|
||||
batch) is done. When two tasks have the same topological rank, prefer the
|
||||
lower-numbered (more foundational) task first.
|
||||
|
||||
## Complexity Budget
|
||||
|
||||
Each batch should not exceed 20 total complexity points.
|
||||
If it does, split the batch and let the user choose which tasks to include.
|
||||
The budget exists to keep the per-batch code review scope reviewable.
|
||||
|
||||
@@ -129,7 +129,8 @@ If `_docs/_repo-config.yaml` already exists:
|
||||
- Entries removed (component removed from registry)
|
||||
4. **Ask the user** whether to apply the diff.
|
||||
5. If applied, **preserve `confirmed: true` flags** for entries that still match — don't reset human-approved mappings.
|
||||
6. If user declines, stop — leave config untouched.
|
||||
6. **Preserve user-owned top-level keys verbatim**: `glossary_doc:` (written by autodev meta-repo Step 2.5) and any `assumptions_log:` entries are NEVER edited or removed by this skill. Carry them through unchanged. If the file referenced by `glossary_doc:` no longer exists on disk, surface as an `unresolved:` question — do not auto-clear the field.
|
||||
7. If user declines, stop — leave config untouched.
|
||||
|
||||
### Phase 8: Batch question checkpoint (M4)
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ Propagates component changes into the unified documentation set. Strictly scoped
|
||||
| Root `README.md` **only** if `_repo-config.yaml` lists it as a doc target (e.g., services table) | Install scripts (`ci-*.sh`) → use `monorepo-cicd` |
|
||||
| Docs index (`_docs/README.md` or similar) cross-reference tables | Component-internal docs (`<component>/README.md`, `<component>/docs/*`) |
|
||||
| Cross-cutting docs listed in `docs.cross_cutting` | `_docs/_repo-config.yaml` itself (only `monorepo-discover` and `monorepo-onboard` write it) |
|
||||
| Body of cross-cutting docs **except** the `## Architecture Vision` section (preserved verbatim — owned by autodev meta-repo Step 2.5) | The file at `glossary_doc:` (user-confirmed; only autodev meta-repo Step 2.5 rewrites it). New project terms surfaced during sync are reported back to the user, not silently appended |
|
||||
| `## Architecture Vision` body — read-only, may be referenced for terminology consistency but never edited | — |
|
||||
|
||||
If a component change requires CI/env updates too, tell the user to also run `monorepo-cicd`. This skill does NOT cross domains.
|
||||
|
||||
@@ -166,6 +168,8 @@ Append to `_docs/_repo-config.yaml` under `assumptions_log:`:
|
||||
- Change `confirmed_by_user` or any `confirmed: <bool>` flag
|
||||
- Auto-commit or push
|
||||
- Guess a mapping not in the config
|
||||
- Edit `glossary_doc:` (the file recorded under the config's `glossary_doc:` key)
|
||||
- Edit the `## Architecture Vision` section of any cross-cutting doc; if a sync would conflict with that section, surface the conflict to the user and skip — do not silently rewrite user-confirmed content
|
||||
|
||||
## Edge cases
|
||||
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
---
|
||||
name: monorepo-e2e
|
||||
description: Syncs the suite-level integration e2e harness (`e2e/docker-compose.suite-e2e.yml`, fixtures, Playwright runner) when component contracts drift in ways that affect the cross-service scenario. Reads `_docs/_repo-config.yaml` to know which suite-e2e artifacts are in play. Touches ONLY suite-e2e files — never per-component CI, docs, or component internals. Use when a component changes a port, env var, public API endpoint, DB schema column, or detection model that the suite e2e exercises.
|
||||
---
|
||||
|
||||
# Monorepo Suite-E2E
|
||||
|
||||
Propagates component changes into the suite-level integration e2e harness. Strictly scoped — never edits docs, component internals, per-component CI configs, or the production deploy compose.
|
||||
|
||||
## Scope — explicit
|
||||
|
||||
| In scope | Out of scope |
|
||||
| -------- | ------------ |
|
||||
| `e2e/docker-compose.suite-e2e.yml` (overlay, healthchecks, seed services) | Production `_infra/deploy/<target>/docker-compose.yml` — `monorepo-cicd` owns it |
|
||||
| `e2e/fixtures/init.sql` (seeded rows that the spec depends on) | Component DB migrations — owned by each component |
|
||||
| `e2e/fixtures/expected_detections.json` (detection baseline) | Detection model itself — owned by `detections/` |
|
||||
| `e2e/runner/tests/*.spec.ts` selector / contract-driven edits | New scenarios (user-driven, not drift-driven) |
|
||||
| `e2e/runner/Dockerfile` / `package.json` Playwright version bumps | Net-new e2e infrastructure (use `monorepo-onboard` or initial scaffolding) |
|
||||
| `.woodpecker/suite-e2e.yml` (suite-level pipeline) | Per-component `.woodpecker/01-test.yml` / `02-build-push.yml` — `monorepo-cicd` owns those |
|
||||
| Suite-e2e leftover entries under `_docs/_process_leftovers/` | Per-component leftovers — owned by each component |
|
||||
|
||||
If a component change needs doc updates too, tell the user to also run `monorepo-document`. If it needs production-deploy or per-component CI updates, run `monorepo-cicd`. This skill **only** updates the suite-e2e surface.
|
||||
|
||||
## Preconditions (hard gates)
|
||||
|
||||
1. `_docs/_repo-config.yaml` exists.
|
||||
2. Top-level `confirmed_by_user: true`.
|
||||
3. `suite_e2e.*` section is populated in config (see "Required config block" below). If absent, abort and ask the user to extend the config via `monorepo-discover`.
|
||||
4. Components-in-scope have confirmed contract mappings (port, public API path, DB tables touched), OR user explicitly approves inferred ones.
|
||||
|
||||
## Required config block
|
||||
|
||||
This skill expects `_docs/_repo-config.yaml` to carry:
|
||||
|
||||
```yaml
|
||||
suite_e2e:
|
||||
overlay: e2e/docker-compose.suite-e2e.yml
|
||||
fixtures:
|
||||
init_sql: e2e/fixtures/init.sql
|
||||
baseline_json: e2e/fixtures/expected_detections.json
|
||||
binary_fixtures:
|
||||
- e2e/fixtures/sample.mp4
|
||||
- e2e/fixtures/model.tar.gz
|
||||
runner:
|
||||
dockerfile: e2e/runner/Dockerfile
|
||||
package_json: e2e/runner/package.json
|
||||
spec_dir: e2e/runner/tests
|
||||
pipeline: .woodpecker/suite-e2e.yml
|
||||
scenario:
|
||||
description: "Upload video → detect → overlays → dataset → DB persistence"
|
||||
components_exercised:
|
||||
- ui
|
||||
- annotations
|
||||
- detections
|
||||
- postgres-local
|
||||
api_contracts:
|
||||
- component: ui
|
||||
path: /api/admin/auth/login
|
||||
- component: annotations
|
||||
path: /api/annotations/media/batch
|
||||
- component: annotations
|
||||
path: /api/annotations/media/{id}/annotations
|
||||
db_tables:
|
||||
- media
|
||||
- annotations
|
||||
- detection
|
||||
- detection_classes
|
||||
model_pin:
|
||||
detections_repo_path: <path-to-model-config-or-classes-source>
|
||||
classes_source: annotations/src/Database/DatabaseMigrator.cs
|
||||
```
|
||||
|
||||
If `suite_e2e:` is missing the skill **stops** — it does not invent a default mapping.
|
||||
|
||||
## Mitigations (M1–M7)
|
||||
|
||||
- **M1** Separation: this skill only touches suite-e2e files; no production deploy compose, no per-component CI, no docs, no component internals.
|
||||
- **M3** Factual vs. interpretive: port, env var, API path, DB column — FACTUAL, read from the components' code. Whether a baseline still matches the model — DEFERRED to the user (the skill flags drift, never silently re-records).
|
||||
- **M4** Batch questions at checkpoints.
|
||||
- **M5** Skip over guess: a component change that doesn't map cleanly to one of the in-scope artifacts → skip and report.
|
||||
- **M6** Assumptions footer + append to `_repo-config.yaml` `assumptions_log`.
|
||||
- **M7** Drift detection: verify every path under `suite_e2e.*` exists on disk; stop if not.
|
||||
|
||||
## Workflow
|
||||
|
||||
### Phase 1: Drift check (M7)
|
||||
|
||||
Verify every file listed under `suite_e2e.*` (excluding `binary_fixtures`, which are gitignored) exists on disk. Missing file → stop and ask:
|
||||
- Run `monorepo-discover` to refresh, OR
|
||||
- Skip the missing artifact (recorded in report)
|
||||
|
||||
For `binary_fixtures` paths that are absent (expected — they live in S3/LFS), check whether `expected_detections.json._meta.video_sha256` is still a `TBD-...` placeholder. If yes, surface this as a known leftover (`_docs/_process_leftovers/2026-04-22_suite-e2e-binary-fixtures.md`) and continue.
|
||||
|
||||
### Phase 2: Determine scope
|
||||
|
||||
Same as `monorepo-cicd` Phase 2 — ask the user, or auto-detect. For **auto-detect**, flag commits that touch suite-e2e-relevant concerns:
|
||||
|
||||
| Commit pattern | Suite-e2e impact |
|
||||
| -------------- | ---------------- |
|
||||
| New port exposed by `<component>` | Healthcheck override may change in `e2e/docker-compose.suite-e2e.yml` |
|
||||
| New required env var on `<component>` | `e2e/docker-compose.suite-e2e.yml` `e2e-runner` env block + `init.sql` seed |
|
||||
| Public API path renamed / removed | Spec selector / API call path in `e2e/runner/tests/*.spec.ts` |
|
||||
| DB schema column renamed in a `db_tables` entry | `init.sql` column reference + spec `pg.query` text |
|
||||
| New required DB table referenced by spec | `init.sql` insert block (skip if owned by component migration) |
|
||||
| Detection model rev change in `detections/` | `expected_detections.json` `_meta.model.revision` + flag baseline as stale |
|
||||
| New canonical detection class added | `expected_detections.json._meta` annotation |
|
||||
|
||||
Present the flagged list; confirm.
|
||||
|
||||
### Phase 3: Classify changes per component
|
||||
|
||||
| Change type | Target suite-e2e files |
|
||||
| ----------- | ---------------------- |
|
||||
| Port / env var change | `e2e/docker-compose.suite-e2e.yml` |
|
||||
| API path / contract change | `e2e/runner/tests/*.spec.ts` |
|
||||
| DB schema reference change | `e2e/fixtures/init.sql` and spec SQL queries |
|
||||
| Model / class catalog change | `e2e/fixtures/expected_detections.json` (mark `_meta.fixture_version` bump + leftover entry for binary refresh) |
|
||||
| Playwright dependency drift | `e2e/runner/package.json` + `e2e/runner/Dockerfile` |
|
||||
| Suite scenario steps gone stale | **Stop and ask** — scenario edits are user-driven, not drift-driven |
|
||||
|
||||
### Phase 4: Apply edits
|
||||
|
||||
Edit each in-scope file. After each batch, run `ReadLints` on touched files. Do NOT run the suite e2e itself — that's a downstream pipeline operation, not a sync-skill responsibility.
|
||||
|
||||
For `expected_detections.json`: when the model revision changes, the skill **does not** re-record the baseline — the binary fixture cannot be regenerated from the dev environment. Instead:
|
||||
1. Set `_meta.model.revision` to the new revision.
|
||||
2. Set `_meta.fixture_version` to a new bumped version with a `-stale` suffix (e.g., `0.2.0-stale`).
|
||||
3. Append a new entry to `_docs/_process_leftovers/` describing the required re-record.
|
||||
4. Leave `expected.by_class` untouched — the spec's tolerance check will fail loudly until the binary refresh lands.
|
||||
|
||||
### Phase 5: Update assumptions log
|
||||
|
||||
Append a new `assumptions_log:` entry to `_docs/_repo-config.yaml` recording:
|
||||
- Date, components in scope, which suite-e2e files were touched
|
||||
- Any inferred contract mappings still tagged `confirmed: false`
|
||||
- Any leftover entries created
|
||||
|
||||
### Phase 6: Report
|
||||
|
||||
Render a Choose-format summary of the synced files, surface any `_process_leftovers/` entries created, and end. Do NOT auto-commit.
|
||||
|
||||
## Self-verification
|
||||
|
||||
- [ ] No file outside `e2e/`, `.woodpecker/suite-e2e.yml`, or `_docs/_process_leftovers/` was edited
|
||||
- [ ] `_docs/_repo-config.yaml` `suite_e2e:` block was not silently mutated except for `assumptions_log` append
|
||||
- [ ] `expected_detections.json` was not re-recorded (only metadata bumped + leftover added)
|
||||
- [ ] Every spec edit traces to a flagged commit pattern in Phase 2
|
||||
- [ ] `ReadLints` clean on every touched file
|
||||
|
||||
## Failure handling
|
||||
|
||||
Same retry / escalation protocol as `monorepo-cicd` — see `protocols.md`. The most common failure mode is the binary-fixture leftover (sample.mp4 missing or SHA-mismatched); this skill does not attempt to resolve it, only surfaces it.
|
||||
@@ -59,6 +59,8 @@ Mark each as `complete` / `partial` / `missing` and explain.
|
||||
- Every component in `components:` appears in the registry — flag mismatches
|
||||
- Every `docs.root` file cross-referenced in config exists on disk — flag missing
|
||||
- Every `ci.orchestration_files` and `ci.install_scripts` exists — flag missing
|
||||
- `glossary_doc:` (if recorded in config) points to a file that exists on disk — flag missing
|
||||
- The cross-cutting architecture doc identified by `docs.cross_cutting` contains a `## Architecture Vision` section — flag missing (signals the meta-repo flow's Step 2.5 was skipped or the section was removed)
|
||||
|
||||
### Section 5: Unresolved questions
|
||||
|
||||
@@ -113,6 +115,8 @@ In registry, not in config: [list or "(none)"]
|
||||
In config, not in registry: [list or "(none)"]
|
||||
Config-referenced docs missing: [list or "(none)"]
|
||||
Config-referenced CI files missing: [list or "(none)"]
|
||||
glossary_doc: [path or "not recorded — run /autodev to capture"]
|
||||
Architecture Vision section: [present | missing in <doc>]
|
||||
|
||||
═══════════════════════════════════════════════════
|
||||
Unresolved questions
|
||||
|
||||
@@ -75,7 +75,7 @@ Record the description verbatim for use in subsequent steps.
|
||||
**Role**: Technical analyst
|
||||
**Goal**: Determine whether deep research is needed.
|
||||
|
||||
Read the user's description and the existing codebase documentation from DOCUMENT_DIR (architecture.md, components/, system-flows.md).
|
||||
Read the user's description and the existing codebase documentation from DOCUMENT_DIR (architecture.md including its `## Architecture Vision` section, glossary.md, components/, system-flows.md). Use `glossary.md` to keep the new task's name, acceptance-criteria wording, and component references aligned with the user's confirmed vocabulary; flag the task to the user if the request appears to violate an Architecture Vision principle, do not silently allow it.
|
||||
|
||||
**Consult LESSONS.md**: if `_docs/LESSONS.md` exists, read it and look for entries in categories `estimation`, `architecture`, `dependencies` that might apply to the task under consideration. If a relevant lesson exists (e.g., "estimation: auth-related changes historically take 2x estimate"), bias the classification and recommendation accordingly. Note in the output which lessons (if any) were applied.
|
||||
|
||||
@@ -134,7 +134,8 @@ The `<task_slug>` is a short kebab-case name derived from the feature descriptio
|
||||
**Goal**: Determine where and how to insert the new functionality, and whether existing tests cover the new requirements.
|
||||
|
||||
1. Read the codebase documentation from DOCUMENT_DIR:
|
||||
- `architecture.md` — overall structure
|
||||
- `architecture.md` — overall structure (the `## Architecture Vision` H2 is user-confirmed intent and must not be violated by the new task without explicit approval)
|
||||
- `glossary.md` — project terminology; reuse the user's vocabulary in task names, AC, and component references
|
||||
- `components/` — component specs
|
||||
- `system-flows.md` — data flows (if exists)
|
||||
- `data_model.md` — data model (if exists)
|
||||
@@ -281,7 +282,7 @@ Present using the Choose format for each decision that has meaningful alternativ
|
||||
- Update **Epic** field: `[EPIC-ID]`
|
||||
3. Rename the file from `[##]_[short_name].md` to `[TICKET-ID]_[short_name].md`
|
||||
|
||||
If the work item tracker is not authenticated or unavailable (`tracker: local`):
|
||||
If the work item tracker is not authenticated or unavailable, follow `.cursor/rules/tracker.mdc` before continuing. Only if the user explicitly chooses `tracker: local`:
|
||||
- Keep the numeric prefix
|
||||
- Set **Tracker** to `pending`
|
||||
- Set **Epic** to `pending`
|
||||
@@ -336,7 +337,7 @@ After the user chooses **Done**:
|
||||
| Research skill hits a blocker | Follow research skill's own escalation rules |
|
||||
| Codebase analysis reveals conflicting architectures | **ASK** user which pattern to follow |
|
||||
| Complexity exceeds 5 points | **WARN** user and suggest splitting into multiple tasks |
|
||||
| Work item tracker MCP unavailable | **WARN**, continue with local-only task files |
|
||||
| Work item tracker MCP unavailable | Follow `.cursor/rules/tracker.mdc`; do not continue in local mode unless the user explicitly chooses it |
|
||||
|
||||
## Trigger Conditions
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ Capture any new questions, findings, or insights that arise during test specific
|
||||
|
||||
### Step 2: Solution Analysis
|
||||
|
||||
Read and follow `steps/02_solution-analysis.md`.
|
||||
Read and follow `steps/02_solution-analysis.md`. The step opens with **Phase 2a.0: Glossary & Architecture Vision** (BLOCKING) — drafts `_docs/02_document/glossary.md` and a one-paragraph architecture vision, presents the condensed view to the user, iterates until confirmed, then proceeds into the architecture, data-model, and deployment phases. The confirmed vision becomes the first `## Architecture Vision` H2 of `architecture.md`.
|
||||
|
||||
---
|
||||
|
||||
@@ -107,6 +107,7 @@ Read and follow `steps/07_quality-checklist.md`.
|
||||
- **Coding during planning**: this workflow produces documents, never code
|
||||
- **Multi-responsibility components**: if a component does two things, split it
|
||||
- **Skipping BLOCKING gates**: never proceed past a BLOCKING marker without user confirmation
|
||||
- **Skipping the glossary/vision gate (Phase 2a.0)**: drafting `architecture.md` from raw `solution.md` without confirming terminology and vision means the AI's mental model is not aligned with the user's; every downstream artifact will inherit that drift
|
||||
- **Diagrams without data**: generate diagrams only after the underlying structure is documented
|
||||
- **Copy-pasting problem.md**: the architecture doc should analyze and transform, not repeat the input
|
||||
- **Vague interfaces**: "component A talks to component B" is not enough; define the method, input, output
|
||||
@@ -137,8 +138,10 @@ Read and follow `steps/07_quality-checklist.md`.
|
||||
│ │
|
||||
│ 1. Blackbox Tests → test-spec/SKILL.md │
|
||||
│ [BLOCKING: user confirms test coverage] │
|
||||
│ 2. Solution Analysis → architecture, data model, deployment │
|
||||
│ [BLOCKING: user confirms architecture] │
|
||||
│ 2. Solution Analysis → glossary + vision, architecture, │
|
||||
│ data model, deployment │
|
||||
│ [BLOCKING 2a.0: user confirms glossary + vision] │
|
||||
│ [BLOCKING 2a: user confirms architecture] │
|
||||
│ 3. Component Decomp → component specs + interfaces │
|
||||
│ [BLOCKING: user confirms components] │
|
||||
│ 4. Review & Risk → risk register, iterations │
|
||||
|
||||
@@ -4,20 +4,105 @@
|
||||
**Goal**: Produce `architecture.md`, `system-flows.md`, `data_model.md`, and `deployment/` from the solution draft
|
||||
**Constraints**: No code, no component-level detail yet; focus on system-level view
|
||||
|
||||
### Phase 2a.0: Glossary & Architecture Vision (BLOCKING)
|
||||
|
||||
**Role**: Software architect + business analyst
|
||||
**Goal**: Align the AI's mental model of the project with the user's intent BEFORE drafting `architecture.md`. Capture domain terminology and the user's high-level architecture vision so every downstream artifact (architecture, components, flows, tests, epics) is grounded in confirmed user intent — not in AI inference.
|
||||
|
||||
**Inputs**:
|
||||
- `_docs/00_problem/problem.md`, `acceptance_criteria.md`, `restrictions.md`
|
||||
- `_docs/00_problem/input_data/*`
|
||||
- `_docs/01_solution/solution.md` (and any earlier `solution_draft*.md` siblings)
|
||||
- Any blackbox-test findings produced in Step 1
|
||||
|
||||
**Outputs**:
|
||||
- `_docs/02_document/glossary.md` (NEW)
|
||||
- A confirmed "Architecture Vision" paragraph + bullet list held in working memory and used as the spine of Phase 2a's `architecture.md`
|
||||
|
||||
**Procedure**:
|
||||
|
||||
1. **Draft glossary** — extract project-specific terminology from inputs (NOT generic software terms). Include:
|
||||
- Domain entities, processes, and roles
|
||||
- Acronyms / abbreviations
|
||||
- Internal codenames or product names
|
||||
- Synonym pairs in active use (e.g., "flight" vs. "mission")
|
||||
- Stakeholder personas referenced in problem.md
|
||||
Each entry: one-line definition, plus a parenthetical source (`source: problem.md`, `source: solution.md §3`).
|
||||
Skip terms that have a single well-known industry meaning (REST, JSON, etc.).
|
||||
|
||||
2. **Draft architecture vision** — synthesize from inputs:
|
||||
- **One paragraph**: what the system is, who uses it, the shape of the runtime topology (monolith / services / pipeline / library / hybrid).
|
||||
- **Components & responsibilities** (one-line each). At this stage these are *intent-level*, not the formal decomposition that Step 3 produces.
|
||||
- **Major data flows** (one or two sentences each).
|
||||
- **Architectural principles / non-negotiables** the user has implied (e.g., "DB-driven config", "no per-component state outside Redis", "all UI traffic via REST + SSE only").
|
||||
- **Open architectural questions** the AI cannot resolve from inputs alone.
|
||||
|
||||
3. **Present condensed view** to the user (NOT the full draft files — a synopsis only):
|
||||
|
||||
```
|
||||
══════════════════════════════════════
|
||||
REVIEW: Glossary + Architecture Vision
|
||||
══════════════════════════════════════
|
||||
Glossary (N terms drafted):
|
||||
- <Term>: <one-line definition>
|
||||
- ...
|
||||
Architecture Vision:
|
||||
<one-paragraph synopsis>
|
||||
|
||||
Components / responsibilities:
|
||||
- <component>: <one-line>
|
||||
- ...
|
||||
|
||||
Principles / non-negotiables:
|
||||
- <principle>
|
||||
- ...
|
||||
|
||||
Open questions (AI could not resolve):
|
||||
- <q1>
|
||||
- <q2>
|
||||
══════════════════════════════════════
|
||||
A) Looks correct — write glossary.md, use vision for Phase 2a
|
||||
B) I want to add / correct entries (provide diffs)
|
||||
C) Answer the open questions first, then re-present
|
||||
══════════════════════════════════════
|
||||
Recommendation: pick C if open questions exist, otherwise A
|
||||
══════════════════════════════════════
|
||||
```
|
||||
|
||||
4. **Iterate**:
|
||||
- On B → integrate the user's diffs/additions, re-present the condensed view, loop until A.
|
||||
- On C → ask the listed open questions one round (M4-style batch), integrate answers, re-present.
|
||||
- **Do NOT proceed to step 5 until the user picks A.**
|
||||
|
||||
5. **Save**:
|
||||
- Write `_docs/02_document/glossary.md` with terms in alphabetical order. Include a top-line `**Status**: confirmed-by-user` and the date.
|
||||
- Hold the confirmed vision (paragraph + components + principles) in working memory; Phase 2a will materialize it into `architecture.md` and **must** preserve every confirmed principle and component intent verbatim.
|
||||
|
||||
**Self-verification**:
|
||||
- [ ] Every glossary entry traces to at least one input file (no invented terms)
|
||||
- [ ] Every component listed in the vision is one the inputs reference
|
||||
- [ ] All open questions are either answered or explicitly deferred (with the user's acknowledgement)
|
||||
- [ ] User picked option A on the latest condensed view
|
||||
|
||||
**BLOCKING**: Do NOT proceed to Phase 2a until `glossary.md` is saved and the user has confirmed the architecture vision.
|
||||
|
||||
### Phase 2a: Architecture & Flows
|
||||
|
||||
1. Read all input files thoroughly
|
||||
2. Incorporate findings, questions, and insights discovered during Step 1 (blackbox tests)
|
||||
3. Research unknown or questionable topics via internet; ask user about ambiguities
|
||||
4. Document architecture using `templates/architecture.md` as structure
|
||||
5. Document system flows using `templates/system-flows.md` as structure
|
||||
3. **Apply confirmed vision from Phase 2a.0**: the architecture document must include a top-level `## Architecture Vision` section that contains the user-confirmed paragraph, components, and principles verbatim. The rest of `architecture.md` (tech stack, deployment model, NFRs, ADRs) builds on top of that section, never contradicts it
|
||||
4. Research unknown or questionable topics via internet; ask user about ambiguities
|
||||
5. Document architecture using `templates/architecture.md` as structure
|
||||
6. Document system flows using `templates/system-flows.md` as structure
|
||||
|
||||
**Self-verification**:
|
||||
- [ ] `architecture.md` opens with a `## Architecture Vision` section matching Phase 2a.0
|
||||
- [ ] Architecture covers all capabilities mentioned in solution.md
|
||||
- [ ] System flows cover all main user/system interactions
|
||||
- [ ] No contradictions with problem.md or restrictions.md
|
||||
- [ ] No contradictions with problem.md, restrictions.md, or the confirmed vision
|
||||
- [ ] Technology choices are justified
|
||||
- [ ] Blackbox test findings are reflected in architecture decisions
|
||||
- [ ] Every term used in `architecture.md` that is project-specific appears in `glossary.md`
|
||||
|
||||
**Save action**: Write `architecture.md` and `system-flows.md`
|
||||
|
||||
|
||||
@@ -58,4 +58,4 @@ Do NOT create minimal epics with just a summary and short description. The epic
|
||||
|
||||
8. **Create "Blackbox Tests" epic** — this epic will parent the blackbox test tasks created by the `/decompose` skill. It covers implementing the test scenarios defined in `tests/`.
|
||||
|
||||
**Save action**: Epics created via the configured tracker MCP. Also saved locally in `epics.md` with ticket IDs. If `tracker: local`, save locally only.
|
||||
**Save action**: Epics created via the configured tracker MCP. Also saved locally in `epics.md` with ticket IDs. If tracker availability fails, follow `.cursor/rules/tracker.mdc`; only if the user explicitly chooses `tracker: local`, save locally only with pending tracker markers.
|
||||
|
||||
@@ -133,4 +133,4 @@ Link to architecture.md and relevant component spec.]
|
||||
- `component` — a normal per-component epic
|
||||
- `cross-cutting` — a shared concern that spans ≥2 components
|
||||
- `tests` — the blackbox-tests epic (always exactly one)
|
||||
- Complexity points for child issues follow the project standard: 1, 2, 3, 5, 8. Do not create issues above 5 points — split them.
|
||||
- Complexity points for child issues follow the project standard: 1, 2, 3, 5. Do not create issues above 5 points — split them.
|
||||
|
||||
@@ -181,6 +181,8 @@ Categorized measurable criteria with markdown headers and bullet points:
|
||||
|
||||
Every criterion must have a measurable value. Vague criteria like "should be fast" are not acceptable — push for "less than 400ms end-to-end".
|
||||
|
||||
**AC must be design-independent**: describe testable outcomes only — no libraries, algorithms, params, or design choices. Implementation follows AC, never reverse. (IEEE 830 / Atlassian / GitScrum)
|
||||
|
||||
### input_data/
|
||||
|
||||
At least one file. Options:
|
||||
|
||||
@@ -24,6 +24,8 @@ Phase details live in `phases/` — read the relevant file before executing each
|
||||
- **Save immediately**: write artifacts to disk after each phase
|
||||
- **Delegate execution**: all code changes go through the implement skill via task files
|
||||
- **Ask, don't assume**: when scope or priorities are unclear, STOP and ask the user
|
||||
- **Exact-fit recommendations**: do not recommend a replacement pattern, library, service, architecture, algorithm, or "modern approach" merely because it improves structure or solves a similar class of problem. It must fit confirmed product constraints, acceptance criteria, operating context, integration boundaries, and current code realities. Otherwise reject it, mark it experimental, or ask the user before adding it to the roadmap.
|
||||
- **Per-mode API capability verification on replacements**: when a refactor proposes replacing or adding a library/SDK/framework/service that exposes multiple modes or configurations, pin the exact mode the refactored code will use (inputs, outputs, runtime) and verify *that mode* via mandatory `context7` lookup plus a saved Minimum Viable Example before promoting the recommendation to `Selected`. Capability claims at the category level ("supports A, B, C modes") must be cross-checked against the literal mode enumeration — `A, B → A+B` style conflations are the recurring silent-failure path.
|
||||
|
||||
## Context Resolution
|
||||
|
||||
@@ -57,7 +59,7 @@ Create REFACTOR_DIR and RUN_DIR if missing. If a RUN_DIR with the same name alre
|
||||
|
||||
Both modes produce `RUN_DIR/list-of-changes.md` (template: `templates/list-of-changes.md`). Both modes then convert that file into task files in TASKS_DIR during Phase 2.
|
||||
|
||||
**Guided mode cleanup**: after `RUN_DIR/list-of-changes.md` is created from the input file, delete the original input file to avoid duplication.
|
||||
**Guided mode cleanup**: after `RUN_DIR/list-of-changes.md` is created from the input file, delete the original input file only if it lives outside `RUN_DIR`. If the provided file is already the canonical `RUN_DIR/list-of-changes.md`, keep it as the audit record.
|
||||
|
||||
## Workflow
|
||||
|
||||
@@ -79,10 +81,10 @@ Both modes produce `RUN_DIR/list-of-changes.md` (template: `templates/list-of-ch
|
||||
- "refactor [specific target]" → skip phase 1 if docs exist
|
||||
- Default → all phases
|
||||
|
||||
**Testability-run specifics** (guided mode invoked by autodev existing-code flow Step 4):
|
||||
**Testability-run specifics** (guided mode invoked by autodev existing-code Step 4 or greenfield Step 8):
|
||||
- Run name is `01-testability-refactoring`.
|
||||
- Phase 3 (Safety Net) is skipped by design — no tests exist yet. Compensating control: the `list-of-changes.md` gate in Phase 1 must be reviewed and approved by the user before Phase 4 runs.
|
||||
- Scope is MINIMAL and surgical; reject change entries that drift into full refactor territory (see existing-code flow Step 4 for allowed/disallowed lists). Flagged entries go to `RUN_DIR/deferred_to_refactor.md` for Step 8 (optional full refactor) consideration.
|
||||
- Scope is MINIMAL and surgical; reject change entries that drift into full refactor territory (see the invoking flow's testability step for allowed/disallowed lists). Flagged entries go to `RUN_DIR/deferred_to_refactor.md` for the next optional full-refactor step or backlog consideration.
|
||||
- After Phase 4 (Execution) completes, write `RUN_DIR/testability_changes_summary.md` as Phase 4.5. Format: one bullet per applied change.
|
||||
```markdown
|
||||
# Testability Changes Summary ({{run_name}})
|
||||
|
||||
@@ -95,7 +95,7 @@ Also copy to project standard locations:
|
||||
|
||||
**Critical step — do not skip.** Before producing the change list, cross-reference documented business flows against actual implementation. This catches issues that static code inspection alone misses.
|
||||
|
||||
1. **Read documented flows**: Load `DOCUMENT_DIR/system-flows.md`, `DOCUMENT_DIR/architecture.md`, `DOCUMENT_DIR/module-layout.md`, every file under `DOCUMENT_DIR/contracts/`, and `SOLUTION_DIR/solution.md` (whichever exist). Extract every documented business flow, data path, architectural decision, module ownership boundary, and contract shape.
|
||||
1. **Read documented flows**: Load `DOCUMENT_DIR/system-flows.md`, `DOCUMENT_DIR/architecture.md` (paying special attention to its `## Architecture Vision` section — that's the user-confirmed structural intent), `DOCUMENT_DIR/glossary.md`, `DOCUMENT_DIR/module-layout.md`, every file under `DOCUMENT_DIR/contracts/`, and `SOLUTION_DIR/solution.md` (whichever exist). Extract every documented business flow, data path, architectural decision, module ownership boundary, and contract shape. Any refactor change that contradicts a confirmed Architecture Vision principle must either be rejected or surfaced to the user before being added to `list-of-changes.md` — those principles are not refactor targets without explicit user approval.
|
||||
|
||||
2. **Trace each flow through code**: For every documented flow (e.g., "video batch processing", "image tiling", "engine initialization"), walk the actual code path line by line. At each decision point ask:
|
||||
- Does the code match the documented/intended behavior?
|
||||
|
||||
@@ -7,14 +7,29 @@
|
||||
## 2a. Deep Research
|
||||
|
||||
1. Analyze current implementation patterns
|
||||
2. Research modern approaches for similar systems
|
||||
3. Identify what could be done differently
|
||||
4. Suggest improvements based on state-of-the-art practices
|
||||
2. Extract the **Project Constraint Matrix** from `problem.md`, `restrictions.md`, `acceptance_criteria.md`, current architecture/docs, and actual code constraints. Include required inputs/outputs, operating context, lifecycle assumptions, integration boundaries, non-functional targets, and hard disqualifiers.
|
||||
3. Research modern approaches for similar systems
|
||||
4. For each alternative pattern/library/service/architecture/algorithm, research intrinsic implementation constraints: required inputs/outputs, runtime assumptions, supported deployment modes, resource needs, operational limits, licensing/security constraints, and known failure reports.
|
||||
|
||||
**API Capability Verification — Per-Mode (MANDATORY, BLOCKING for proposed replacements)**
|
||||
|
||||
When a refactor recommendation replaces (or adds) a library/SDK/framework/service, the same per-mode verification used by `/research` Step 2 applies — selecting a replacement on category fit alone is the same silent-failure path. For every replacement candidate that has multiple modes or configurations:
|
||||
|
||||
1. **Pin the exact mode/configuration** the refactored code will use, in one explicit sentence. Inputs (data shapes, sensor counts, payloads, rates), outputs (per `acceptance_criteria.md` and contract files), runtime (matching the project's deployment).
|
||||
2. **Run `context7` (or equivalent docs lookup)** for the candidate. **Mandatory for every replacement library/SDK/framework candidate**, not optional. Minimum three queries per candidate: mode enumeration, project's exact mode (with input/output shapes), disqualifier probe ("does this mode produce the required output? are there published limitations on this runtime?"). Append URLs to `RUN_DIR/analysis/research_findings.md` references section.
|
||||
3. **Save a Minimum Viable Example (MVE)** for the pinned mode under `RUN_DIR/analysis/mve_evidence.md` with: source, inputs in example, outputs in example, project inputs, project outputs required, match assessment ✅/⚠️/❌. If no official example covers the project's exact configuration, the recommendation cannot be `Selected` based on category fit alone — it must be `Experimental only` (with required-evidence note) or `Rejected`.
|
||||
4. **Treat "the same library in a different mode" as a different recommendation.** If the project's pinned mode is `<X>` but the only documented evidence covers `<Y>`, do not silently soften the description. Open a separate recommendation row, with its own MVE, fit assessment, and disqualifiers.
|
||||
5. **Common silent-failure pattern**: a fact summary paraphrases docs as "supports A, B, C, D modes" when the docs actually mean "supports A; B; C and D as separate orthogonal modes" — no `A+B` combination exists. Cross-check paraphrased capability claims against the literal mode enumeration.
|
||||
|
||||
5. Identify what could be done differently
|
||||
6. Suggest improvements only when they fit the Project Constraint Matrix. A cleaner or more modern approach that violates product constraints must be marked `Rejected` or `Experimental only`, not added as a roadmap recommendation.
|
||||
|
||||
Write `RUN_DIR/analysis/research_findings.md`:
|
||||
- Current state analysis: patterns used, strengths, weaknesses
|
||||
- Alternative approaches per component: current vs alternative, pros/cons, migration effort
|
||||
- Prioritized recommendations: quick wins + strategic improvements
|
||||
- Constraint-fit table: recommendation, **pinned mode/config**, constraints checked, **API capability evidence (MVE link)**, evidence, mismatches/disqualifiers, status (`Selected` / `Rejected` / `Experimental only` / `Needs user decision`)
|
||||
- For every recommendation that replaces or adds a library/SDK/framework, append a **Restrictions × Candidate-Mode sub-matrix** that walks every numbered line of `restrictions.md` and `acceptance_criteria.md` against the candidate's pinned mode, marking each cell ✅ Pass / ❌ Fail / ❓ Verify / N/A with cited evidence. A recommendation cannot be `Selected` while any cell is ❌ or ❓.
|
||||
|
||||
## 2b. Solution Assessment & Hardening Tracks
|
||||
|
||||
@@ -22,6 +37,7 @@ Write `RUN_DIR/analysis/research_findings.md`:
|
||||
2. Identify weak points in codebase, map to specific code areas
|
||||
3. Perform gap analysis: acceptance criteria vs current state
|
||||
4. Prioritize changes by impact and effort
|
||||
5. Reject or escalate any proposed refactor that improves code structure while weakening required behavior, integration contracts, runtime constraints, safety/security posture, or acceptance criteria
|
||||
|
||||
Present optional hardening tracks for user to include in the roadmap:
|
||||
|
||||
@@ -47,6 +63,9 @@ Write `RUN_DIR/analysis/refactoring_roadmap.md`:
|
||||
- Gap analysis: what's missing, what needs improvement
|
||||
- Phased roadmap: Phase 1 (critical fixes), Phase 2 (major improvements), Phase 3 (enhancements)
|
||||
- Selected hardening tracks and their items
|
||||
- Applicability gate: each roadmap item must state constraint fit, mismatches, required evidence, and status (`Selected` / `Rejected` / `Experimental only` / `Needs user decision`)
|
||||
|
||||
**BLOCKING applicability gate**: Before 2c and 2d, every recommendation in the roadmap must be `Selected`. Items marked `Rejected` are excluded. Items marked `Experimental only` or `Needs user decision` require a user decision before task creation.
|
||||
|
||||
## 2c. Create Epic
|
||||
|
||||
@@ -55,7 +74,7 @@ Create a work item tracker epic for this refactoring run:
|
||||
1. Epic name: the RUN_DIR name (e.g., `01-testability-refactoring`)
|
||||
2. Create the epic via configured tracker MCP
|
||||
3. Record the Epic ID — all tasks in 2d will be linked under this epic
|
||||
4. If tracker unavailable, use `PENDING` placeholder and note for later
|
||||
4. If tracker is unavailable, follow `.cursor/rules/tracker.mdc`; only use `PENDING` placeholders if the user explicitly chooses `tracker: local`
|
||||
|
||||
## 2d. Task Decomposition
|
||||
|
||||
@@ -79,6 +98,12 @@ Convert the finalized `RUN_DIR/list-of-changes.md` into implementable task files
|
||||
**Self-verification**:
|
||||
- [ ] All acceptance criteria are addressed in gap analysis
|
||||
- [ ] Recommendations are grounded in actual code, not abstract
|
||||
- [ ] Every recommendation has been checked against the Project Constraint Matrix
|
||||
- [ ] No recommendation violates product restrictions, acceptance criteria, documented architecture decisions, or actual code integration boundaries
|
||||
- [ ] Every replacement library/SDK/framework recommendation has a pinned mode/config, a saved MVE in `mve_evidence.md`, and a Restrictions × Candidate-Mode sub-matrix with no ❌ or ❓ cells
|
||||
- [ ] `context7` (or equivalent) was consulted for every replacement library/SDK/framework recommendation
|
||||
- [ ] Paraphrased capability claims have been cross-checked against the literal mode-enumeration evidence (no `A, B → A+B` style conflation)
|
||||
- [ ] Rejected and experimental approaches are documented but not converted into implementation tasks without user approval
|
||||
- [ ] Roadmap phases are prioritized by impact
|
||||
- [ ] Epic created and all tasks linked to it
|
||||
- [ ] Every entry in list-of-changes.md has a corresponding task file in TASKS_DIR
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
- All `[TRACKER-ID]_refactor_*.md` files are present
|
||||
- Each task file has valid header fields (Task, Name, Description, Complexity, Dependencies)
|
||||
2. Verify `TASKS_DIR/_dependencies_table.md` includes the refactoring tasks
|
||||
3. Verify all tests pass (safety net from Phase 3 is green)
|
||||
3. Verify all tests pass (safety net from Phase 3 is green), unless this is a testability run where Phase 3 was intentionally skipped
|
||||
4. If any check fails, go back to the relevant phase to fix
|
||||
|
||||
## 4b. Delegate to Implement Skill
|
||||
@@ -21,9 +21,9 @@ The implement skill will:
|
||||
1. Parse task files and dependency graph from TASKS_DIR
|
||||
2. Detect already-completed tasks (skip non-refactoring tasks from prior workflow steps)
|
||||
3. Compute execution batches for the refactoring tasks
|
||||
4. Launch implementer subagents (up to 4 in parallel)
|
||||
4. Implement tasks sequentially in topological order (no subagents, no parallelism)
|
||||
5. Run code review after each batch
|
||||
6. Commit and push per batch
|
||||
6. Commit per batch and push only when the user approved pushing
|
||||
7. Update work item ticket status
|
||||
|
||||
Do NOT modify, skip, or abbreviate any part of the implement skill's workflow. The refactor skill is delegating execution, not optimizing it.
|
||||
@@ -47,7 +47,7 @@ After the implement skill completes:
|
||||
For each successfully completed refactoring task:
|
||||
|
||||
1. Transition the work item ticket status to **Done** via the configured tracker MCP
|
||||
2. If tracker unavailable, note the pending status transitions in `RUN_DIR/execution_log.md`
|
||||
2. If tracker is unavailable, follow `.cursor/rules/tracker.mdc`; if the user explicitly chose `tracker: local`, note the pending status transitions in `RUN_DIR/execution_log.md`
|
||||
|
||||
For any failed or blocked tasks, leave their status as-is (the implement skill already set them to In Testing or blocked).
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ For each component doc affected:
|
||||
## 7d. Update System-Level Documentation
|
||||
|
||||
If structural changes were made (new modules, removed modules, changed interfaces):
|
||||
1. Update `_docs/02_document/architecture.md` if architecture changed
|
||||
1. Update `_docs/02_document/architecture.md` if architecture changed — but **never edit the `## Architecture Vision` section**. That section is user-confirmed (plan Phase 2a.0 / document Step 4.5); if a refactor invalidates a vision principle, surface it to the user and let them update the vision themselves before continuing. Update only the technical sections below the Vision H2.
|
||||
2. Update `_docs/02_document/system-flows.md` if flow sequences changed
|
||||
3. Update `_docs/02_document/diagrams/components.md` if component relationships changed
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ Save as `RUN_DIR/list-of-changes.md`. Produced during Phase 1 (Discovery).
|
||||
- **Problem**: [what makes this problematic / untestable / coupled]
|
||||
- **Change**: [what to do — behavioral description, not implementation steps]
|
||||
- **Rationale**: [why this change is needed]
|
||||
- **Constraint Fit**: [which product constraints / acceptance criteria / integration boundaries this preserves; or "Rejected — violates ..."]
|
||||
- **Risk**: [low | medium | high]
|
||||
- **Dependencies**: [other change IDs this depends on, or "None"]
|
||||
|
||||
@@ -31,6 +32,7 @@ Save as `RUN_DIR/list-of-changes.md`. Produced during Phase 1 (Discovery).
|
||||
- **Problem**: [description]
|
||||
- **Change**: [description]
|
||||
- **Rationale**: [description]
|
||||
- **Constraint Fit**: [description]
|
||||
- **Risk**: [low | medium | high]
|
||||
- **Dependencies**: [C01, or "None"]
|
||||
```
|
||||
@@ -44,6 +46,8 @@ Save as `RUN_DIR/list-of-changes.md`. Produced during Phase 1 (Discovery).
|
||||
- **File(s)** must reference actual files verified to exist in the codebase
|
||||
- **Problem** describes the current state, not the desired state
|
||||
- **Change** describes what the system should do differently — behavioral, not prescriptive
|
||||
- **Constraint Fit** proves the change preserves confirmed product requirements, restrictions, acceptance criteria, architecture decisions, and integration contracts
|
||||
- Do not include changes whose only benefit is structural cleanliness if they weaken required behavior or violate constraints; record those as rejected in analysis instead
|
||||
- **Dependencies** reference other change IDs within this list; cross-run dependencies use tracker IDs
|
||||
- In guided mode, the input file entries are validated against actual code and enriched with file paths, risk, and dependencies before writing
|
||||
- In automatic mode, entries are derived from Phase 1 component analysis and Phase 2 research findings
|
||||
|
||||
@@ -30,6 +30,27 @@ Transform vague topics raised by users into high-quality, deliverable research r
|
||||
- **Internet-first investigation** — do not rely on training data for factual claims; search the web extensively for every sub-question, rephrase queries when results are thin, and keep searching until you have converging evidence from multiple independent sources
|
||||
- **Multi-perspective analysis** — examine every problem from at least 3 different viewpoints (e.g., end-user, implementer, business decision-maker, contrarian, domain expert, field practitioner); each perspective should generate its own search queries
|
||||
- **Question multiplication** — for each sub-question, generate multiple reformulated search queries (synonyms, related terms, negations, "what can go wrong" variants, practitioner-focused variants) to maximize coverage and uncover blind spots
|
||||
- **Component option breadth** — for every component area, build a broad option landscape before selecting. Search direct candidates, adjacent-domain alternatives, commercial/open-source variants, classical/simple baselines, current SOTA, and "do not use" failure cases. A component may not be narrowed to one candidate until alternatives have been searched and rejected with evidence.
|
||||
- **Component research depth** — for every serious component candidate, go beyond discovery pages. Read official docs, repository/license files, issue discussions, benchmarks, deployment guides, version/platform requirements, security notes, maintenance signals, and real-world failure reports. Extract evidence for inputs/outputs, lifecycle assumptions, runtime/storage/latency fit, integration boundaries, licensing, operational risks, and unsupported scenarios before assigning any selection status.
|
||||
- **Exact-fit component selection** — never select a component, tool, library, service, architecture pattern, or algorithm merely because it solves a similar class of problem. It must be proven compatible with the project's explicit operating context, constraints, required inputs/outputs, non-functional requirements, lifecycle assumptions, and acceptance criteria. If fit is unproven or mismatched, mark it `Rejected`, `Experimental only`, or escalate for user decision before it can shape the solution.
|
||||
- **Per-mode API capability verification** *(applies only to technical-component selection — see Research Output Class below)* — when a candidate library/SDK/framework/service exposes multiple modes or configurations, *the candidate is not a single thing*. Pin the exact mode the project will use (one explicit sentence: inputs, outputs, runtime), and verify *that mode* against the project's required inputs/outputs via official docs (mandatory `context7` lookup) plus a saved Minimum Viable Example. Capability claims at the category level ("supports X, Y, Z modes") must be cross-checked against the literal mode enumeration before being treated as project-applicable. Two modes of one library are two distinct candidates for the purposes of the Component Applicability Gate. Does not apply to non-technical research (concept comparison, market/policy investigation, knowledge organization, etc.).
|
||||
|
||||
## Research Output Class (BLOCKING — set in Step 1)
|
||||
|
||||
Before applying any of the technical-component gates (per-mode API capability verification, Component Applicability Gate, Restrictions × Candidate-Mode sub-matrix, MVE evidence, mandatory `context7` lookup), classify the research output into one of two classes. Record the decision in `00_question_decomposition.md` once, near the top, so every downstream step honors it.
|
||||
|
||||
| Class | What the output recommends or selects | Examples | Technical-component gates apply? |
|
||||
|-------|---------------------------------------|----------|----------------------------------|
|
||||
| **Technical-component selection** | One or more libraries, SDKs, frameworks, services, protocols, data formats, infrastructure patterns, algorithms, or APIs that will be implemented or operated against | "Pick a vector database", "Compare auth-token strategies for our API", "Should we use Kafka or RabbitMQ?", architecture / tech-stack / migration drafts (Mode A, Mode B) | **Yes — all gates active** |
|
||||
| **Non-technical investigation** | Concept comparisons, knowledge organization, root-cause investigation of an event, market/policy/regulatory/social analysis, literature review, decision support without committing to specific tooling | "Why did adoption stall in Q3?", "Compare phenomenology vs constructivism", "Map regulatory landscape for X", "What do practitioners say about onboarding under remote-first orgs?" | **No — skip API/MVE/sub-matrix gates; the rest of the 8-step engine still applies** |
|
||||
|
||||
How to decide:
|
||||
1. Inspect the question and the input files (`problem.md`, `restrictions.md`, `acceptance_criteria.md`, or the standalone input file).
|
||||
2. If the deliverable will name specific software/services/protocols that someone will then build with or operate, it is **Technical-component selection**.
|
||||
3. If the deliverable is a report, comparison, or recommendation that does not commit to specific tooling, it is **Non-technical investigation**.
|
||||
4. **Mixed runs are valid.** Some research questions have a non-technical core but include one technical sub-question (or vice versa). In that case classify per component area within the run, not the run as a whole, and note in `00_question_decomposition.md` which component areas trigger the technical-component gates.
|
||||
|
||||
When the run is purely **Non-technical investigation**, the rest of the research engine — question decomposition, perspective rotation, exhaustive web search, fact extraction, comparison framework, reasoning chain, validation, deliverable formatting — still applies in full. The sections that get skipped are explicitly the technical gates listed in the table above.
|
||||
|
||||
## Context Resolution
|
||||
|
||||
|
||||
@@ -27,13 +27,26 @@
|
||||
- [ ] Iterative deepening completed: follow-up questions from initial findings were searched
|
||||
- [ ] No sub-question relies solely on training data without web verification
|
||||
|
||||
## Component Option Breadth
|
||||
|
||||
- [ ] `00_question_decomposition.md` contains a Component Option Search Plan
|
||||
- [ ] Every component area was searched across simple baseline, established production, open-source, commercial/vendor, current SOTA, adjacent-domain, no-build/defer, and known-bad options where applicable
|
||||
- [ ] Every component area has at least 3 realistic candidates, or a documented explanation of why broad searches found fewer
|
||||
- [ ] Each lead candidate has official/source-of-truth evidence plus independent validation when available
|
||||
- [ ] Each component area includes at least one baseline/fallback option and at least one rejected or experimental option when possible
|
||||
- [ ] Alternative names, synonyms, and neighboring-domain terms were searched before declaring the option landscape complete
|
||||
- [ ] Licensing, runtime, platform, maintenance, and unsupported-scenario searches were performed for every lead, fallback, and rejected candidate
|
||||
|
||||
## Mode A Specific
|
||||
|
||||
- [ ] Phase 1 completed: AC assessment was presented to and confirmed by user
|
||||
- [ ] AC assessment consistent: Solution draft respects the (possibly adjusted) acceptance criteria and restrictions
|
||||
- [ ] Competitor analysis included: Existing solutions were researched
|
||||
- [ ] All components have comparison tables: Each component lists alternatives with tools, advantages, limitations, security, cost
|
||||
- [ ] Component options are broad: component tables include baseline, production, open-source, commercial/vendor, SOTA/research, adjacent-domain, defer/no-build, and disqualified options where applicable
|
||||
- [ ] Tools/libraries verified: Suggested tools actually exist and work as described
|
||||
- [ ] Component fit matrix completed: `06_component_fit_matrix.md` (or `06_component_fit_matrix/` if split) exists and every selected component/tool/pattern is marked `Selected`
|
||||
- [ ] No field-adjacent substitution: no selected candidate is chosen only because it solves a similar class of problem while failing the project's explicit constraints
|
||||
- [ ] Testing strategy covers AC: Tests map to acceptance criteria
|
||||
- [ ] Tech stack documented (if Phase 3 ran): `tech_stack.md` has evaluation tables, risk assessment, and learning requirements
|
||||
- [ ] Security analysis documented (if Phase 4 ran): `security_analysis.md` has threat model and per-component controls
|
||||
@@ -45,6 +58,9 @@
|
||||
- [ ] New draft is self-contained: Written as if from scratch, no "updated" markers
|
||||
- [ ] Performance column included: Mode B comparison tables include performance characteristics
|
||||
- [ ] Previous draft issues addressed: Every finding in the table is resolved in the new draft
|
||||
- [ ] Existing selected components were challenged against a broad alternative landscape before being kept
|
||||
- [ ] Existing component fit audited: every old and new component/tool/pattern was checked against `restrictions.md`, `acceptance_criteria.md`, and the Project Constraint Matrix
|
||||
- [ ] Rejected/experimental candidates are not lead recommendations unless the user explicitly accepted the risk
|
||||
|
||||
## Timeliness Check (High-Sensitivity Domain BLOCKING)
|
||||
|
||||
@@ -64,7 +80,7 @@ When the research topic has Critical or High sensitivity level:
|
||||
## Target Audience Consistency Check (BLOCKING)
|
||||
|
||||
- [ ] Research boundary clearly defined: `00_question_decomposition.md` has clear population/geography/timeframe/level boundaries
|
||||
- [ ] Every source has target audience annotated in `01_source_registry.md`
|
||||
- [ ] Every source has target audience annotated in `01_source_registry.md` (or category files under `01_source_registry/` if split)
|
||||
- [ ] Mismatched sources properly handled (excluded, annotated, or marked reference-only)
|
||||
- [ ] No audience confusion in fact cards: Every fact has target audience consistent with research boundary
|
||||
- [ ] No audience confusion in the report: Policies/research/data cited have consistent target audiences
|
||||
@@ -76,3 +92,33 @@ When the research topic has Critical or High sensitivity level:
|
||||
- [ ] Cited facts have corresponding statements in the original text (no over-interpretation)
|
||||
- [ ] Source publication/update dates annotated; technical docs include version numbers
|
||||
- [ ] Unverifiable information annotated `[limited source]` and not sole support for core conclusions
|
||||
|
||||
## Exact-Fit Validation (BLOCKING)
|
||||
|
||||
- [ ] Project Constraint Matrix extracted from problem context before component selection
|
||||
- [ ] Component fit matrix includes `Component Area`, `Option Family`, and `Pinned Mode/Config` columns
|
||||
- [ ] Every selected component/tool/library/service/pattern/algorithm has evidence for required inputs/outputs and integration boundaries
|
||||
- [ ] Every selected candidate has evidence for the operating context and lifecycle assumptions it must support
|
||||
- [ ] Every selected candidate has evidence for non-functional targets that are binding for the project
|
||||
- [ ] Known unsupported scenarios and failure reports were searched for every selected candidate
|
||||
- [ ] Mismatches are recorded as disqualifiers, not softened into generic limitations
|
||||
- [ ] Any candidate with unproven fit is marked `Experimental only` or escalated for user decision
|
||||
- [ ] Any candidate with documented constraint conflict is marked `Rejected`
|
||||
|
||||
## API Capability Verification (BLOCKING)
|
||||
|
||||
**Applicability**: this checklist applies only when the run is classified as **Technical-component selection** (see SKILL.md → Research Output Class). For non-technical research (concept comparison, market/policy investigation, root-cause analysis, knowledge organization), skip this checklist entirely and note the skip in `05_validation_log.md`. For mixed runs, apply only to technical component areas.
|
||||
|
||||
For every lead candidate that is a library/SDK/framework/service:
|
||||
|
||||
- [ ] The exact mode/configuration the project will use is pinned in one explicit sentence (inputs, outputs, runtime); no vague "supports X" language
|
||||
- [ ] `context7` (or equivalent docs lookup) was run for the candidate, with at least 3 queries: mode enumeration, project's exact mode, disqualifier probe
|
||||
- [ ] All consulted URLs from context7 / official docs are appended to `01_source_registry.md` (or files under `01_source_registry/` if split)
|
||||
- [ ] A Minimum Viable Example (MVE) was saved for the pinned mode in `02_fact_cards.md` / `02_fact_cards/` (or `02_mve_evidence.md`) with: source, inputs in example, outputs in example, project inputs, project outputs required, match assessment ✅/⚠️/❌
|
||||
- [ ] When the MVE inputs or outputs do not exactly match the project's, the mismatch is cited from the official docs (not inferred), and the candidate is `Experimental only` or `Rejected`
|
||||
- [ ] When a library has multiple modes, each project-relevant mode appears as its own candidate row (not a single library row that softens across modes)
|
||||
- [ ] Restrictions × Candidate-Modes sub-matrix in `06_component_fit_matrix.md` (or files under `06_component_fit_matrix/` if split) is filled for every lead candidate, with one row per numbered restriction and per numbered acceptance criterion
|
||||
- [ ] Sub-matrix uses ✅ / ❌ / ❓ / N/A only — no free-form prose substitutes
|
||||
- [ ] No `Selected` candidate has any ❌ or ❓ cell in its sub-matrix
|
||||
- [ ] "Validation gate required" footnotes are explicitly classified as either *API capability* (must be resolved here) or *runtime quality* (may be carried forward)
|
||||
- [ ] Paraphrased capability claims in fact cards have been cross-checked against the literal mode-enumeration evidence (no `mono, inertial → mono-inertial` style conflation)
|
||||
|
||||
@@ -89,7 +89,7 @@ Value Translation:
|
||||
|
||||
## Source Registry Entry Template
|
||||
|
||||
For each source consulted, immediately append to `01_source_registry.md`:
|
||||
For each source consulted, immediately append to `01_source_registry.md` (or the appropriate category file under `01_source_registry/` if the artifact has been split — see splittable-artifacts convention in `steps/00_project-integration.md`):
|
||||
```markdown
|
||||
## Source #[number]
|
||||
- **Title**: [source title]
|
||||
|
||||
@@ -57,22 +57,49 @@ RESEARCH_DIR/
|
||||
├── 03_comparison_framework.md # Step 4 output: selected framework and populated data
|
||||
├── 04_reasoning_chain.md # Step 6 output: fact → conclusion reasoning
|
||||
├── 05_validation_log.md # Step 7 output: use-case validation results
|
||||
├── 06_component_fit_matrix.md # Step 7.5 output: component exact-fit gate
|
||||
└── raw/ # Raw source archive (optional)
|
||||
├── source_1.md
|
||||
└── source_2.md
|
||||
```
|
||||
|
||||
#### Splittable artifacts — Layout convention
|
||||
|
||||
The following three artifacts MAY equivalently be a **folder** of the same base name when the single-file form has grown unwieldy (typically ≳ 1000 lines or ≳ 200 KB):
|
||||
|
||||
- `01_source_registry.md` ↔ `01_source_registry/`
|
||||
- `02_fact_cards.md` ↔ `02_fact_cards/`
|
||||
- `06_component_fit_matrix.md` ↔ `06_component_fit_matrix/`
|
||||
|
||||
When using the folder form:
|
||||
|
||||
- Place a `00_summary.md` index file at the folder root with a short common summary table and the cross-cutting status the single-file form would have carried in its preamble.
|
||||
- Split per-entry content into category files (e.g. one file per sub-question or per component): `SQ1_*.md`, `C1_*.md`, etc. Keep entry numbering global across the folder so cross-references like "Source #42" still resolve to exactly one place.
|
||||
- Cross-references from outside the folder may point at either `01_source_registry/00_summary.md` (for the index) or directly at the relevant category file.
|
||||
|
||||
```
|
||||
RESEARCH_DIR/01_source_registry/ # split form (when single-file is too large)
|
||||
├── 00_summary.md # index + investigation status + compact source table
|
||||
├── SQ1_existing_systems.md # category file
|
||||
├── SQ2_canonical_pipeline.md # category file
|
||||
├── C1_vio.md # per-component file
|
||||
└── ...
|
||||
```
|
||||
|
||||
Throughout the rest of this skill (other steps, references, templates), the singular `XX.md` form is used as a logical name; treat each occurrence as applying equally to the folder form when the artifact has been split.
|
||||
|
||||
### Save Timing & Content
|
||||
|
||||
| Step | Save immediately after completion | Filename |
|
||||
|------|-----------------------------------|----------|
|
||||
| Mode A Phase 1 | AC & restrictions assessment tables | `00_ac_assessment.md` |
|
||||
| Step 0-1 | Question type classification + sub-question list | `00_question_decomposition.md` |
|
||||
| Step 2 | Each consulted source link, tier, summary | `01_source_registry.md` |
|
||||
| Step 3 | Each fact card (statement + source + confidence) | `02_fact_cards.md` |
|
||||
| Step 2 | Each consulted source link, tier, summary | `01_source_registry.md` *(splittable, see convention)* |
|
||||
| Step 3 | Each fact card (statement + source + confidence) | `02_fact_cards.md` *(splittable, see convention)* |
|
||||
| Step 4 | Selected comparison framework + initial population | `03_comparison_framework.md` |
|
||||
| Step 6 | Reasoning process for each dimension | `04_reasoning_chain.md` |
|
||||
| Step 7 | Validation scenarios + results + review checklist | `05_validation_log.md` |
|
||||
| Step 7.5 | Component exact-fit gate and selection status | `06_component_fit_matrix.md` *(splittable, see convention)* |
|
||||
| Step 8 | Complete solution draft | `OUTPUT_DIR/solution_draft##.md` |
|
||||
|
||||
### Save Principles
|
||||
@@ -90,11 +117,12 @@ RESEARCH_DIR/
|
||||
|------|---------|----------------|
|
||||
| `00_ac_assessment.md` | AC & restrictions assessment (Mode A only) | After Phase 1 completion |
|
||||
| `00_question_decomposition.md` | Question type, sub-question list | After Step 0-1 completion |
|
||||
| `01_source_registry.md` | All source links and summaries | Continuously updated during Step 2 |
|
||||
| `02_fact_cards.md` | Extracted facts and sources | Continuously updated during Step 3 |
|
||||
| `01_source_registry.md` *(splittable)* | All source links and summaries | Continuously updated during Step 2 |
|
||||
| `02_fact_cards.md` *(splittable)* | Extracted facts and sources | Continuously updated during Step 3 |
|
||||
| `03_comparison_framework.md` | Selected framework and populated data | After Step 4 completion |
|
||||
| `04_reasoning_chain.md` | Fact → conclusion reasoning | After Step 6 completion |
|
||||
| `05_validation_log.md` | Use-case validation and review | After Step 7 completion |
|
||||
| `06_component_fit_matrix.md` *(splittable)* | Exact-fit matrix for every proposed component/tool/pattern with status `Selected` / `Rejected` / `Experimental only` / `Needs user decision` | Before Step 8 deliverable formatting |
|
||||
| `OUTPUT_DIR/solution_draft##.md` | Complete solution draft | After Step 8 completion |
|
||||
| `OUTPUT_DIR/tech_stack.md` | Tech stack evaluation and decisions | After Phase 3 (optional) |
|
||||
| `OUTPUT_DIR/security_analysis.md` | Threat model and security controls | After Phase 4 (optional) |
|
||||
|
||||
@@ -6,7 +6,9 @@ Triggered when no `solution_draft*.md` files exist in OUTPUT_DIR, or when the us
|
||||
|
||||
**Role**: Professional software architect
|
||||
|
||||
A focused preliminary research pass **before** the main solution research. The goal is to validate that the acceptance criteria and restrictions are realistic before designing a solution around them.
|
||||
> **AC must be design-independent**: describe testable outcomes only — no libraries, algorithms, params, or design choices. Implementation follows AC, never reverse. (IEEE 830 / Atlassian / GitScrum)
|
||||
|
||||
A focused preliminary research pass **before** the main solution research. The goal is to validate that the acceptance criteria and restrictions are realistic before designing a solution around them. Any revision proposed in this phase must respect the design-independence rule above — propose AC changes as outcome/budget edits, not as implementation prescriptions.
|
||||
|
||||
**Input**: All files from INPUT_DIR (or INPUT_FILE in standalone mode)
|
||||
|
||||
@@ -73,16 +75,18 @@ Full 8-step research methodology. Produces the first solution draft.
|
||||
**Task** (drives the 8-step engine):
|
||||
1. Research existing/competitor solutions for similar problems — search broadly across industries and adjacent domains, not just the obvious competitors
|
||||
2. Research the problem thoroughly — all possible ways to solve it, split into components; search for how different fields approach analogous problems
|
||||
3. For each component, research all possible solutions and find the most efficient state-of-the-art approaches — use multiple query variants and perspectives from Step 1
|
||||
4. For each promising approach, search for real-world deployment experience: success stories, failure reports, lessons learned, and practitioner opinions
|
||||
5. Search for contrarian viewpoints — who argues against the common approaches and why? What failure modes exist?
|
||||
6. Verify that suggested tools/libraries actually exist and work as described — check official repos, latest releases, and community health (stars, recent commits, open issues)
|
||||
7. Include security considerations in each component analysis
|
||||
8. Provide rough cost estimates for proposed solutions
|
||||
3. Derive a **Project Constraint Matrix** before evaluating component options. Extract exact constraints from `problem.md`, `restrictions.md`, `acceptance_criteria.md`, input data notes, and the Phase 1 AC assessment. Include required inputs/outputs, operating context, runtime envelope, data availability, lifecycle boundaries, non-functional targets, integration boundaries, security constraints, and explicit out-of-scope decisions.
|
||||
4. For each component, research all possible solutions and find the most efficient state-of-the-art approaches — use multiple query variants and perspectives from Step 1
|
||||
5. For each promising approach, search for real-world deployment experience: success stories, failure reports, lessons learned, and practitioner opinions
|
||||
6. Search for contrarian viewpoints — who argues against the common approaches and why? What failure modes exist?
|
||||
7. Verify that suggested tools/libraries actually exist and work as described — check official repos, latest releases, and community health (stars, recent commits, open issues)
|
||||
8. For every candidate component/tool/library/service/pattern/algorithm, prove exact fit against the Project Constraint Matrix. A field-adjacent solution is not selectable unless its documented implementation assumptions match the project's constraints. Mismatches must be recorded as disqualifiers and the candidate marked `Rejected`, `Experimental only`, or `Needs user decision`.
|
||||
9. Include security considerations in each component analysis
|
||||
10. Provide rough cost estimates for proposed solutions
|
||||
|
||||
Be concise in formulating. The fewer words, the better, but do not miss any important details.
|
||||
|
||||
**Save action**: Write `OUTPUT_DIR/solution_draft##.md` using template: `templates/solution_draft_mode_a.md`
|
||||
**Save action**: Write `RESEARCH_DIR/06_component_fit_matrix.md` (or its split-folder equivalent under `RESEARCH_DIR/06_component_fit_matrix/`, per the splittable-artifacts convention in `00_project-integration.md`) before the final draft, then write `OUTPUT_DIR/solution_draft##.md` using template: `templates/solution_draft_mode_a.md`
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -10,18 +10,25 @@ Full 8-step research methodology applied to assessing and improving an existing
|
||||
|
||||
**Task** (drives the 8-step engine):
|
||||
1. Read the existing solution draft thoroughly
|
||||
2. Research in internet extensively — for each component/decision in the draft, search for:
|
||||
2. Derive or refresh the **Project Constraint Matrix** from all files in INPUT_DIR. Include required inputs/outputs, operating context, runtime envelope, data availability, lifecycle boundaries, non-functional targets, integration boundaries, security constraints, and explicit out-of-scope decisions.
|
||||
3. Audit every component/decision in the existing draft against the Project Constraint Matrix before researching alternatives:
|
||||
- If a component's documented implementation assumptions match the project constraints, keep it eligible and record evidence.
|
||||
- If fit is unproven, mark it `Experimental only` until evidence is found.
|
||||
- If constraints conflict, mark it `Rejected` and search for alternatives.
|
||||
- If rejecting it changes product behavior or risk materially, escalate for user decision.
|
||||
4. Research in internet extensively — for each component/decision in the draft, search for:
|
||||
- Known problems and limitations of the chosen approach
|
||||
- What practitioners say about using it in production
|
||||
- Better alternatives that may have emerged recently
|
||||
- Common failure modes and edge cases
|
||||
- How competitors/similar projects solve the same problem differently
|
||||
3. Search specifically for contrarian views: "why not [chosen approach]", "[chosen approach] criticism", "[chosen approach] failure"
|
||||
4. Identify security weak points and vulnerabilities — search for CVEs, security advisories, and known attack vectors for each technology in the draft
|
||||
5. Identify performance bottlenecks — search for benchmarks, load test results, and scalability reports
|
||||
6. For each identified weak point, search for multiple solution approaches and compare them
|
||||
7. Based on findings, form a new solution draft in the same format
|
||||
5. Search specifically for contrarian views: "why not [chosen approach]", "[chosen approach] criticism", "[chosen approach] failure"
|
||||
6. Identify security weak points and vulnerabilities — search for CVEs, security advisories, and known attack vectors for each technology in the draft
|
||||
7. Identify performance bottlenecks — search for benchmarks, load test results, and scalability reports
|
||||
8. For each identified weak point, search for multiple solution approaches and compare them
|
||||
9. For every revised candidate, prove exact fit against the Project Constraint Matrix. Do not select field-adjacent or "similar problem" options unless their intrinsic implementation constraints match the project.
|
||||
10. Based on findings, form a new solution draft in the same format
|
||||
|
||||
**Save action**: Write `OUTPUT_DIR/solution_draft##.md` (incremented) using template: `templates/solution_draft_mode_b.md`
|
||||
**Save action**: Write `RESEARCH_DIR/06_component_fit_matrix.md` (or its split-folder equivalent under `RESEARCH_DIR/06_component_fit_matrix/`, per the splittable-artifacts convention in `00_project-integration.md`) before the final draft, then write `OUTPUT_DIR/solution_draft##.md` (incremented) using template: `templates/solution_draft_mode_b.md`
|
||||
|
||||
**Optional follow-up**: After Mode B completes, the user can request Phase 3 (Tech Stack Consolidation) or Phase 4 (Security Deep Dive) using the revised draft. These phases work identically to their Mode A descriptions in `steps/01_mode-a-initial-research.md`.
|
||||
|
||||
@@ -40,6 +40,7 @@ Key principle: Critical-sensitivity topics (AI/LLMs, blockchain) require sources
|
||||
- "What existing/competitor solutions address this problem?"
|
||||
- "What are the component parts of this problem?"
|
||||
- "For each component, what are the state-of-the-art solutions?"
|
||||
- "For each component, what are the practical alternatives across simple baseline, established production option, open-source option, commercial option, current SOTA, adjacent-domain option, and no-build/defer option?"
|
||||
- "What are the security considerations per component?"
|
||||
- "What are the cost implications of each approach?"
|
||||
|
||||
@@ -48,6 +49,7 @@ Key principle: Critical-sensitivity topics (AI/LLMs, blockchain) require sources
|
||||
- "What are the security vulnerabilities in the proposed architecture?"
|
||||
- "Where are the performance bottlenecks?"
|
||||
- "What solutions exist for each identified issue?"
|
||||
- "For each component already selected in the draft, what alternatives should be considered before keeping, replacing, or rejecting it?"
|
||||
|
||||
**General sub-question patterns** (use when applicable):
|
||||
- **Sub-question A**: "What is X and how does it work?" (Definition & mechanism)
|
||||
@@ -84,6 +86,27 @@ For **each sub-question**, generate **at least 3-5 search query variants** befor
|
||||
|
||||
Record all planned queries in `00_question_decomposition.md` alongside each sub-question.
|
||||
|
||||
#### Component Option Breadth (MANDATORY)
|
||||
|
||||
Before Step 2, identify the component areas implied by the problem and create a search plan for options in each area. A component area is any replaceable tool, library, model, service, algorithm, data format, protocol, infrastructure pattern, or validation approach that could materially affect the solution.
|
||||
|
||||
For every component area, generate search queries for these option families unless clearly not applicable:
|
||||
- **Simple baseline**: low-complexity classical or manual approach that can serve as a fallback or regression baseline.
|
||||
- **Established production option**: mature library/service/pattern with field usage.
|
||||
- **Open-source candidate**: permissive-license option with inspectable implementation and community history.
|
||||
- **Commercial/vendor option**: paid or vendor-supported option, including SDK/platform constraints.
|
||||
- **Current SOTA / research option**: recent model, paper, or benchmark leader that may be promising but immature.
|
||||
- **Adjacent-domain option**: solution from a neighboring domain with similar constraints.
|
||||
- **No-build / defer option**: whether the component can be avoided, simplified, or moved out of scope.
|
||||
- **Known bad option**: candidate or family that appears attractive but has documented failure modes or disqualifiers.
|
||||
|
||||
For each component area, record:
|
||||
- Candidate names and option families to search.
|
||||
- At least 5 query variants covering alternatives, comparisons, limitations, licensing, runtime/scale, and exact project constraints.
|
||||
- The minimum evidence needed to mark a candidate `Selected`, `Rejected`, `Experimental only`, or `Needs user decision`.
|
||||
|
||||
Add this as a "Component Option Search Plan" section in `00_question_decomposition.md`.
|
||||
|
||||
**Research Subject Boundary Definition (BLOCKING - must be explicit)**:
|
||||
|
||||
When decomposing questions, you must explicitly define the **boundaries of the research subject**:
|
||||
@@ -94,6 +117,9 @@ When decomposing questions, you must explicitly define the **boundaries of the r
|
||||
| **Geography** | Which region is being studied? | Chinese universities vs US universities vs global |
|
||||
| **Timeframe** | Which period is being studied? | Post-2020 vs full historical picture |
|
||||
| **Level** | Which level is being studied? | Undergraduate vs graduate vs vocational |
|
||||
| **Operating context** | What exact environment, lifecycle phase, and runtime conditions must the solution support? | In-flight embedded runtime vs offline post-processing; production web traffic vs admin batch job |
|
||||
| **Required interfaces** | What inputs, outputs, protocols, data shapes, and ownership boundaries are fixed? | One camera vs stereo rig; REST API vs message queue; local file boundary vs service API |
|
||||
| **Non-functional envelope** | What latency, throughput, storage, memory, availability, safety, security, cost, and maintainability targets are binding? | <400 ms p95, 8 GB RAM, 99.9% availability, reversible migrations |
|
||||
|
||||
**Common mistake**: User asks about "university classroom issues" but sources include policies targeting "K-12 students" — mismatched target populations will invalidate the entire research.
|
||||
|
||||
@@ -116,9 +142,11 @@ Record the audit result in `00_question_decomposition.md` as a "Completeness Aud
|
||||
- Summary of relevant problem context from INPUT_DIR
|
||||
- Classified question type and rationale
|
||||
- **Research subject boundary definition** (population, geography, timeframe, level)
|
||||
- **Project Constraint Matrix summary** (operating context, required interfaces, non-functional envelope, lifecycle assumptions, and hard disqualifiers extracted from input files)
|
||||
- List of decomposed sub-questions
|
||||
- **Chosen perspectives** (at least 3 from the Perspective Rotation table) with rationale
|
||||
- **Search query variants** for each sub-question (at least 3-5 per sub-question)
|
||||
- **Component Option Search Plan** (component areas, option families, candidate names, query variants, required evidence)
|
||||
- **Completeness audit** (taxonomy cross-reference + domain discovery results)
|
||||
4. Write TodoWrite to track progress
|
||||
|
||||
@@ -132,7 +160,7 @@ Tier sources by authority, **prioritize primary sources** (L1 > L2 > L3 > L4). C
|
||||
|
||||
**Tool Usage**:
|
||||
- Use `WebSearch` for broad searches; `WebFetch` to read specific pages
|
||||
- Use the `context7` MCP server (`resolve-library-id` then `get-library-docs`) for up-to-date library/framework documentation
|
||||
- Use the `context7` MCP server (`resolve-library-id` then `query-docs` / `get-library-docs`) for up-to-date library/framework documentation. **Mandatory per lead candidate** — see "API Capability Verification" below.
|
||||
- Always cross-verify training data claims against live sources for facts that may have changed (versions, APIs, deprecations, security advisories)
|
||||
- When citing web sources, include the URL and date accessed
|
||||
|
||||
@@ -145,17 +173,77 @@ Do not stop at the first few results. The goal is to build a comprehensive evide
|
||||
- Consult at least **2 different source tiers** per sub-question (e.g., L1 official docs + L4 community discussion)
|
||||
- If initial searches yield fewer than 3 relevant sources for a sub-question, **broaden the search** with alternative terms, related domains, or analogous problems
|
||||
|
||||
**Minimum search effort per component area**:
|
||||
- Search every option family from the "Component Option Search Plan" before choosing a lead candidate.
|
||||
- For each lead, fallback, or rejected candidate, search at least one official/source-of-truth page and at least one independent validation source when available.
|
||||
- Search `"[component] alternatives"`, `"[candidate] vs [alternative]"`, `"[candidate] limitations"`, `"[candidate] license"`, `"[candidate] production"`, and `"[candidate] [binding project constraint]"`.
|
||||
- If fewer than 3 realistic candidates are found for a component area, explicitly document why the landscape is narrow and search adjacent domains before accepting that result.
|
||||
- Include at least one simple baseline and one "do not use" or disqualified candidate per component area when possible; these prevent false confidence in the selected option.
|
||||
|
||||
**Candidate implementation-limit searches (MANDATORY)**:
|
||||
For every component/tool/library/service/pattern/algorithm that may be selected or recommended, search for its intrinsic implementation constraints. Do not rely on product category labels, marketing summaries, or examples from a different operating context. Include query variants for:
|
||||
- Official supported inputs/outputs, protocols, data formats, and deployment modes
|
||||
- Required hardware/runtime/platform/version constraints
|
||||
- Timing, throughput, memory, storage, synchronization, and scaling assumptions
|
||||
- Lifecycle assumptions: offline vs online, batch vs real time, development vs production, single tenant vs multi tenant, local vs networked
|
||||
- Known unsupported scenarios, limitations, issue reports, production failures, and workarounds
|
||||
- Licensing, security, maintenance, and community-health constraints
|
||||
- Exact phrases from the project's restrictions and acceptance criteria combined with the candidate name
|
||||
|
||||
**API Capability Verification — Per-Mode (MANDATORY, BLOCKING for lead candidates)**:
|
||||
|
||||
**Applicability**: this section applies only when the run is classified as **Technical-component selection** in the SKILL's Research Output Class section, and only to lead candidates that are libraries/SDKs/frameworks/services/protocols/data formats with multiple modes or configurations. For non-technical research (concept comparison, market/policy investigation, knowledge organization, root-cause analysis without tooling commitments), skip this entire sub-section and continue with the rest of Step 2 — the broader candidate implementation-limit search above is sufficient. State the skip explicitly once in `02_fact_cards.md` (or in `02_fact_cards/00_summary.md` if split): `API Capability Verification: not applicable — this run is a Non-technical investigation, no library/SDK/service candidates`.
|
||||
|
||||
Most libraries/SDKs/services expose **multiple modes or configurations** (e.g., monocular vs stereo VO, sync vs async API, batch vs streaming inference, write-through vs write-behind cache). Selecting a candidate "because it supports X" without pinning *which mode* the project will use, and *whether that exact mode produces the required outputs from the required inputs*, is the most common silent-failure path in research. A library can support a class of problem in mode A while being unusable for the project's specific configuration in mode B.
|
||||
|
||||
For every lead candidate that is a library/SDK/framework/service with multiple modes or configurations, do the following — in this order, before marking the candidate `Selected`:
|
||||
|
||||
1. **Pin the exact mode/configuration the project will use.**
|
||||
Derived from the Project Constraint Matrix: which inputs are available (sensor count, sensor types, data shapes, rates), which outputs are required (per `acceptance_criteria.md` and contract files), which hardware/runtime is fixed (per `restrictions.md`). Write this as a single sentence: "We will use `<library>` in `<mode/config>` with inputs `<list>` and expect outputs `<list>` on `<runtime>`." Do not progress past this step on a vague mode description.
|
||||
|
||||
2. **Run `context7` (or equivalent docs lookup) for the candidate** — this is **mandatory for every lead library/SDK/framework candidate**, not optional. Minimum three queries per candidate:
|
||||
1. *Mode enumeration*: "What modes/configurations does `<library>` support? List every value of the mode/config enum and what each requires as input."
|
||||
2. *Project's exact mode*: "Show a minimum runnable example of `<library>` in `<the pinned mode>` with `<the project's input shape>`. What does it produce?"
|
||||
3. *Disqualifier probe*: "Does `<library>` `<the pinned mode>` produce `<the required output>`? Are there published limitations of `<the pinned mode>` for `<the project's runtime/hardware>`?"
|
||||
|
||||
For services without context7 coverage, use official docs site + WebFetch on the API reference page + the project's example/tutorial directory in the source repo. Append every consulted URL to `01_source_registry.md` (or the appropriate category file under `01_source_registry/` if split — see splittable-artifacts convention in `00_project-integration.md`).
|
||||
|
||||
3. **Save a Minimum Viable Example (MVE) for the pinned mode.**
|
||||
Append to `02_fact_cards.md` / `02_fact_cards/` (or a sibling `02_mve_evidence.md`) at least one block per lead library candidate with:
|
||||
|
||||
```markdown
|
||||
## MVE — <library> in <pinned mode>
|
||||
- **Source**: <official URL or context7 reference, with date>
|
||||
- **Inputs in the example**: <e.g., 2 calibrated cameras + IMU at 200 Hz>
|
||||
- **Outputs in the example**: <e.g., 6-DoF pose with covariance>
|
||||
- **Project inputs**: <e.g., 1 camera + IMU at 200 Hz>
|
||||
- **Project outputs required**: <e.g., 6-DoF pose with metric translation>
|
||||
- **Match assessment**: ✅ exact match / ⚠️ partial (specify dimension) / ❌ mismatch (specify dimension)
|
||||
- **If ⚠️ or ❌**: cite the official-docs sentence that establishes the mismatch.
|
||||
```
|
||||
|
||||
If no official example covers the project's exact configuration → the candidate cannot be marked `Selected` based on category fit alone. Status must be `Experimental only` (with required-evidence note) or `Rejected` (when the docs explicitly disqualify the configuration).
|
||||
|
||||
4. **Bind every numbered Restriction and Acceptance Criterion to the candidate's pinned mode.**
|
||||
For each numbered line in `restrictions.md` and `acceptance_criteria.md`, decide one of: `Pass` (the pinned mode satisfies it with cited evidence), `Fail` (the pinned mode contradicts it with cited evidence), `Verify` (no evidence either way; deeper investigation required), `N/A` (the line is irrelevant to this component area). Record this in `02_fact_cards.md` (or the candidate's per-component file under `02_fact_cards/` if split) under the candidate's MVE block. The structural matrix in Step 7.5 reads from these bindings.
|
||||
|
||||
5. **Treat "the same library in a different mode" as a different candidate.**
|
||||
If the project's pinned mode is `Monocular` but the only documented evidence covers `Stereo`, do not silently soften "rotation only" into "rotation + translation". Open a separate candidate row for the Monocular mode, with its own MVE, fit assessment, and disqualifiers. Two modes of one library are two distinct candidates for the purposes of this gate.
|
||||
|
||||
**Common silent-failure pattern this guards against**: a fact card paraphrases the docs as "supports A, B, C, D modes" when the docs actually mean "supports A; B; C and D as separate orthogonal modes". A category-level "Selected" decision then carries through every downstream artifact, masking that the project's required A+B combination does not exist as a single mode.
|
||||
|
||||
**Search broadening strategies** (use when results are thin):
|
||||
- Try adjacent fields: if researching "drone indoor navigation", also search "robot indoor navigation", "warehouse AGV navigation"
|
||||
- Try different communities: academic papers, industry whitepapers, military/defense publications, hobbyist forums
|
||||
- Try different geographies: search in English + search for European/Asian approaches if relevant
|
||||
- Try historical evolution: "history of X", "evolution of X approaches", "X state of the art 2024 2025"
|
||||
- Try failure analysis: "X project failure", "X post-mortem", "X recall", "X incident report"
|
||||
- Try disqualifier probes: "X unsupported", "X limitations", "X requirements", "X with [project constraint]", "X without [required input]", "X real-time [target]", "X production failure"
|
||||
|
||||
**Search saturation rule**: Continue searching until new queries stop producing substantially new information. If the last 3 searches only repeat previously found facts, the sub-question is saturated.
|
||||
|
||||
**Save action**:
|
||||
For each source consulted, **immediately** append to `01_source_registry.md` using the entry template from `references/source-tiering.md`.
|
||||
For each source consulted, **immediately** append to `01_source_registry.md` (or the appropriate category file under `01_source_registry/` if split) using the entry template from `references/source-tiering.md`.
|
||||
|
||||
---
|
||||
|
||||
@@ -185,7 +273,7 @@ Transform sources into **verifiable fact cards**:
|
||||
- ❓ Low: Inference or from unofficial sources
|
||||
|
||||
**Save action**:
|
||||
For each extracted fact, **immediately** append to `02_fact_cards.md`:
|
||||
For each extracted fact, **immediately** append to `02_fact_cards.md` (or the appropriate category file under `02_fact_cards/` if split):
|
||||
```markdown
|
||||
## Fact #[number]
|
||||
- **Statement**: [specific fact description]
|
||||
@@ -194,6 +282,7 @@ For each extracted fact, **immediately** append to `02_fact_cards.md`:
|
||||
- **Target Audience**: [which group this fact applies to, inherited from source or further refined]
|
||||
- **Confidence**: ✅/⚠️/❓
|
||||
- **Related Dimension**: [corresponding comparison dimension]
|
||||
- **Fit Impact**: [supports selection / disqualifies / makes experimental / needs user decision]
|
||||
```
|
||||
|
||||
**Target audience in fact statements**:
|
||||
@@ -229,7 +318,7 @@ After initial fact extraction, review what you have found and identify **knowled
|
||||
- Failure cases and edge conditions
|
||||
- Recent developments that may change the picture
|
||||
|
||||
4. **Update artifacts**: Append new sources to `01_source_registry.md`, new facts to `02_fact_cards.md`
|
||||
4. **Update artifacts**: Append new sources to `01_source_registry.md`, new facts to `02_fact_cards.md` (use the appropriate category files under `01_source_registry/` and `02_fact_cards/` if split)
|
||||
|
||||
**Exit criteria**: Proceed to Step 4 when:
|
||||
- Every sub-question has at least 3 facts with at least one from L1/L2
|
||||
|
||||
@@ -24,6 +24,18 @@ Write to `03_comparison_framework.md`:
|
||||
| ... | | | |
|
||||
```
|
||||
|
||||
**Required exact-fit dimensions for component/tool decisions**:
|
||||
When the output selects or recommends a component, tool, library, service, architecture pattern, or algorithm, the framework MUST include these dimensions unless explicitly not applicable:
|
||||
- Option family (`Simple baseline`, `Established production`, `Open-source`, `Commercial/vendor`, `Current SOTA`, `Adjacent-domain`, `No-build/defer`, `Known bad`)
|
||||
- Required inputs/outputs and ownership boundaries
|
||||
- Operating context and lifecycle fit
|
||||
- Non-functional envelope fit
|
||||
- Implementation assumptions and hard disqualifiers
|
||||
- Evidence quality and source tier
|
||||
- Selection status (`Selected`, `Rejected`, `Experimental only`, `Needs user decision`)
|
||||
|
||||
For each component area, include multiple candidates in the initial population. Do not present only the preferred option unless the investigation found no realistic alternatives; if so, state the searches that proved the narrow landscape.
|
||||
|
||||
---
|
||||
|
||||
### Step 5: Reference Point Baseline Alignment
|
||||
@@ -97,6 +109,8 @@ Validate conclusions against a typical scenario:
|
||||
- [ ] Are there any important dimensions missed?
|
||||
- [ ] Is there any over-extrapolation?
|
||||
- [ ] Are conclusions actionable/verifiable?
|
||||
- [ ] Does every selected component/tool/pattern match the Project Constraint Matrix?
|
||||
- [ ] Are mismatches marked as disqualifiers instead of hidden as generic "limitations"?
|
||||
|
||||
**Save action**:
|
||||
Write to `05_validation_log.md`:
|
||||
@@ -128,6 +142,66 @@ If using Y: [expected behavior]
|
||||
|
||||
---
|
||||
|
||||
### Step 7.5: Component Applicability Gate (BLOCKING)
|
||||
|
||||
**Applicability**: this gate applies only when the run is classified as **Technical-component selection** in the SKILL's Research Output Class section. For non-technical research (concept comparison, market/policy investigation, root-cause analysis without tooling, knowledge organization), skip this entire step and proceed to Step 8 — there are no components to gate. State the skip once in `05_validation_log.md`: `Step 7.5 (Component Applicability Gate): not applicable — Non-technical investigation`. For mixed runs (some component areas technical, some not), apply this gate only to the technical component areas; the non-technical ones do not produce 7.5 rows.
|
||||
|
||||
Before finalizing the solution draft, build an exact-fit matrix for every component/tool/library/service/pattern/algorithm that is selected, recommended, rejected, or treated as a fallback. Free-form prose in a "Project Constraints Checked" column is **not sufficient** — mismatches hide inside rationale text. The matrix must be structured per restriction and per acceptance criterion.
|
||||
|
||||
#### 7.5.1 Top-level Component Fit Matrix
|
||||
|
||||
```markdown
|
||||
# Component Fit Matrix
|
||||
|
||||
| Component Area | Candidate | Pinned Mode/Config | Option Family | Intended Role | API Capability Evidence | Mismatches / Disqualifiers | Status | Decision Rationale |
|
||||
|----------------|-----------|--------------------|---------------|---------------|-------------------------|----------------------------|--------|--------------------|
|
||||
| [area] | [name] | [exact mode/config the project will use, copied verbatim from the MVE block in Step 2] | [family] | [role] | MVE: [link to MVE block in `02_fact_cards.md` / `02_fact_cards/` or `02_mve_evidence.md`]; docs: [Source #] | [none / list] | Selected / Rejected / Experimental only / Needs user decision | [why] |
|
||||
```
|
||||
|
||||
The new **Pinned Mode/Config** column is mandatory. A row without a pinned mode is incomplete. The new **API Capability Evidence** column links to the Minimum Viable Example saved during Step 2's API Capability Verification — without an MVE link the candidate cannot be `Selected`.
|
||||
|
||||
#### 7.5.2 Restrictions × Candidate-Modes Sub-Matrix (MANDATORY)
|
||||
|
||||
For each lead candidate row in the top-level matrix, append a structured cross-check that walks every numbered line of `restrictions.md` and `acceptance_criteria.md` against the candidate's **pinned mode/config**.
|
||||
|
||||
```markdown
|
||||
## Sub-Matrix — <Candidate Name> in <Pinned Mode>
|
||||
|
||||
| Restriction / AC | Candidate-mode behavior | Result | Evidence |
|
||||
|------------------|-------------------------|--------|----------|
|
||||
| R1: <verbatim line from restrictions.md> | <how the pinned mode behaves under this restriction> | ✅ Pass / ❌ Fail / ❓ Verify / N/A | [Fact # / Source # / MVE link] |
|
||||
| R2: ... | ... | ... | ... |
|
||||
| ... | ... | ... | ... |
|
||||
| AC-1.1: <verbatim line from acceptance_criteria.md> | <how the pinned mode satisfies (or contradicts) this AC's measurable target> | ✅ / ❌ / ❓ / N/A | [Fact # / Source # / MVE link] |
|
||||
| AC-1.2: ... | ... | ... | ... |
|
||||
| ... | ... | ... | ... |
|
||||
```
|
||||
|
||||
Cell semantics:
|
||||
- ✅ **Pass** — the candidate's pinned mode satisfies this line, with cited official-doc or MVE evidence.
|
||||
- ❌ **Fail** — the candidate's pinned mode contradicts this line, with cited evidence. Even one ❌ disqualifies the candidate from `Selected` status.
|
||||
- ❓ **Verify** — no evidence yet either way; further investigation required (loops back to Step 2 / Step 3.5). A row left ❓ at the end of analysis blocks the candidate.
|
||||
- **N/A** — the line is irrelevant to this component area (state why in one phrase).
|
||||
|
||||
A candidate row may not be marked `Selected` while any cell is ❌ or ❓.
|
||||
|
||||
#### 7.5.3 Decision Rules
|
||||
|
||||
- `Selected` is allowed only when (a) the top-level row has an MVE link, (b) the sub-matrix has zero ❌, (c) the sub-matrix has zero ❓, and (d) the candidate's documented implementation assumptions match the project's explicit constraints and acceptance criteria.
|
||||
- `Experimental only` is required when a candidate might work but lacks proof for the exact operating context (e.g., MVE exists for a similar configuration but not the exact one).
|
||||
- `Rejected` is required when documented assumptions conflict with project constraints (any sub-matrix row is ❌ with cited evidence).
|
||||
- `Needs user decision` is required when a mismatch changes scope, cost, safety, product behavior, or acceptance criteria — and the user has not yet been consulted.
|
||||
- Each component area must include at least one selected or fallback-safe option, plus the most credible rejected/experimental alternatives discovered during web research.
|
||||
- A component area with only one candidate is incomplete unless `00_question_decomposition.md` documents the broader searches and why they yielded no realistic alternatives.
|
||||
- A candidate may not appear as the lead solution in Step 8 unless this gate marks it `Selected`.
|
||||
- "Validation gate required" footnotes are not equivalent to `Selected`. If the validation gate concerns API capability (does the mode produce the required output?), that is a Step-2 / Step-7.5 question and must be resolved here, not deferred to runtime. Only validation gates concerning *runtime quality* (e.g., "does this VO converge on this terrain class?") may be carried forward as `Selected with runtime gate`.
|
||||
|
||||
**Save action**: Write `06_component_fit_matrix.md` (or, when split, the equivalent files under `06_component_fit_matrix/` — typically `00_summary.md` for the top-level matrix plus per-component sub-matrix files) containing both 7.5.1 (top-level) and 7.5.2 (per-candidate sub-matrices).
|
||||
|
||||
**BLOCKING**: If any lead candidate has ❌, ❓, `Experimental only`, `Rejected`, or `Needs user decision` status, do not silently proceed. Ask the user or choose a different selected candidate.
|
||||
|
||||
---
|
||||
|
||||
### Step 8: Deliverable Formatting
|
||||
|
||||
Make the output **readable, traceable, and actionable**.
|
||||
@@ -139,8 +213,8 @@ Integrate all intermediate artifacts. Write to `OUTPUT_DIR/solution_draft##.md`
|
||||
|
||||
Sources to integrate:
|
||||
- Extract background from `00_question_decomposition.md`
|
||||
- Reference key facts from `02_fact_cards.md`
|
||||
- Reference key facts from `02_fact_cards.md` (or files under `02_fact_cards/` if split)
|
||||
- Organize conclusions from `04_reasoning_chain.md`
|
||||
- Generate references from `01_source_registry.md`
|
||||
- Generate references from `01_source_registry.md` (or files under `01_source_registry/` if split)
|
||||
- Supplement with use cases from `05_validation_log.md`
|
||||
- For Mode A: include AC assessment from `00_ac_assessment.md`
|
||||
|
||||
@@ -10,12 +10,21 @@
|
||||
|
||||
[Architecture solution that meets restrictions and acceptance criteria.]
|
||||
|
||||
> **Applicability** — the table columns `Pinned Mode/Config` and `API Capability Evidence` apply only to technical-component runs (per SKILL.md → Research Output Class). For non-technical research outputs (concept comparison, market/policy report, investigation answer), this Architecture section may be replaced with a comparison/analysis section that does not use these columns; or the columns may be marked `N/A` per row when the row describes a non-technical "component" (a process, a policy, an organizational construct). For mixed runs, fill the columns only on rows that describe libraries/SDKs/frameworks/services/protocols/data formats/algorithms.
|
||||
|
||||
### Component: [Component Name]
|
||||
|
||||
| Solution | Tools | Advantages | Limitations | Requirements | Security | Cost | Fit |
|
||||
|----------|-------|-----------|-------------|-------------|----------|------|-----|
|
||||
| [Option 1] | [lib/platform] | [pros] | [cons] | [reqs] | [security] | [cost] | [fit assessment] |
|
||||
| [Option 2] | [lib/platform] | [pros] | [cons] | [reqs] | [security] | [cost] | [fit assessment] |
|
||||
| Solution | Tools | Pinned Mode/Config | Advantages | Limitations | Requirements | Security | Cost | API Capability Evidence | Fit |
|
||||
|----------|-------|--------------------|-----------|-------------|-------------|----------|------|-------------------------|-----|
|
||||
| [Option 1] | [lib/platform] | [exact mode/config used: inputs, outputs, runtime] | [pros] | [cons] | [intrinsic requirements] | [security] | [cost] | MVE: [link to MVE block]; docs: [Source #] | [Selected / Rejected / Experimental only / Needs user decision — cite exact-fit evidence and disqualifiers] |
|
||||
| [Option 2] | [lib/platform] | [exact mode/config used] | [pros] | [cons] | [intrinsic requirements] | [security] | [cost] | MVE: [link]; docs: [Source #] | [Selected / Rejected / Experimental only / Needs user decision] |
|
||||
|
||||
**Exact-fit evidence**:
|
||||
- Project constraints checked: [inputs/outputs, operating context, lifecycle, NFRs, acceptance criteria]
|
||||
- Evidence: [Fact # / Source #]
|
||||
- Disqualifiers: [none or list]
|
||||
- Restrictions × Candidate-Modes sub-matrix: see `06_component_fit_matrix.md` (or `06_component_fit_matrix/` if split) § <Candidate Name>
|
||||
- API capability gates: ✅ MVE saved / ⚠️ partial — see disqualifiers / ❌ no MVE — candidate is Experimental only or Rejected
|
||||
|
||||
[Repeat per component]
|
||||
|
||||
|
||||
@@ -13,12 +13,21 @@
|
||||
|
||||
[Architecture solution that meets restrictions and acceptance criteria.]
|
||||
|
||||
> **Applicability** — the table columns `Pinned Mode/Config` and `API Capability Evidence` apply only to technical-component runs (per SKILL.md → Research Output Class). For non-technical assessment outputs (e.g., reassessing a policy approach, comparing organizational designs), this Architecture section may be replaced with the assessment content that does not use these columns; or the columns may be marked `N/A` per row for non-technical "components". For mixed runs, fill the columns only on rows that describe libraries/SDKs/frameworks/services/protocols/data formats/algorithms.
|
||||
|
||||
### Component: [Component Name]
|
||||
|
||||
| Solution | Tools | Advantages | Limitations | Requirements | Security | Performance | Fit |
|
||||
|----------|-------|-----------|-------------|-------------|----------|------------|-----|
|
||||
| [Option 1] | [lib/platform] | [pros] | [cons] | [reqs] | [security] | [perf] | [fit assessment] |
|
||||
| [Option 2] | [lib/platform] | [pros] | [cons] | [reqs] | [security] | [perf] | [fit assessment] |
|
||||
| Solution | Tools | Pinned Mode/Config | Advantages | Limitations | Requirements | Security | Performance | API Capability Evidence | Fit |
|
||||
|----------|-------|--------------------|-----------|-------------|-------------|----------|------------|-------------------------|-----|
|
||||
| [Option 1] | [lib/platform] | [exact mode/config used: inputs, outputs, runtime] | [pros] | [cons] | [intrinsic requirements] | [security] | [perf] | MVE: [link to MVE block]; docs: [Source #] | [Selected / Rejected / Experimental only / Needs user decision — cite exact-fit evidence and disqualifiers] |
|
||||
| [Option 2] | [lib/platform] | [exact mode/config used] | [pros] | [cons] | [intrinsic requirements] | [security] | [perf] | MVE: [link]; docs: [Source #] | [Selected / Rejected / Experimental only / Needs user decision] |
|
||||
|
||||
**Exact-fit evidence**:
|
||||
- Project constraints checked: [inputs/outputs, operating context, lifecycle, NFRs, acceptance criteria]
|
||||
- Evidence: [Fact # / Source #]
|
||||
- Disqualifiers: [none or list]
|
||||
- Restrictions × Candidate-Modes sub-matrix: see `06_component_fit_matrix.md` (or `06_component_fit_matrix/` if split) § <Candidate Name>
|
||||
- API capability gates: ✅ MVE saved / ⚠️ partial — see disqualifiers / ❌ no MVE — candidate is Experimental only or Rejected
|
||||
|
||||
[Repeat per component]
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ test-run has two modes. The caller passes the mode explicitly; if missing, defau
|
||||
| Mode | Scope | Typical caller | Input artifacts |
|
||||
|------|-------|---------------|-----------------|
|
||||
| `functional` (default) | Unit / integration / blackbox tests — correctness | autodev Steps that verify after Implement Tests or Implement | `scripts/run-tests.sh`, `_docs/02_document/tests/environment.md`, `_docs/02_document/tests/blackbox-tests.md` |
|
||||
| `perf` | Performance / load / stress / soak tests — latency, throughput, error-rate thresholds | autodev greenfield Step 9, existing-code Step 15 (pre-deploy) | `scripts/run-performance-tests.sh`, `_docs/02_document/tests/performance-tests.md`, AC thresholds in `_docs/00_problem/acceptance_criteria.md` |
|
||||
| `perf` | Performance / load / stress / soak tests — latency, throughput, error-rate thresholds | autodev greenfield Step 15, existing-code Step 15 (pre-deploy) | `scripts/run-performance-tests.sh`, `_docs/02_document/tests/performance-tests.md`, AC thresholds in `_docs/00_problem/acceptance_criteria.md` |
|
||||
|
||||
Direct user invocation (`/test-run`) defaults to `functional`. If the user says "perf tests", "load test", "performance", or passes a performance scenarios file, run `perf` mode.
|
||||
|
||||
@@ -32,6 +32,17 @@ After selecting a mode, read its corresponding workflow below; do not mix them.
|
||||
|
||||
## Functional Mode
|
||||
|
||||
### 0. System-Under-Test Reality Gate
|
||||
|
||||
Before accepting any functional, blackbox, or e2e result as a pass, verify what the tests actually exercised.
|
||||
|
||||
1. If `_docs/00_problem/input_data/expected_results/results_report.md` exists, at least one e2e/blackbox run must compare actual product outputs against that mapping or the machine-readable files it references.
|
||||
2. Stubs are allowed only for external systems outside the product boundary: flight controller/SITL, QGC observer, satellite-provider/Suite service, physical Jetson hardware, physical camera, unavailable licensed datasets, and network services.
|
||||
3. Stubs, fakes, deterministic fallbacks, monkeypatches, or direct replacement of internal product modules are not allowed for the behavior under test. Internal examples include VIO, safety/anchor wrapper, satellite retrieval, anchor verification, tile manager, MAVLink output adapter, FDR, and the A-Z localization pipeline.
|
||||
4. If tests pass only because an internal module is fake/scaffolded, classify the run as **failed** with category `missing product implementation`.
|
||||
5. If a scenario is blocked because external hardware/data is absent, verify the production code path exists before accepting the block as legitimate. Missing internal production code is not an environment block.
|
||||
6. If the test runner writes CSV/Markdown reports, inspect them. A zero exit code is not enough; blocked/internal-stubbed scenarios still require classification.
|
||||
|
||||
### 1. Detect Test Runner
|
||||
|
||||
Check in order — first match wins:
|
||||
@@ -94,7 +105,7 @@ Categorize skips as: **explicit skip (dead code)**, **runtime skip (unreachable)
|
||||
|
||||
### 5. Handle Outcome
|
||||
|
||||
**All tests pass, zero skipped** → return success to the autodev for auto-chain.
|
||||
**All tests pass, zero skipped, and the System-Under-Test Reality Gate passes** → return success to the autodev for auto-chain.
|
||||
|
||||
**Any test fails or errors** → this is a **blocking gate**. Never silently ignore failures. **Always investigate the root cause before deciding on an action.** Read the failing test code, read the error output, check service logs if applicable, and determine whether the bug is in the test or in the production code.
|
||||
|
||||
|
||||
@@ -95,7 +95,7 @@ Examples:
|
||||
|
||||
File: `expected_results/image_01_detections.json`
|
||||
|
||||
```json
|
||||
```json
|
||||
{
|
||||
"input": "image_01.jpg",
|
||||
"expected": {
|
||||
@@ -119,7 +119,7 @@ File: `expected_results/image_01_detections.json`
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
```
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# =============================================================================
|
||||
# Azaion Admin API — environment variable template
|
||||
# Copy to `.env` (git-ignored) and fill in real values for your environment.
|
||||
# Production secrets MUST come from the secret manager, not from a checked-in
|
||||
# file. See _docs/04_deploy/reports/deploy_status_report.md for the full table.
|
||||
# =============================================================================
|
||||
|
||||
# ---------- ASP.NET Core runtime --------------------------------------------
|
||||
ASPNETCORE_ENVIRONMENT=Development # Development | Staging | Production
|
||||
ASPNETCORE_URLS=http://+:8080 # Kestrel bind address inside the container
|
||||
|
||||
# ---------- Database (PostgreSQL on port 4312 in prod, 5432 in test) --------
|
||||
# Two roles: reader (read-only) and admin (read/write). See env/db/01_permissions.sql.
|
||||
ASPNETCORE_ConnectionStrings__AzaionDb=Host=localhost;Port=4312;Database=azaion;Username=azaion_reader;Password=CHANGE_ME
|
||||
ASPNETCORE_ConnectionStrings__AzaionDbAdmin=Host=localhost;Port=4312;Database=azaion;Username=azaion_admin;Password=CHANGE_ME
|
||||
|
||||
# ---------- JWT (ES256, 15 min access, 8/12 h refresh — AZ-531/AZ-532) ------
|
||||
# AZ-532 — admin signs access tokens with ES256. Keys live as PEM files in the
|
||||
# folder named by KeysFolder (the kid is the filename without `.pem`); generate
|
||||
# with scripts/generate-jwt-key.sh. The cycle-1 symmetric secret was removed in
|
||||
# cycle 2; verifiers now fetch the public key from /.well-known/jwks.json.
|
||||
ASPNETCORE_JwtConfig__Issuer=AzaionApi
|
||||
ASPNETCORE_JwtConfig__Audience=Annotators/OrangePi/Admins
|
||||
ASPNETCORE_JwtConfig__KeysFolder=/etc/azaion/jwt-keys
|
||||
# AZ-552/AZ-553 — ActiveKid is REQUIRED in production deployments. The
|
||||
# preflight in scripts/start-services.sh fails fast if it is unset.
|
||||
ASPNETCORE_JwtConfig__ActiveKid=kid-20260514-000000
|
||||
ASPNETCORE_JwtConfig__AccessTokenLifetimeMinutes=15
|
||||
|
||||
# AZ-553 — host-side directory holding the ES256 PEMs. Bind-mounted RO into
|
||||
# the container at $JwtConfig__KeysFolder. Must be owned by (or readable by)
|
||||
# the container's `app` UID. See secrets/README.md "Host-side directories".
|
||||
DEPLOY_HOST_JWT_KEYS_DIR=/var/lib/azaion/jwt-keys
|
||||
|
||||
# AZ-531 — refresh-token windows. Sliding extends on every rotation; absolute
|
||||
# caps the family lifetime regardless of activity.
|
||||
ASPNETCORE_SessionConfig__RefreshSlidingHours=8
|
||||
ASPNETCORE_SessionConfig__RefreshAbsoluteHours=12
|
||||
|
||||
# ---------- DataProtection (AZ-554) -----------------------------------------
|
||||
# AZ-554 — DataProtection master keys MUST persist across container restarts;
|
||||
# otherwise the cycle-2 MFA secret ciphertexts become unreadable and every
|
||||
# MFA-enrolled user is locked out at the next deploy. Production deployments
|
||||
# MUST set this; non-prod uses the ephemeral default if unset.
|
||||
ASPNETCORE_DataProtection__KeysFolder=/var/lib/azaion/dp-keys
|
||||
|
||||
# AZ-554 — host-side directory holding the DataProtection key ring. Bind-mounted
|
||||
# RW into the container at $DataProtection__KeysFolder. Must be writable by the
|
||||
# container's `app` UID. NEVER world-readable (chmod 0700).
|
||||
DEPLOY_HOST_DP_KEYS_DIR=/var/lib/azaion/dp-keys
|
||||
|
||||
# ---------- Resource storage (filesystem) -----------------------------------
|
||||
ASPNETCORE_ResourcesConfig__ResourcesFolder=Content
|
||||
|
||||
# ---------- Container build / image label ------------------------------------
|
||||
# Injected at build time as --build-arg CI_COMMIT_SHA=… by Woodpecker.
|
||||
# Local builds may leave it unset (Dockerfile defaults to "unknown").
|
||||
# CI_COMMIT_SHA=
|
||||
|
||||
# ---------- Deploy targets (consumed by scripts/, not by the API process) ---
|
||||
DEPLOY_HOST=admin.azaion.com # SSH target for scripts/deploy.sh
|
||||
DEPLOY_SSH_USER=root # SSH user on DEPLOY_HOST
|
||||
DEPLOY_CONTAINER_NAME=azaion.api # Docker container name on the host
|
||||
DEPLOY_HOST_PORT=4000 # Port published on DEPLOY_HOST (mapped to 8080 in container)
|
||||
DEPLOY_HOST_CONTENT_DIR=/root/api/content # Bind-mount for resource files
|
||||
DEPLOY_HOST_LOGS_DIR=/root/api/logs # Bind-mount for Serilog rolling files
|
||||
|
||||
# ---------- Container registry ----------------------------------------------
|
||||
REGISTRY_HOST=docker.azaion.com # Private registry; CI may use localhost:5000
|
||||
REGISTRY_IMAGE=azaion/admin # Image path inside REGISTRY_HOST
|
||||
REGISTRY_TAG=dev-arm # main→arm, stage→stage-arm, dev→dev-arm
|
||||
REGISTRY_USER= # CI / scripts only — leave empty in dev .env
|
||||
REGISTRY_TOKEN= # CI / scripts only — leave empty in dev .env
|
||||
+5
-1
@@ -10,4 +10,8 @@ Content/
|
||||
.env
|
||||
.DS_Store
|
||||
e2e/test-results/*
|
||||
!e2e/test-results/.gitkeep
|
||||
!e2e/test-results/.gitkeep
|
||||
|
||||
# AZ-532 — never commit production JWT signing keys.
|
||||
secrets/jwt-keys/*
|
||||
!secrets/jwt-keys/.gitkeep
|
||||
@@ -0,0 +1,54 @@
|
||||
when:
|
||||
event: [push, pull_request, manual]
|
||||
branch: [dev, stage, main]
|
||||
|
||||
matrix:
|
||||
include:
|
||||
- PLATFORM: arm64
|
||||
TAG_SUFFIX: arm
|
||||
# - PLATFORM: amd64
|
||||
# TAG_SUFFIX: amd
|
||||
|
||||
labels:
|
||||
platform: ${PLATFORM}
|
||||
|
||||
steps:
|
||||
- name: lint-format
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0
|
||||
commands:
|
||||
- dotnet format Azaion.AdminApi.sln --verify-no-changes --verbosity diagnostic
|
||||
|
||||
- name: unit-tests
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0
|
||||
commands:
|
||||
- dotnet restore Azaion.AdminApi.sln
|
||||
- dotnet test Azaion.AdminApi.sln --no-restore --configuration Release --logger "console;verbosity=normal" --logger "trx;LogFileName=test-results.trx" --results-directory /app/test-results
|
||||
|
||||
- name: deps-audit
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0
|
||||
commands:
|
||||
# Security audit recommendation 13: fail the build on any High or Critical
|
||||
# vulnerable dependency. The grep returns non-zero when no match is found,
|
||||
# which we want to treat as success — hence the explicit inversion.
|
||||
- dotnet restore Azaion.AdminApi.sln
|
||||
- dotnet list Azaion.AdminApi.sln package --vulnerable --include-transitive 2>&1 | tee deps-audit.log
|
||||
- if grep -E "^\s+>\s+\S+\s+\S+\s+\S+\s+(High|Critical)\s*$" deps-audit.log; then echo "Vulnerable High/Critical dependency found"; exit 1; fi
|
||||
|
||||
- name: e2e-tests
|
||||
image: docker
|
||||
commands:
|
||||
# Mirrors scripts/run-tests.sh: drop volumes from any prior run so the DB
|
||||
# init scripts re-run on a clean data dir, then run compose to completion.
|
||||
- docker compose -f docker-compose.test.yml down -v --remove-orphans
|
||||
- docker compose -f docker-compose.test.yml up --build --abort-on-container-exit --exit-code-from e2e-consumer
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
|
||||
- name: e2e-cleanup
|
||||
image: docker
|
||||
when:
|
||||
status: [success, failure]
|
||||
commands:
|
||||
- docker compose -f docker-compose.test.yml down -v --remove-orphans
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
@@ -0,0 +1,53 @@
|
||||
when:
|
||||
event: [push, manual]
|
||||
branch: [dev, stage, main]
|
||||
|
||||
depends_on:
|
||||
- 01-test
|
||||
|
||||
# Multi-arch matrix. Adding amd64 = uncommenting the second entry once an
|
||||
# amd64 agent is online.
|
||||
matrix:
|
||||
include:
|
||||
- PLATFORM: arm64
|
||||
TAG_SUFFIX: arm
|
||||
# - PLATFORM: amd64
|
||||
# TAG_SUFFIX: amd
|
||||
|
||||
labels:
|
||||
platform: ${PLATFORM}
|
||||
|
||||
steps:
|
||||
- name: build-push
|
||||
image: docker
|
||||
environment:
|
||||
REGISTRY_HOST:
|
||||
from_secret: registry_host
|
||||
REGISTRY_USER:
|
||||
from_secret: registry_user
|
||||
REGISTRY_TOKEN:
|
||||
from_secret: registry_token
|
||||
commands:
|
||||
- echo "$REGISTRY_TOKEN" | docker login "$REGISTRY_HOST" -u "$REGISTRY_USER" --password-stdin
|
||||
- export BRANCH_TAG=${CI_COMMIT_BRANCH}-${TAG_SUFFIX}
|
||||
# 12-char SHA prefix is human-readable while still globally-unique inside
|
||||
# the repo. Pair with TAG_SUFFIX so multi-arch entries don't collide.
|
||||
- export SHA_TAG=$(echo "$CI_COMMIT_SHA" | cut -c1-12)-${TAG_SUFFIX}
|
||||
- export BUILD_DATE=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
- export IMAGE=$REGISTRY_HOST/azaion/admin
|
||||
- |
|
||||
docker build -f Dockerfile \
|
||||
--build-arg CI_COMMIT_SHA=$CI_COMMIT_SHA \
|
||||
--build-arg BUILD_DATE=$BUILD_DATE \
|
||||
--label org.opencontainers.image.revision=$CI_COMMIT_SHA \
|
||||
--label org.opencontainers.image.created=$BUILD_DATE \
|
||||
--label org.opencontainers.image.source=$CI_REPO_URL \
|
||||
-t $IMAGE:$BRANCH_TAG \
|
||||
-t $IMAGE:$SHA_TAG .
|
||||
# Mutable branch tag for "give me whatever's latest on dev" pulls.
|
||||
- docker push $IMAGE:$BRANCH_TAG
|
||||
# Immutable SHA tag — the deploy scripts pin to this and rollback uses it.
|
||||
- docker push $IMAGE:$SHA_TAG
|
||||
- echo "Pushed $IMAGE:$BRANCH_TAG and $IMAGE:$SHA_TAG"
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
@@ -1,31 +0,0 @@
|
||||
when:
|
||||
event: [push, manual]
|
||||
branch: [dev, stage, main]
|
||||
|
||||
labels:
|
||||
platform: arm64
|
||||
|
||||
steps:
|
||||
- name: build-push
|
||||
image: docker
|
||||
environment:
|
||||
REGISTRY_HOST:
|
||||
from_secret: registry_host
|
||||
REGISTRY_USER:
|
||||
from_secret: registry_user
|
||||
REGISTRY_TOKEN:
|
||||
from_secret: registry_token
|
||||
commands:
|
||||
- echo "$REGISTRY_TOKEN" | docker login "$REGISTRY_HOST" -u "$REGISTRY_USER" --password-stdin
|
||||
- export TAG=${CI_COMMIT_BRANCH}-arm
|
||||
- export BUILD_DATE=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
- |
|
||||
docker build -f Dockerfile \
|
||||
--build-arg CI_COMMIT_SHA=$CI_COMMIT_SHA \
|
||||
--label org.opencontainers.image.revision=$CI_COMMIT_SHA \
|
||||
--label org.opencontainers.image.created=$BUILD_DATE \
|
||||
--label org.opencontainers.image.source=$CI_REPO_URL \
|
||||
-t $REGISTRY_HOST/azaion/admin:$TAG .
|
||||
- docker push $REGISTRY_HOST/azaion/admin:$TAG
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
+4
-8
@@ -1,4 +1,4 @@
|
||||
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azaion.AdminApi", "Azaion.AdminApi\Azaion.AdminApi.csproj", "{03A56CF2-A57F-4631-8454-C08B804B8903}"
|
||||
EndProject
|
||||
@@ -6,13 +6,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azaion.Common", "Azaion.Com
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azaion.Services", "Azaion.Services\Azaion.Services.csproj", "{07CFFA74-A1ED-43F9-9CD4-5A09B320EF44}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Azaion.Test", "Azaion.Test\Azaion.Test.csproj", "{2F4F0EA9-0645-4917-8D21-F317E815EB9E}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Docker", "Docker", "{49FBE419-D2FA-4D7C-8419-D3AD5B44DD58}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
Dockerfile = Dockerfile
|
||||
.dockerignore = .dockerignore
|
||||
deploy.cmd = deploy.cmd
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Global
|
||||
@@ -33,9 +30,8 @@ Global
|
||||
{07CFFA74-A1ED-43F9-9CD4-5A09B320EF44}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{07CFFA74-A1ED-43F9-9CD4-5A09B320EF44}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{07CFFA74-A1ED-43F9-9CD4-5A09B320EF44}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{2F4F0EA9-0645-4917-8D21-F317E815EB9E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{2F4F0EA9-0645-4917-8D21-F317E815EB9E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{2F4F0EA9-0645-4917-8D21-F317E815EB9E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{2F4F0EA9-0645-4917-8D21-F317E815EB9E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
|
||||
using System.Globalization;
|
||||
using Microsoft.AspNetCore.Diagnostics;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -13,9 +13,12 @@ public class BusinessExceptionHandler(ILogger<BusinessExceptionHandler> logger)
|
||||
if (exception is BusinessException ex)
|
||||
{
|
||||
logger.LogWarning(exception, ex.Message);
|
||||
httpContext.Response.StatusCode = StatusCodes.Status409Conflict;
|
||||
httpContext.Response.StatusCode = MapStatusCode(ex.ExceptionEnum);
|
||||
httpContext.Response.ContentType = "application/json";
|
||||
|
||||
if (ex.RetryAfterSeconds is { } retry && retry > 0)
|
||||
httpContext.Response.Headers.RetryAfter = retry.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
var err = JsonConvert.SerializeObject(new
|
||||
{
|
||||
ErrorCode = ex.ExceptionEnum,
|
||||
@@ -42,4 +45,24 @@ public class BusinessExceptionHandler(ILogger<BusinessExceptionHandler> logger)
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static int MapStatusCode(ExceptionEnum kind) => kind switch
|
||||
{
|
||||
// AZ-556 — `InvalidCredentials` covers unknown email, wrong password, disabled
|
||||
// account, lockout, and per-account rate-limit. Same 401 for all five so the
|
||||
// wire response carries no signal beyond the optional Retry-After header.
|
||||
ExceptionEnum.InvalidCredentials => StatusCodes.Status401Unauthorized,
|
||||
ExceptionEnum.AccountLocked => StatusCodes.Status423Locked,
|
||||
ExceptionEnum.LoginRateLimited => StatusCodes.Status429TooManyRequests,
|
||||
ExceptionEnum.InvalidRefreshToken => StatusCodes.Status401Unauthorized,
|
||||
ExceptionEnum.SessionNotFound => StatusCodes.Status404NotFound,
|
||||
ExceptionEnum.InvalidMissionRequest => StatusCodes.Status400BadRequest,
|
||||
ExceptionEnum.AircraftNotFound => StatusCodes.Status400BadRequest,
|
||||
ExceptionEnum.MfaAlreadyEnabled => StatusCodes.Status409Conflict,
|
||||
ExceptionEnum.MfaNotEnrolling => StatusCodes.Status409Conflict,
|
||||
ExceptionEnum.MfaNotEnabled => StatusCodes.Status409Conflict,
|
||||
ExceptionEnum.InvalidMfaCode => StatusCodes.Status401Unauthorized,
|
||||
ExceptionEnum.InvalidMfaToken => StatusCodes.Status401Unauthorized,
|
||||
_ => StatusCodes.Status409Conflict
|
||||
};
|
||||
}
|
||||
|
||||
+492
-75
@@ -1,4 +1,6 @@
|
||||
using System.Text;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Threading.RateLimiting;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Azaion.Common;
|
||||
using Azaion.Common.Configs;
|
||||
using Azaion.Common.Database;
|
||||
@@ -6,10 +8,15 @@ using Azaion.Common.Entities;
|
||||
using Azaion.Common.Requests;
|
||||
using Azaion.Services;
|
||||
using FluentValidation;
|
||||
using LinqToDB.Data;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.AspNetCore.Rewrite;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi;
|
||||
using Serilog;
|
||||
@@ -29,9 +36,26 @@ builder.Services.Configure<Microsoft.AspNetCore.Http.Features.FormOptions>(o =>
|
||||
o.MultipartBodyLengthLimit = 209715200);
|
||||
|
||||
var jwtConfig = builder.Configuration.GetSection(nameof(JwtConfig)).Get<JwtConfig>();
|
||||
if (jwtConfig == null || string.IsNullOrEmpty(jwtConfig.Secret))
|
||||
throw new Exception("Missing configuration section: JwtConfig");
|
||||
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.Secret));
|
||||
if (jwtConfig == null || string.IsNullOrEmpty(jwtConfig.Issuer) || string.IsNullOrEmpty(jwtConfig.Audience))
|
||||
throw new Exception("Missing configuration section: JwtConfig (Issuer + Audience required)");
|
||||
|
||||
// AZ-532 — load ES256 signing keys eagerly so JwtBearer can resolve issuer signing
|
||||
// keys via the same provider DI registers below for AuthService.
|
||||
var signingKeyLoggerFactory = LoggerFactory.Create(c => c.AddSerilog(Log.Logger));
|
||||
var jwtSigningKeyProvider = new JwtSigningKeyProvider(
|
||||
Options.Create(jwtConfig),
|
||||
signingKeyLoggerFactory.CreateLogger<JwtSigningKeyProvider>());
|
||||
|
||||
// Fail-fast for DB connection strings — surfaces a missing env var at startup
|
||||
// instead of on the first request to a DB-backed endpoint.
|
||||
var connectionStrings = builder.Configuration.GetSection(nameof(ConnectionStrings)).Get<ConnectionStrings>();
|
||||
if (connectionStrings == null
|
||||
|| string.IsNullOrEmpty(connectionStrings.AzaionDb)
|
||||
|| string.IsNullOrEmpty(connectionStrings.AzaionDbAdmin))
|
||||
throw new Exception("Missing configuration section: ConnectionStrings (AzaionDb and AzaionDbAdmin are required)");
|
||||
|
||||
// Graceful shutdown: 30 s for in-flight requests; pair with `docker stop -t 40`.
|
||||
builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));
|
||||
|
||||
builder.Services.AddSerilog();
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
@@ -39,13 +63,22 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
{
|
||||
o.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = jwtConfig.Issuer,
|
||||
ValidAudience = jwtConfig.Audience,
|
||||
IssuerSigningKey = signingKey
|
||||
ValidIssuer = jwtConfig.Issuer,
|
||||
ValidAudience = jwtConfig.Audience,
|
||||
// AZ-532 AC-5 — pin algorithms so a token forged with alg=HS256 using the
|
||||
// public key as the HMAC secret cannot pass validation.
|
||||
ValidAlgorithms = [SecurityAlgorithms.EcdsaSha256],
|
||||
IssuerSigningKeyResolver = (_, _, kid, _) =>
|
||||
{
|
||||
if (string.IsNullOrEmpty(kid))
|
||||
return jwtSigningKeyProvider.All.Select(k => (SecurityKey)k.SecurityKey);
|
||||
var hit = jwtSigningKeyProvider.All.FirstOrDefault(k => k.Kid == kid);
|
||||
return hit != null ? [hit.SecurityKey] : [];
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
@@ -54,13 +87,16 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
var apiAdminPolicy = new AuthorizationPolicyBuilder()
|
||||
.RequireRole(RoleEnum.ApiAdmin.ToString()).Build();
|
||||
|
||||
var apiUploaderPolicy = new AuthorizationPolicyBuilder()
|
||||
.RequireRole(RoleEnum.ResourceUploader.ToString(), RoleEnum.ApiAdmin.ToString()).Build();
|
||||
// AZ-535 — verifiers (satellite-provider, gps-denied, ui) authenticate as
|
||||
// service-role identities and are the only callers (besides ApiAdmin) allowed
|
||||
// to read the global revocation snapshot.
|
||||
var revocationReaderPolicy = new AuthorizationPolicyBuilder()
|
||||
.RequireRole(RoleEnum.Service.ToString(), RoleEnum.ApiAdmin.ToString()).Build();
|
||||
|
||||
builder.Services.AddAuthorization(o =>
|
||||
{
|
||||
o.AddPolicy(nameof(apiAdminPolicy), apiAdminPolicy);
|
||||
o.AddPolicy(nameof(apiUploaderPolicy), apiUploaderPolicy);
|
||||
o.AddPolicy(nameof(apiAdminPolicy), apiAdminPolicy);
|
||||
o.AddPolicy(nameof(revocationReaderPolicy), revocationReaderPolicy);
|
||||
});
|
||||
|
||||
#endregion Policies
|
||||
@@ -93,10 +129,79 @@ builder.Services.AddSwaggerGen(c =>
|
||||
builder.Services.Configure<ResourcesConfig>(builder.Configuration.GetSection(nameof(ResourcesConfig)));
|
||||
builder.Services.Configure<JwtConfig>(builder.Configuration.GetSection(nameof(JwtConfig)));
|
||||
builder.Services.Configure<ConnectionStrings>(builder.Configuration.GetSection(nameof(ConnectionStrings)));
|
||||
builder.Services.Configure<AuthConfig>(builder.Configuration.GetSection(nameof(AuthConfig)));
|
||||
builder.Services.Configure<SessionConfig>(builder.Configuration.GetSection(nameof(SessionConfig)));
|
||||
|
||||
var authConfig = builder.Configuration.GetSection(nameof(AuthConfig)).Get<AuthConfig>() ?? new AuthConfig();
|
||||
|
||||
// AZ-532 — share the eagerly-built provider so JwtBearer and AuthService both
|
||||
// hold the same set of loaded keys.
|
||||
builder.Services.AddSingleton<IJwtSigningKeyProvider>(jwtSigningKeyProvider);
|
||||
builder.Services.AddScoped<IUserService, UserService>();
|
||||
builder.Services.AddScoped<IAuthService, AuthService>();
|
||||
builder.Services.AddScoped<IRefreshTokenService, RefreshTokenService>();
|
||||
builder.Services.AddScoped<ISessionService, SessionService>();
|
||||
builder.Services.AddScoped<IMissionTokenService, MissionTokenService>();
|
||||
builder.Services.AddScoped<IMfaService, MfaService>();
|
||||
|
||||
// AZ-534 / AZ-554 — DataProtection encrypts mfa_secret at rest. Production
|
||||
// MUST persist the key ring to a bind-mounted host folder; otherwise every
|
||||
// container restart rotates the master key and locks every MFA-enrolled user
|
||||
// out at the next deploy. Development falls back to the ephemeral default.
|
||||
{
|
||||
var dpBuilder = builder.Services.AddDataProtection();
|
||||
dpBuilder.SetApplicationName("Azaion.AdminApi");
|
||||
var keyFolder = builder.Configuration["DataProtection:KeysFolder"];
|
||||
var isProduction = builder.Environment.IsProduction();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(keyFolder))
|
||||
{
|
||||
if (isProduction)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"DataProtection.KeysFolder is required in Production. " +
|
||||
"Set ASPNETCORE_DataProtection__KeysFolder to a persistent bind-mounted path " +
|
||||
"(e.g. /var/lib/azaion/dp-keys backed by DEPLOY_HOST_DP_KEYS_DIR). " +
|
||||
"Without this, MFA secret ciphertexts become unreadable after the next container restart.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(keyFolder);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"DataProtection.KeysFolder '{keyFolder}' is not writable: {ex.Message}. " +
|
||||
"Ensure the bind-mounted host directory is owned by the container user.",
|
||||
ex);
|
||||
}
|
||||
|
||||
if (isProduction)
|
||||
{
|
||||
var probe = Path.Combine(keyFolder, ".dp-writable-probe");
|
||||
try
|
||||
{
|
||||
File.WriteAllText(probe, "ok");
|
||||
File.Delete(probe);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"DataProtection.KeysFolder '{keyFolder}' exists but is not writable by the current process: {ex.Message}. " +
|
||||
"Check host-side ownership/permissions of DEPLOY_HOST_DP_KEYS_DIR (must be writable by the container user).",
|
||||
ex);
|
||||
}
|
||||
}
|
||||
|
||||
dpBuilder.PersistKeysToFileSystem(new DirectoryInfo(keyFolder));
|
||||
}
|
||||
}
|
||||
builder.Services.AddScoped<IResourcesService, ResourcesService>();
|
||||
builder.Services.AddScoped<IDetectionClassService, DetectionClassService>();
|
||||
builder.Services.AddScoped<IAuditLog, AuditLog>();
|
||||
builder.Services.AddSingleton<IDbFactory, DbFactory>();
|
||||
|
||||
builder.Services.AddLazyCache();
|
||||
@@ -105,18 +210,61 @@ builder.Services.AddScoped<ICache, MemoryCache>();
|
||||
builder.Services.AddValidatorsFromAssemblyContaining<RegisterUserValidator>();
|
||||
builder.Services.AddExceptionHandler<BusinessExceptionHandler>();
|
||||
|
||||
// Add CORS configuration
|
||||
// AZ-537 — per-IP sliding window rate limit on /login. Per-account rate limit and
|
||||
// account lockout live in UserService.ValidateUser (DB-backed) so they survive
|
||||
// process restarts and feed the audit_events table.
|
||||
const string LoginPerIpPolicy = "login-per-ip";
|
||||
builder.Services.AddRateLimiter(options =>
|
||||
{
|
||||
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
|
||||
options.OnRejected = (ctx, _) =>
|
||||
{
|
||||
if (ctx.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter))
|
||||
ctx.HttpContext.Response.Headers.RetryAfter =
|
||||
((int)Math.Ceiling(retryAfter.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
return ValueTask.CompletedTask;
|
||||
};
|
||||
|
||||
options.AddPolicy(LoginPerIpPolicy, httpContext =>
|
||||
{
|
||||
var ip = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||
return RateLimitPartition.GetSlidingWindowLimiter(ip, _ => new SlidingWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = authConfig.RateLimit.PerIpPermitLimit,
|
||||
Window = TimeSpan.FromSeconds(authConfig.RateLimit.PerIpWindowSeconds),
|
||||
SegmentsPerWindow = 6,
|
||||
QueueLimit = 0,
|
||||
AutoReplenishment = true
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// AZ-538 — only the HTTPS origin is allowed; the legacy http:// origin combined with
|
||||
// AllowCredentials() permitted credentialed cleartext traffic and is now removed.
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("AdminCorsPolicy", policy =>
|
||||
{
|
||||
policy.WithOrigins("https://admin.azaion.com", "http://admin.azaion.com")
|
||||
policy.WithOrigins("https://admin.azaion.com")
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader()
|
||||
.AllowCredentials();
|
||||
});
|
||||
});
|
||||
|
||||
// AZ-538 — HSTS: 1 year, includeSubDomains, preload eligible. Only attached in
|
||||
// non-Development envs; Development skips both HSTS and HTTPS redirection so
|
||||
// `dotnet watch` on http://localhost keeps working.
|
||||
if (!builder.Environment.IsDevelopment())
|
||||
{
|
||||
builder.Services.AddHsts(o =>
|
||||
{
|
||||
o.MaxAge = TimeSpan.FromDays(365);
|
||||
o.IncludeSubDomains = true;
|
||||
o.Preload = true;
|
||||
});
|
||||
}
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
@@ -124,21 +272,309 @@ if (app.Environment.IsDevelopment())
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
else
|
||||
{
|
||||
// AZ-538 — defence in depth: even if the http origin is re-added by accident
|
||||
// the protocol-layer redirect kicks in first.
|
||||
app.UseHsts();
|
||||
app.UseHttpsRedirection();
|
||||
}
|
||||
|
||||
app.UseCors("AdminCorsPolicy");
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.UseRateLimiter();
|
||||
|
||||
app.UseRewriter(new RewriteOptions().AddRedirect("^$", "/swagger"));
|
||||
|
||||
#region Health endpoints
|
||||
// Anonymous; expected to be exposed only on the management interface (not via the
|
||||
// public Nginx vhost). Surface contract documented in
|
||||
// _docs/04_deploy/deployment_procedures.md §2 and observability.md §7.
|
||||
|
||||
app.MapGet("/health/live", (HttpContext http) =>
|
||||
{
|
||||
http.Response.Headers.CacheControl = "no-store";
|
||||
return Results.Ok(new { status = "live" });
|
||||
}).AllowAnonymous().ExcludeFromDescription();
|
||||
|
||||
app.MapGet("/health/ready", async (IDbFactory dbFactory, HttpContext http, CancellationToken ct) =>
|
||||
{
|
||||
http.Response.Headers.CacheControl = "no-store";
|
||||
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
timeoutCts.CancelAfter(TimeSpan.FromSeconds(2));
|
||||
try
|
||||
{
|
||||
await dbFactory.Run(db => db.ExecuteAsync<int>("SELECT 1"));
|
||||
await dbFactory.RunAdmin(db => db.ExecuteAsync<int>("SELECT 1"));
|
||||
return Results.Ok(new { status = "ready" });
|
||||
}
|
||||
catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested && !ct.IsCancellationRequested)
|
||||
{
|
||||
return Results.Json(new { status = "not-ready", reason = "db-timeout" }, statusCode: 503);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Results.Json(new { status = "not-ready", reason = ex.GetType().Name }, statusCode: 503);
|
||||
}
|
||||
}).AllowAnonymous().ExcludeFromDescription();
|
||||
#endregion Health endpoints
|
||||
|
||||
app.MapPost("/login",
|
||||
async (LoginRequest request, IUserService userService, IAuthService authService, CancellationToken cancellationToken) =>
|
||||
async (LoginRequest request,
|
||||
IUserService userService,
|
||||
IAuthService authService,
|
||||
IRefreshTokenService refreshTokens,
|
||||
ISessionService sessionService,
|
||||
IMfaService mfaService,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var user = await userService.ValidateUser(request, ct: cancellationToken);
|
||||
return Results.Ok(new { Token = authService.CreateToken(user)});
|
||||
|
||||
// AZ-534 AC-3 — MFA-enabled users get short-circuited to a step-1 token; the
|
||||
// real access+refresh pair is minted only after /login/mfa.
|
||||
if (user.MfaEnabled)
|
||||
{
|
||||
return Results.Ok(new MfaRequiredResponse
|
||||
{
|
||||
MfaRequired = true,
|
||||
MfaToken = mfaService.IssueMfaStepToken(user.Id),
|
||||
ExpiresIn = 300,
|
||||
});
|
||||
}
|
||||
|
||||
return await IssueDualTokens(user, authService, refreshTokens, sessionService, amr: null, cancellationToken);
|
||||
})
|
||||
.WithSummary("Login");
|
||||
.RequireRateLimiting(LoginPerIpPolicy)
|
||||
.WithSummary("Login (returns access + refresh token, OR mfa_required if MFA is enabled)");
|
||||
|
||||
// AZ-534 AC-3 / AC-4 — second factor at credential login. Anonymous because the
|
||||
// step-1 mfa_token is itself the proof the caller is mid-flow.
|
||||
app.MapPost("/login/mfa",
|
||||
async (MfaLoginRequest request,
|
||||
IMfaService mfaService,
|
||||
IUserService userService,
|
||||
IAuthService authService,
|
||||
IRefreshTokenService refreshTokens,
|
||||
ISessionService sessionService,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var userId = mfaService.ValidateMfaStepToken(request.MfaToken);
|
||||
// AZ-556 — keep the wire response opaque even on the unlikely state where the
|
||||
// step-1 token resolves to a userId that no longer exists. MfaService applies
|
||||
// the same opaque response for missing MfaSecret / disabled user.
|
||||
var user = await userService.GetById(userId, cancellationToken)
|
||||
?? throw new BusinessException(ExceptionEnum.InvalidCredentials);
|
||||
|
||||
var amr = await mfaService.VerifyForLogin(userId, request.Code, cancellationToken);
|
||||
return await IssueDualTokens(user, authService, refreshTokens, sessionService, amr, cancellationToken);
|
||||
})
|
||||
.AllowAnonymous()
|
||||
.RequireRateLimiting(LoginPerIpPolicy)
|
||||
.WithSummary("AZ-534 — second-factor verification; returns access + refresh token");
|
||||
|
||||
static async Task<IResult> IssueDualTokens(
|
||||
User user,
|
||||
IAuthService authService,
|
||||
IRefreshTokenService refreshTokens,
|
||||
ISessionService sessionService,
|
||||
string[]? amr,
|
||||
CancellationToken ct)
|
||||
{
|
||||
// AZ-534 — pin AMR strength to the session so refresh rotation inherits it.
|
||||
var mfaAuthenticated = amr != null && amr.Contains("mfa");
|
||||
var (refreshToken, session) = await refreshTokens.IssueForNewLogin(user.Id, mfaAuthenticated, ct);
|
||||
var access = authService.CreateToken(user, sessionId: session.Id, jti: Guid.NewGuid(), amr: amr);
|
||||
|
||||
// AZ-533 AC-4 — post-flight reconnect: if the just-authenticated user is an
|
||||
// aircraft (CompanionPC), kill any open mission session bound to it.
|
||||
if (user.Role == RoleEnum.CompanionPC)
|
||||
await sessionService.RevokeMissionsForAircraft(user.Id, ct);
|
||||
|
||||
return Results.Ok(new LoginResponse
|
||||
{
|
||||
AccessToken = access.Jwt,
|
||||
AccessExp = access.ExpiresAt,
|
||||
RefreshToken = refreshToken,
|
||||
RefreshExp = session.ExpiresAt,
|
||||
});
|
||||
}
|
||||
|
||||
// AZ-531 — refresh-token rotation. Anonymous: clients pass the opaque refresh
|
||||
// in the request body so an expired access token doesn't block the refresh.
|
||||
app.MapPost("/token/refresh",
|
||||
async (RefreshTokenRequest request,
|
||||
IRefreshTokenService refreshTokens,
|
||||
IUserService userService,
|
||||
IAuthService authService,
|
||||
ISessionService sessionService,
|
||||
CancellationToken cancellationToken) =>
|
||||
{
|
||||
var (newRefresh, session) = await refreshTokens.Rotate(request.RefreshToken, cancellationToken);
|
||||
var user = await userService.GetById(session.UserId, cancellationToken);
|
||||
if (user == null) throw new BusinessException(ExceptionEnum.InvalidRefreshToken);
|
||||
|
||||
// AZ-534 — preserve the original AMR strength across rotations.
|
||||
var amr = session.MfaAuthenticated ? new[] { "pwd", "mfa" } : new[] { "pwd" };
|
||||
var access = authService.CreateToken(user, sessionId: session.Id, jti: Guid.NewGuid(), amr: amr);
|
||||
|
||||
// AZ-533 AC-4 — same auto-revoke trigger as /login.
|
||||
if (user.Role == RoleEnum.CompanionPC)
|
||||
await sessionService.RevokeMissionsForAircraft(user.Id, cancellationToken);
|
||||
|
||||
return Results.Ok(new LoginResponse
|
||||
{
|
||||
AccessToken = access.Jwt,
|
||||
AccessExp = access.ExpiresAt,
|
||||
RefreshToken = newRefresh,
|
||||
RefreshExp = session.ExpiresAt,
|
||||
});
|
||||
})
|
||||
.AllowAnonymous()
|
||||
.WithSummary("Rotate a refresh token; returns a fresh access + refresh pair");
|
||||
|
||||
// AZ-535 — logout: revoke the caller's current session (the sid claim on their
|
||||
// access token). Idempotent.
|
||||
app.MapPost("/logout",
|
||||
async (HttpContext http, ISessionService sessions, CancellationToken ct) =>
|
||||
{
|
||||
var sid = ParseSidClaim(http.User);
|
||||
var caller = ParseUserIdClaim(http.User);
|
||||
var alreadyRevoked = await sessions.RevokeBySid(sid, caller, SessionRevokedReasons.LoggedOut, ct);
|
||||
return Results.Ok(new { alreadyRevoked });
|
||||
})
|
||||
.RequireAuthorization()
|
||||
.WithSummary("AZ-535 — revoke the caller's current session");
|
||||
|
||||
// AZ-535 AC-2 — sign out everywhere: revoke every active session for the caller.
|
||||
app.MapPost("/logout/all",
|
||||
async (HttpContext http, ISessionService sessions, CancellationToken ct) =>
|
||||
{
|
||||
var caller = ParseUserIdClaim(http.User);
|
||||
var revoked = await sessions.RevokeAllForUser(caller, caller, SessionRevokedReasons.LoggedOutAll, ct);
|
||||
return Results.Ok(new { revoked });
|
||||
})
|
||||
.RequireAuthorization()
|
||||
.WithSummary("AZ-535 — revoke every session for the caller's user");
|
||||
|
||||
// AZ-535 AC-3 — admin-only revoke-by-sid.
|
||||
app.MapPost("/sessions/{sid:guid}/revoke",
|
||||
async (Guid sid, HttpContext http, ISessionService sessions, CancellationToken ct) =>
|
||||
{
|
||||
var admin = ParseUserIdClaim(http.User);
|
||||
var alreadyRevoked = await sessions.RevokeBySid(sid, admin, SessionRevokedReasons.AdminRevoked, ct);
|
||||
return Results.Ok(new { alreadyRevoked });
|
||||
})
|
||||
.RequireAuthorization(apiAdminPolicy)
|
||||
.WithSummary("AZ-535 — admin revoke-by-session-id");
|
||||
|
||||
// AZ-535 AC-4 — verifier-poll snapshot of revoked-but-not-yet-expired sessions.
|
||||
app.MapGet("/sessions/revoked",
|
||||
async (DateTime? since, HttpContext http, ISessionService sessions, CancellationToken ct) =>
|
||||
{
|
||||
// Cap "since" to the longest plausible token TTL (12 h, matches mission cap)
|
||||
// so a buggy verifier asking for "everything since 1970" doesn't cost us a
|
||||
// multi-million-row table scan.
|
||||
var floor = DateTime.UtcNow.AddHours(-12);
|
||||
var effective = since.HasValue && since.Value > floor ? since.Value : floor;
|
||||
|
||||
var rows = await sessions.GetRevokedSince(effective, ct);
|
||||
http.Response.Headers.CacheControl = "no-cache";
|
||||
return Results.Ok(rows.Select(r => new
|
||||
{
|
||||
sid = r.Sid,
|
||||
exp = r.Exp,
|
||||
revokedAt = r.RevokedAt,
|
||||
reason = r.Reason
|
||||
}));
|
||||
})
|
||||
.RequireAuthorization(revocationReaderPolicy)
|
||||
.WithSummary("AZ-535 — verifier snapshot of revoked sessions still within their TTL");
|
||||
|
||||
// AZ-534 — TOTP MFA enrollment + management.
|
||||
app.MapPost("/users/me/mfa/enroll",
|
||||
async (MfaEnrollRequest request, HttpContext http, IMfaService mfa, CancellationToken ct) =>
|
||||
{
|
||||
var userId = ParseUserIdClaim(http.User);
|
||||
var resp = await mfa.Enroll(userId, request.Password, ct);
|
||||
return Results.Ok(resp);
|
||||
})
|
||||
.RequireAuthorization()
|
||||
.WithSummary("AZ-534 — start TOTP enrollment (pre-confirm)");
|
||||
|
||||
app.MapPost("/users/me/mfa/confirm",
|
||||
async (MfaConfirmRequest request, HttpContext http, IMfaService mfa, CancellationToken ct) =>
|
||||
{
|
||||
var userId = ParseUserIdClaim(http.User);
|
||||
await mfa.Confirm(userId, request.Code, ct);
|
||||
return Results.Ok(new { mfaEnabled = true });
|
||||
})
|
||||
.RequireAuthorization()
|
||||
.WithSummary("AZ-534 — confirm TOTP enrollment with a valid code");
|
||||
|
||||
app.MapPost("/users/me/mfa/disable",
|
||||
async (MfaDisableRequest request, HttpContext http, IMfaService mfa, CancellationToken ct) =>
|
||||
{
|
||||
var userId = ParseUserIdClaim(http.User);
|
||||
await mfa.Disable(userId, request.Password, request.Code, ct);
|
||||
return Results.Ok(new { mfaEnabled = false });
|
||||
})
|
||||
.RequireAuthorization()
|
||||
.WithSummary("AZ-534 — disable MFA (requires password + valid code)");
|
||||
|
||||
// AZ-533 — mission token issuance for offline UAV ops. Pilot calls with their
|
||||
// interactive access token; admin returns a long-lived no-refresh token bound
|
||||
// to one aircraft + one mission.
|
||||
app.MapPost("/sessions/mission",
|
||||
async (MissionSessionRequest request, HttpContext http, IMissionTokenService missions, CancellationToken ct) =>
|
||||
{
|
||||
var pilot = ParseUserIdClaim(http.User);
|
||||
// TODO (AZ-534): require amr=["pwd","mfa"]; until MFA ships this is a code
|
||||
// comment per the AZ-533 spec, not an enforced gate.
|
||||
var resp = await missions.Issue(pilot, request, ct);
|
||||
return Results.Ok(resp);
|
||||
})
|
||||
.RequireAuthorization()
|
||||
.WithSummary("AZ-533 — issue a long-lived mission token for one UAV flight");
|
||||
|
||||
static Guid ParseSidClaim(System.Security.Claims.ClaimsPrincipal user) =>
|
||||
Guid.TryParse(user.FindFirst(JwtRegisteredClaimNames.Sid)?.Value, out var s)
|
||||
? s
|
||||
: throw new BusinessException(ExceptionEnum.InvalidRefreshToken);
|
||||
|
||||
static Guid ParseUserIdClaim(System.Security.Claims.ClaimsPrincipal user) =>
|
||||
Guid.TryParse(user.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value, out var u)
|
||||
? u
|
||||
: throw new BusinessException(ExceptionEnum.InvalidRefreshToken);
|
||||
|
||||
// AZ-532 — JWKS endpoint. Verifiers cache for 1 h (Cache-Control: public, max-age=3600).
|
||||
app.MapGet("/.well-known/jwks.json",
|
||||
(IJwtSigningKeyProvider keys, HttpContext http) =>
|
||||
{
|
||||
http.Response.Headers.CacheControl = "public, max-age=3600";
|
||||
var jwks = new
|
||||
{
|
||||
keys = keys.All.Select(k =>
|
||||
{
|
||||
var p = k.Ecdsa.ExportParameters(includePrivateParameters: false);
|
||||
return new
|
||||
{
|
||||
kty = "EC",
|
||||
crv = "P-256",
|
||||
kid = k.Kid,
|
||||
use = "sig",
|
||||
alg = "ES256",
|
||||
x = Microsoft.IdentityModel.Tokens.Base64UrlEncoder.Encode(p.Q.X!),
|
||||
y = Microsoft.IdentityModel.Tokens.Base64UrlEncoder.Encode(p.Q.Y!)
|
||||
};
|
||||
}).ToArray()
|
||||
};
|
||||
return Results.Json(jwks);
|
||||
})
|
||||
.AllowAnonymous()
|
||||
.ExcludeFromDescription()
|
||||
.WithSummary("JWKS — public verification keys");
|
||||
|
||||
app.MapPost("/users",
|
||||
async (RegisterUserRequest registerUserRequest, IValidator<RegisterUserRequest> validator,
|
||||
@@ -153,6 +589,12 @@ app.MapPost("/users",
|
||||
.RequireAuthorization(apiAdminPolicy)
|
||||
.WithSummary("Creates a new user");
|
||||
|
||||
app.MapPost("/devices",
|
||||
async (IUserService userService, CancellationToken cancellationToken)
|
||||
=> await userService.RegisterDevice(cancellationToken))
|
||||
.RequireAuthorization(apiAdminPolicy)
|
||||
.WithSummary("Creates a new device (server-assigned serial, email and password)");
|
||||
|
||||
app.MapGet("/users/current",
|
||||
async (IAuthService authService) => await authService.GetCurrentUser())
|
||||
.RequireAuthorization()
|
||||
@@ -164,12 +606,6 @@ app.MapGet("/users",
|
||||
.RequireAuthorization(apiAdminPolicy)
|
||||
.WithSummary("List users by criteria");
|
||||
|
||||
app.MapPut("/users/hardware/set",
|
||||
async ([FromBody]SetHWRequest request, IUserService userService, ICache cache, CancellationToken ct) =>
|
||||
await userService.UpdateHardware(request.Email, request.Hardware, ct: ct))
|
||||
.RequireAuthorization(apiAdminPolicy)
|
||||
.WithSummary("Sets user's hardware");
|
||||
|
||||
app.MapPut("/users/queue-offsets/set",
|
||||
async ([FromBody]SetUserQueueOffsetsRequest request, IUserService userService, CancellationToken ct)
|
||||
=> await userService.UpdateQueueOffsets(request.Email, request.Offsets, ct))
|
||||
@@ -219,59 +655,40 @@ app.MapPost("/resources/clear/{dataFolder?}",
|
||||
.RequireAuthorization(apiAdminPolicy)
|
||||
.WithSummary("Clear folder");
|
||||
|
||||
app.MapPost("/resources/get/{dataFolder?}", //Need to have POST method for secure password
|
||||
async ([FromBody]GetResourceRequest request, [FromRoute]string? dataFolder, IAuthService authService,
|
||||
IUserService userService, IResourcesService resourcesService, CancellationToken ct) =>
|
||||
app.MapPost("/classes",
|
||||
async (CreateDetectionClassRequest request, IValidator<CreateDetectionClassRequest> validator,
|
||||
IDetectionClassService detectionClassService, CancellationToken ct) =>
|
||||
{
|
||||
var user = await authService.GetCurrentUser();
|
||||
if (user == null)
|
||||
throw new UnauthorizedAccessException();
|
||||
var validation = await validator.ValidateAsync(request, ct);
|
||||
if (!validation.IsValid)
|
||||
return Results.ValidationProblem(validation.ToDictionary());
|
||||
var created = await detectionClassService.Create(request, ct);
|
||||
return Results.Ok(created);
|
||||
})
|
||||
.RequireAuthorization(apiAdminPolicy)
|
||||
.WithSummary("Creates a new detection class");
|
||||
|
||||
var hwHash = await userService.CheckHardwareHash(user, request.Hardware);
|
||||
|
||||
var key = Security.GetApiEncryptionKey(user.Email, request.Password, hwHash);
|
||||
var stream = await resourcesService.GetEncryptedResource(dataFolder, request.FileName, key, ct);
|
||||
|
||||
return Results.File(stream, "application/octet-stream", request.FileName);
|
||||
}).RequireAuthorization()
|
||||
.WithSummary("Gets encrypted by users Password and HardwareHash resources. POST method for secure password");
|
||||
|
||||
app.MapGet("/resources/get-installer",
|
||||
async (IAuthService authService, IResourcesService resourcesService, CancellationToken ct) =>
|
||||
{
|
||||
var user = await authService.GetCurrentUser();
|
||||
if (user == null)
|
||||
throw new UnauthorizedAccessException();
|
||||
var (name, stream) = resourcesService.GetInstaller(isStage: false);
|
||||
if (stream == null)
|
||||
throw new FileNotFoundException("Installer file was not found!");
|
||||
return Results.File(stream, "application/octet-stream", name);
|
||||
}).RequireAuthorization()
|
||||
.WithSummary("Gets latest installer");
|
||||
|
||||
app.MapGet("/resources/get-installer/stage",
|
||||
async (IAuthService authService, IResourcesService resourcesService, CancellationToken ct) =>
|
||||
{
|
||||
var user = await authService.GetCurrentUser();
|
||||
if (user == null)
|
||||
throw new UnauthorizedAccessException();
|
||||
var (name, stream) = resourcesService.GetInstaller(isStage: true);
|
||||
if (stream == null)
|
||||
throw new FileNotFoundException("Installer file was not found!");
|
||||
return Results.File(stream, "application/octet-stream", name);
|
||||
}).RequireAuthorization()
|
||||
.WithSummary("Gets latest installer");
|
||||
|
||||
|
||||
app.MapPost("/resources/check",
|
||||
async (CheckResourceRequest request, IAuthService authService, IUserService userService) =>
|
||||
app.MapPatch("/classes/{id:int}",
|
||||
async (int id, UpdateDetectionClassRequest request, IValidator<UpdateDetectionClassRequest> validator,
|
||||
IDetectionClassService detectionClassService, CancellationToken ct) =>
|
||||
{
|
||||
var user = await authService.GetCurrentUser();
|
||||
if (user == null)
|
||||
throw new UnauthorizedAccessException();
|
||||
await userService.CheckHardwareHash(user, request.Hardware);
|
||||
return true;
|
||||
});
|
||||
var validation = await validator.ValidateAsync(request, ct);
|
||||
if (!validation.IsValid)
|
||||
return Results.ValidationProblem(validation.ToDictionary());
|
||||
var updated = await detectionClassService.Update(id, request, ct);
|
||||
return updated == null ? Results.NotFound() : Results.Ok(updated);
|
||||
})
|
||||
.RequireAuthorization(apiAdminPolicy)
|
||||
.WithSummary("Updates an existing detection class (partial-merge accepted)");
|
||||
|
||||
app.MapDelete("/classes/{id:int}",
|
||||
async (int id, IDetectionClassService detectionClassService, CancellationToken ct) =>
|
||||
{
|
||||
var ok = await detectionClassService.Delete(id, ct);
|
||||
return ok ? Results.NoContent() : Results.NotFound();
|
||||
})
|
||||
.RequireAuthorization(apiAdminPolicy)
|
||||
.WithSummary("Deletes a detection class");
|
||||
|
||||
app.UseExceptionHandler(_ => {});
|
||||
|
||||
|
||||
@@ -4,5 +4,10 @@
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AuthConfig": {
|
||||
"RateLimit": {
|
||||
"PerIpPermitLimit": 1000
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,13 +7,31 @@
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"ResourcesConfig": {
|
||||
"ResourcesFolder": "Content",
|
||||
"SuiteInstallerFolder": "suite",
|
||||
"SuiteStageInstallerFolder": "suite-stage"
|
||||
"ResourcesFolder": "Content"
|
||||
},
|
||||
"JwtConfig": {
|
||||
"Issuer": "AzaionApi",
|
||||
"Audience": "Annotators/OrangePi/Admins",
|
||||
"TokenLifetimeHours": 4
|
||||
"KeysFolder": "secrets/jwt-keys",
|
||||
"AccessTokenLifetimeMinutes": 15
|
||||
},
|
||||
"SessionConfig": {
|
||||
"RefreshSlidingHours": 8,
|
||||
"RefreshAbsoluteHours": 12
|
||||
},
|
||||
"AuthConfig": {
|
||||
"RateLimit": {
|
||||
"PerIpPermitLimit": 10,
|
||||
"PerIpWindowSeconds": 60,
|
||||
"PerAccountPermitLimit": 5,
|
||||
"PerAccountWindowSeconds": 300
|
||||
},
|
||||
"Lockout": {
|
||||
"MaxAttempts": 10,
|
||||
"DurationSeconds": 900
|
||||
}
|
||||
},
|
||||
"DataProtection": {
|
||||
"KeysFolder": ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FluentValidation" Version="11.10.0" />
|
||||
<PackageReference Include="linq2db" Version="5.4.1" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
|
||||
<PackageReference Include="Npgsql" Version="10.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -14,17 +14,34 @@ public class BusinessException(ExceptionEnum exEnum) : Exception(GetMessage(exEn
|
||||
|
||||
public ExceptionEnum ExceptionEnum { get; set; } = exEnum;
|
||||
|
||||
/// <summary>
|
||||
/// Optional cooldown hint surfaced as a Retry-After response header by the exception
|
||||
/// handler. Used by AccountLocked and LoginRateLimited (AZ-537).
|
||||
/// </summary>
|
||||
public int? RetryAfterSeconds { get; init; }
|
||||
|
||||
public BusinessException(ExceptionEnum exEnum, int retryAfterSeconds) : this(exEnum)
|
||||
{
|
||||
RetryAfterSeconds = retryAfterSeconds;
|
||||
}
|
||||
|
||||
public static string GetMessage(ExceptionEnum exEnum) => ExceptionDescriptions.GetValueOrDefault(exEnum) ?? exEnum.ToString();
|
||||
}
|
||||
|
||||
public enum ExceptionEnum
|
||||
{
|
||||
// AZ-556 — DEPRECATED: no longer thrown by `UserService.ValidateUser`. The login
|
||||
// path now uses `InvalidCredentials` (70) for all rejection categories to close the
|
||||
// user-enumeration leak (F-AUTH-1 + F-AUTH-3). Kept defined for any cross-workspace
|
||||
// verifier that still pattern-matches on the old codes. Removal is scheduled in a
|
||||
// separate ticket after the deprecation window.
|
||||
[Description("No such email found.")]
|
||||
NoEmailFound = 10,
|
||||
|
||||
[Description("Email already exists.")]
|
||||
EmailExists = 20,
|
||||
|
||||
// AZ-556 — DEPRECATED: see the `NoEmailFound` deprecation note above.
|
||||
[Description("Passwords do not match.")]
|
||||
WrongPassword = 30,
|
||||
|
||||
@@ -36,18 +53,55 @@ public enum ExceptionEnum
|
||||
|
||||
WrongEmail = 37,
|
||||
|
||||
// AZ-556 — DEPRECATED: see the `NoEmailFound` deprecation note above.
|
||||
[Description("User account is disabled.")]
|
||||
UserDisabled = 38,
|
||||
|
||||
[Description("Hardware mismatch! You are not authorized to access this resource from this hardware.")]
|
||||
HardwareIdMismatch = 40,
|
||||
// AZ-556 — DEPRECATED: cycle-2 unifies the lockout response under
|
||||
// `InvalidCredentials` + Retry-After header (AC-7). Kept defined for cross-workspace
|
||||
// verifier compatibility; will be removed alongside `NoEmailFound`/`WrongPassword`.
|
||||
[Description("Account is temporarily locked due to too many failed login attempts.")]
|
||||
AccountLocked = 50,
|
||||
|
||||
[Description("Hardware should be not empty.")]
|
||||
BadHardware = 45,
|
||||
// AZ-556 — DEPRECATED: see the `AccountLocked` deprecation note above.
|
||||
[Description("Too many login attempts. Try again later.")]
|
||||
LoginRateLimited = 51,
|
||||
|
||||
[Description("Wrong resource file name.")]
|
||||
WrongResourceName = 50,
|
||||
[Description("Refresh token is invalid, expired, or has been revoked.")]
|
||||
InvalidRefreshToken = 52,
|
||||
|
||||
[Description("Session not found.")]
|
||||
SessionNotFound = 53,
|
||||
|
||||
[Description("Mission token request is invalid.")]
|
||||
InvalidMissionRequest = 54,
|
||||
|
||||
[Description("Aircraft not found or wrong role.")]
|
||||
AircraftNotFound = 55,
|
||||
|
||||
[Description("MFA is already enabled for this user.")]
|
||||
MfaAlreadyEnabled = 56,
|
||||
|
||||
[Description("MFA enrollment is not in progress for this user.")]
|
||||
MfaNotEnrolling = 57,
|
||||
|
||||
[Description("MFA is not enabled for this user.")]
|
||||
MfaNotEnabled = 58,
|
||||
|
||||
[Description("Invalid MFA code or recovery code.")]
|
||||
InvalidMfaCode = 59,
|
||||
|
||||
[Description("MFA token is invalid or expired.")]
|
||||
InvalidMfaToken = 61,
|
||||
|
||||
[Description("No file provided.")]
|
||||
NoFileProvided = 60,
|
||||
|
||||
// AZ-556 — single opaque login-failure code. Replaces the wire-side use of
|
||||
// `NoEmailFound`, `WrongPassword`, `UserDisabled`, `AccountLocked`, and
|
||||
// `LoginRateLimited`. The audit log preserves the actual category for SecOps.
|
||||
// Lockout / rate-limit responses additionally carry a Retry-After header via
|
||||
// `BusinessException.RetryAfterSeconds`.
|
||||
[Description("Invalid credentials.")]
|
||||
InvalidCredentials = 70,
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace Azaion.Common.Configs;
|
||||
|
||||
public class AuthConfig
|
||||
{
|
||||
public RateLimitOptions RateLimit { get; set; } = new();
|
||||
public LockoutOptions Lockout { get; set; } = new();
|
||||
}
|
||||
|
||||
public class RateLimitOptions
|
||||
{
|
||||
public int PerIpPermitLimit { get; set; } = 10;
|
||||
public int PerIpWindowSeconds { get; set; } = 60;
|
||||
public int PerAccountPermitLimit { get; set; } = 5;
|
||||
public int PerAccountWindowSeconds { get; set; } = 300;
|
||||
}
|
||||
|
||||
public class LockoutOptions
|
||||
{
|
||||
public int MaxAttempts { get; set; } = 10;
|
||||
public int DurationSeconds { get; set; } = 900; // 15 min
|
||||
}
|
||||
@@ -2,8 +2,41 @@ namespace Azaion.Common.Configs;
|
||||
|
||||
public class JwtConfig
|
||||
{
|
||||
public string Issuer { get; set; } = null!;
|
||||
public string Issuer { get; set; } = null!;
|
||||
public string Audience { get; set; } = null!;
|
||||
public string Secret { get; set; } = null!;
|
||||
public double TokenLifetimeHours { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AZ-532 — directory containing ES256 private keys (PEM, *.pem). The kid is
|
||||
/// the filename without extension. Production: <c>secrets/jwt-keys</c>.
|
||||
/// </summary>
|
||||
public string KeysFolder { get; set; } = "secrets/jwt-keys";
|
||||
|
||||
/// <summary>
|
||||
/// AZ-532 — kid of the key currently used to SIGN new tokens. Other keys in
|
||||
/// <see cref="KeysFolder"/> remain in JWKS for the rotation overlap window so
|
||||
/// in-flight tokens still verify.
|
||||
/// </summary>
|
||||
public string? ActiveKid { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// AZ-531 — access-token TTL in minutes (default 15). Refresh-token TTLs live
|
||||
/// on <see cref="SessionConfig"/>.
|
||||
/// </summary>
|
||||
public int AccessTokenLifetimeMinutes { get; set; } = 15;
|
||||
}
|
||||
|
||||
public class SessionConfig
|
||||
{
|
||||
/// <summary>
|
||||
/// AZ-531 — sliding window. Each refresh extends expires_at by this many
|
||||
/// hours from "now"; family-level absolute cap below.
|
||||
/// </summary>
|
||||
public int RefreshSlidingHours { get; set; } = 8;
|
||||
|
||||
/// <summary>
|
||||
/// AZ-531 — absolute cap. A session family older than this many hours since
|
||||
/// the family's first issue is rejected even if every individual rotation
|
||||
/// stayed within the sliding window.
|
||||
/// </summary>
|
||||
public int RefreshAbsoluteHours { get; set; } = 12;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,4 @@ namespace Azaion.Common.Configs;
|
||||
public class ResourcesConfig
|
||||
{
|
||||
public string ResourcesFolder { get; set; } = null!;
|
||||
public string SuiteInstallerFolder { get; set; } = null!;
|
||||
public string SuiteStageInstallerFolder { get; set; } = null!;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,5 +6,8 @@ namespace Azaion.Common.Database;
|
||||
|
||||
public class AzaionDb(DataOptions dataOptions) : DataConnection(dataOptions)
|
||||
{
|
||||
public ITable<User> Users => this.GetTable<User>();
|
||||
public ITable<User> Users => this.GetTable<User>();
|
||||
public ITable<DetectionClass> DetectionClasses => this.GetTable<DetectionClass>();
|
||||
public ITable<AuditEvent> AuditEvents => this.GetTable<AuditEvent>();
|
||||
public ITable<Session> Sessions => this.GetTable<Session>();
|
||||
}
|
||||
@@ -34,8 +34,30 @@ public static class AzaionDbSchemaHolder
|
||||
.HasConversion(
|
||||
v => v == null ? null : JsonConvert.SerializeObject(v),
|
||||
p => string.IsNullOrEmpty(p) ? new UserConfig() : JsonConvert.DeserializeObject<UserConfig>(p))
|
||||
.IsNullable();
|
||||
.IsNullable()
|
||||
// AZ-534 — mfa_recovery_codes is JSONB; tell the provider so Npgsql sends
|
||||
// the JSON type oid instead of text (otherwise inserts fail with
|
||||
// "column is of type jsonb but expression is of type text").
|
||||
.Property(x => x.MfaRecoveryCodes)
|
||||
.HasDataType(DataType.BinaryJson);
|
||||
|
||||
builder.Entity<DetectionClass>()
|
||||
.HasTableName("detection_classes")
|
||||
.Property(x => x.Id)
|
||||
.IsPrimaryKey()
|
||||
.IsIdentity();
|
||||
|
||||
builder.Entity<AuditEvent>()
|
||||
.HasTableName("audit_events")
|
||||
.Property(x => x.Id)
|
||||
.IsPrimaryKey()
|
||||
.IsIdentity();
|
||||
|
||||
builder.Entity<Session>()
|
||||
.HasTableName("sessions")
|
||||
.Property(x => x.Id)
|
||||
.IsPrimaryKey()
|
||||
.HasDataType(DataType.Guid);
|
||||
|
||||
builder.Build();
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ public interface IDbFactory
|
||||
Task<T> Run<T>(Func<AzaionDb, Task<T>> func);
|
||||
Task Run(Func<AzaionDb, Task> func);
|
||||
Task RunAdmin(Func<AzaionDb, Task> func);
|
||||
Task<T> RunAdmin<T>(Func<AzaionDb, Task<T>> func);
|
||||
}
|
||||
|
||||
public class DbFactory : IDbFactory
|
||||
@@ -54,4 +55,10 @@ public class DbFactory : IDbFactory
|
||||
await using var db = new AzaionDb(_dataOptionsAdmin);
|
||||
await func(db);
|
||||
}
|
||||
|
||||
public async Task<T> RunAdmin<T>(Func<AzaionDb, Task<T>> func)
|
||||
{
|
||||
await using var db = new AzaionDb(_dataOptionsAdmin);
|
||||
return await func(db);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
namespace Azaion.Common.Entities;
|
||||
|
||||
public class AuditEvent
|
||||
{
|
||||
public long Id { get; set; }
|
||||
public string EventType { get; set; } = null!;
|
||||
public DateTime OccurredAt { get; set; }
|
||||
public string? Email { get; set; }
|
||||
public string? Ip { get; set; }
|
||||
public string? Metadata { get; set; }
|
||||
}
|
||||
|
||||
public static class AuditEventTypes
|
||||
{
|
||||
public const string LoginFailed = "login_failed";
|
||||
public const string LoginLockout = "login_lockout";
|
||||
public const string LoginSuccess = "login_success";
|
||||
|
||||
// AZ-556 — per-category internal forensics for unified `InvalidCredentials` wire
|
||||
// response. SecOps can distinguish these in the audit_events table even though the
|
||||
// /login response cannot be distinguished by an attacker.
|
||||
public const string LoginFailedUnknownEmail = "login_failed_unknown_email";
|
||||
public const string LoginFailedDisabled = "login_failed_disabled";
|
||||
|
||||
// AZ-534 — MFA lifecycle + login events.
|
||||
public const string MfaEnroll = "mfa_enroll";
|
||||
public const string MfaConfirm = "mfa_confirm";
|
||||
public const string MfaDisable = "mfa_disable";
|
||||
public const string MfaLoginSuccess = "mfa_login_success";
|
||||
public const string MfaLoginFailed = "mfa_login_failed";
|
||||
public const string MfaRecoveryUsed = "mfa_recovery_used";
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Azaion.Common.Entities;
|
||||
|
||||
public class DetectionClass
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; } = null!;
|
||||
public string ShortName { get; set; } = null!;
|
||||
public string Color { get; set; } = null!;
|
||||
public double MaxSizeM { get; set; }
|
||||
public string? PhotoMode { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
}
|
||||
@@ -8,5 +8,10 @@ public enum RoleEnum
|
||||
CompanionPC = 30,
|
||||
Admin = 40, //
|
||||
ResourceUploader = 50, //Uploading dll and ai models
|
||||
// AZ-535 — service-to-service identity (one per verifier: satellite-provider,
|
||||
// gps-denied, ui). Only authorized to read /sessions/revoked snapshot; not
|
||||
// valid for any user-facing endpoint. Each verifier deployment gets one
|
||||
// dedicated Service user.
|
||||
Service = 60,
|
||||
ApiAdmin = 1000 //everything
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
namespace Azaion.Common.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// AZ-531 — refresh-token session row. One row per issued refresh token. A
|
||||
/// "session family" is the chain of rotated sessions that all share the same
|
||||
/// <see cref="FamilyId"/>; reuse-detection keys off it.
|
||||
/// </summary>
|
||||
public class Session
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid UserId { get; set; }
|
||||
/// <summary>
|
||||
/// AZ-531 — sha256(opaque refresh) for interactive sessions. AZ-533 mission
|
||||
/// sessions have no refresh value and store NULL here.
|
||||
/// </summary>
|
||||
public string? RefreshHash { get; set; }
|
||||
public Guid FamilyId { get; set; }
|
||||
public DateTime IssuedAt { get; set; }
|
||||
public DateTime LastUsedAt { get; set; }
|
||||
public DateTime ExpiresAt { get; set; }
|
||||
public DateTime? RevokedAt { get; set; }
|
||||
public string? RevokedReason { get; set; }
|
||||
public Guid? ParentSessionId { get; set; }
|
||||
public DateTime FamilyStartedAt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// AZ-535 — audit trail for who revoked the session (user id of the admin or
|
||||
/// the user themselves on /logout). Null for system revocations (rotation,
|
||||
/// reuse detection, post-flight reconnect).
|
||||
/// </summary>
|
||||
public Guid? RevokedByUserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// AZ-533 — session class. <see cref="SessionClasses.Interactive"/> is the
|
||||
/// default refresh-backed interactive session (AZ-531); <see cref="SessionClasses.Mission"/>
|
||||
/// is a long-lived no-refresh token issued for a single UAV mission.
|
||||
/// </summary>
|
||||
public string Class { get; set; } = SessionClasses.Interactive;
|
||||
|
||||
/// <summary>
|
||||
/// AZ-533 — for mission sessions: the aircraft (CompanionPC user) the mission
|
||||
/// token belongs to. Used by the auto-revoke-on-reconnect middleware. Null for
|
||||
/// interactive sessions.
|
||||
/// </summary>
|
||||
public Guid? AircraftId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// AZ-534 — true iff the session was created via an MFA-validated /login/mfa
|
||||
/// call. Refresh-token rotation reads this to keep the AMR claim stable across
|
||||
/// the session lifetime.
|
||||
/// </summary>
|
||||
public bool MfaAuthenticated { get; set; }
|
||||
}
|
||||
|
||||
public static class SessionRevokedReasons
|
||||
{
|
||||
public const string Rotated = "rotated";
|
||||
public const string ReuseDetected = "reuse_detected";
|
||||
public const string LoggedOut = "logged_out";
|
||||
public const string LoggedOutAll = "logged_out_all";
|
||||
public const string AdminRevoked = "admin_revoked";
|
||||
public const string PostFlightReconnect = "post_flight_reconnect";
|
||||
public const string FamilyRevoked = "family_revoked";
|
||||
}
|
||||
|
||||
public static class SessionClasses
|
||||
{
|
||||
public const string Interactive = "interactive";
|
||||
public const string Mission = "mission";
|
||||
}
|
||||
@@ -16,6 +16,24 @@ public class User
|
||||
public UserConfig? UserConfig { get; set; } = null!;
|
||||
public bool IsEnabled { get; set; }
|
||||
|
||||
// AZ-537 — consecutive failed-login counter and active lockout deadline.
|
||||
public int FailedLoginCount { get; set; }
|
||||
public DateTime? LockoutUntil { get; set; }
|
||||
|
||||
// AZ-534 — TOTP-based 2FA. mfa_secret is encrypted at rest; recovery codes are
|
||||
// stored as a JSONB array of { hash, used_at } objects. mfa_last_used_window
|
||||
// is the RFC 6238 time-step counter of the most recently accepted code,
|
||||
// used to reject in-window replays.
|
||||
[JsonIgnore]
|
||||
public bool MfaEnabled { get; set; }
|
||||
[JsonIgnore]
|
||||
public string? MfaSecret { get; set; }
|
||||
[JsonIgnore]
|
||||
public string? MfaRecoveryCodes { get; set; }
|
||||
public DateTime? MfaEnrolledAt { get; set; }
|
||||
[JsonIgnore]
|
||||
public long? MfaLastUsedWindow { get; set; }
|
||||
|
||||
public static string GetCacheKey(string email) =>
|
||||
string.IsNullOrEmpty(email) ? "" : $"{nameof(User)}.{email}";
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Azaion.Common.Extensions;
|
||||
|
||||
public static class StreamExtensions
|
||||
{
|
||||
public static string ConvertToString(this Stream stream)
|
||||
{
|
||||
stream.Position = 0;
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
var result = reader.ReadToEnd();
|
||||
stream.Position = 0;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Azaion.Common.Requests;
|
||||
|
||||
public class CreateDetectionClassRequest
|
||||
{
|
||||
public string Name { get; set; } = null!;
|
||||
public string ShortName { get; set; } = null!;
|
||||
public string Color { get; set; } = null!;
|
||||
public double MaxSizeM { get; set; }
|
||||
public string? PhotoMode { get; set; }
|
||||
}
|
||||
|
||||
public class CreateDetectionClassValidator : AbstractValidator<CreateDetectionClassRequest>
|
||||
{
|
||||
public CreateDetectionClassValidator()
|
||||
{
|
||||
RuleFor(r => r.Name).NotEmpty().MaximumLength(120);
|
||||
RuleFor(r => r.ShortName).NotEmpty().MaximumLength(20);
|
||||
RuleFor(r => r.Color).NotEmpty().MaximumLength(20);
|
||||
RuleFor(r => r.MaxSizeM).GreaterThan(0);
|
||||
RuleFor(r => r.PhotoMode!).MaximumLength(20).When(r => r.PhotoMode != null);
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Azaion.Common.Requests;
|
||||
|
||||
public class CheckResourceRequest
|
||||
{
|
||||
public string Hardware { get; set; } = null!;
|
||||
}
|
||||
|
||||
public class GetResourceRequest
|
||||
{
|
||||
public string Password { get; set; } = null!;
|
||||
public string Hardware { get; set; } = null!;
|
||||
public string FileName { get; set; } = null!;
|
||||
}
|
||||
|
||||
public class GetResourceRequestValidator : AbstractValidator<GetResourceRequest>
|
||||
{
|
||||
public GetResourceRequestValidator()
|
||||
{
|
||||
RuleFor(r => r.Password)
|
||||
.MinimumLength(8)
|
||||
.WithErrorCode(nameof(ExceptionEnum.PasswordLengthIncorrect))
|
||||
.WithMessage(_ => BusinessException.GetMessage(ExceptionEnum.PasswordLengthIncorrect));
|
||||
|
||||
RuleFor(r => r.Hardware)
|
||||
.NotEmpty()
|
||||
.WithMessage(_ => BusinessException.GetMessage(ExceptionEnum.BadHardware));
|
||||
|
||||
RuleFor(r => r.FileName)
|
||||
.NotEmpty()
|
||||
.WithErrorCode(nameof(ExceptionEnum.WrongResourceName))
|
||||
.WithMessage(_ => BusinessException.GetMessage(ExceptionEnum.WrongResourceName));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace Azaion.Common.Requests;
|
||||
|
||||
/// <summary>
|
||||
/// AZ-531 — dual-token login response. <see cref="Token"/> is kept for
|
||||
/// backwards compatibility with pre-AZ-531 clients (UI ignores extra fields);
|
||||
/// it carries the same value as <see cref="AccessToken"/>.
|
||||
/// </summary>
|
||||
public class LoginResponse
|
||||
{
|
||||
public string AccessToken { get; set; } = null!;
|
||||
public DateTime AccessExp { get; set; }
|
||||
public string RefreshToken { get; set; } = null!;
|
||||
public DateTime RefreshExp { get; set; }
|
||||
|
||||
public string Token => AccessToken;
|
||||
}
|
||||
|
||||
public class RefreshTokenRequest
|
||||
{
|
||||
public string RefreshToken { get; set; } = null!;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
namespace Azaion.Common.Requests;
|
||||
|
||||
/// <summary>AZ-534 — body for <c>POST /users/me/mfa/enroll</c>.</summary>
|
||||
public class MfaEnrollRequest
|
||||
{
|
||||
public string Password { get; set; } = null!;
|
||||
}
|
||||
|
||||
/// <summary>AZ-534 — response of /enroll (also surfaces recovery codes ONCE; they are
|
||||
/// hashed at rest and unrecoverable after this response).</summary>
|
||||
public class MfaEnrollResponse
|
||||
{
|
||||
public string Secret { get; set; } = null!;
|
||||
public string OtpAuthUrl { get; set; } = null!;
|
||||
public string QrPngBase64 { get; set; } = null!;
|
||||
public string[] RecoveryCodes { get; set; } = [];
|
||||
}
|
||||
|
||||
public class MfaConfirmRequest
|
||||
{
|
||||
public string Code { get; set; } = null!;
|
||||
}
|
||||
|
||||
public class MfaDisableRequest
|
||||
{
|
||||
public string Password { get; set; } = null!;
|
||||
public string Code { get; set; } = null!;
|
||||
}
|
||||
|
||||
/// <summary>AZ-534 AC-3 — response of step-1 /login when the user has MFA enabled.
|
||||
/// The mfa_token is a short-lived JWT carried into <c>POST /login/mfa</c>.</summary>
|
||||
public class MfaRequiredResponse
|
||||
{
|
||||
public bool MfaRequired { get; set; } = true;
|
||||
public string MfaToken { get; set; } = null!;
|
||||
public int ExpiresIn { get; set; }
|
||||
}
|
||||
|
||||
public class MfaLoginRequest
|
||||
{
|
||||
public string MfaToken { get; set; } = null!;
|
||||
public string Code { get; set; } = null!;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Azaion.Common.Requests;
|
||||
|
||||
/// <summary>
|
||||
/// AZ-533 — body for <c>POST /sessions/mission</c>. Pilot (interactive session)
|
||||
/// asks admin to mint a long-lived no-refresh token for a single UAV flight.
|
||||
/// </summary>
|
||||
public class MissionSessionRequest
|
||||
{
|
||||
[Required] public string MissionId { get; set; } = null!;
|
||||
[Required] public Guid AircraftId { get; set; }
|
||||
[Required] public double PlannedDurationH { get; set; }
|
||||
public IList<string>? RequestedScope { get; set; }
|
||||
/// <summary>
|
||||
/// Optional bbox of the operating area. Informational until the verifier
|
||||
/// (satellite-provider) enforces it; included verbatim in the token claim.
|
||||
/// </summary>
|
||||
public ValidRegion? ValidRegion { get; set; }
|
||||
}
|
||||
|
||||
public class ValidRegion
|
||||
{
|
||||
public double MinLat { get; set; }
|
||||
public double MinLon { get; set; }
|
||||
public double MaxLat { get; set; }
|
||||
public double MaxLon { get; set; }
|
||||
}
|
||||
|
||||
public class MissionSessionResponse
|
||||
{
|
||||
public string AccessToken { get; set; } = null!;
|
||||
public DateTime AccessExp { get; set; }
|
||||
public string TokenClass { get; set; } = "mission";
|
||||
public Guid SessionId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace Azaion.Common.Requests;
|
||||
|
||||
public class RegisterDeviceResponse
|
||||
{
|
||||
public string Serial { get; set; } = null!;
|
||||
public string Email { get; set; } = null!;
|
||||
public string Password { get; set; } = null!;
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Azaion.Common.Requests;
|
||||
|
||||
public class SetHWRequest
|
||||
{
|
||||
public string Email { get; set; } = null!;
|
||||
public string? Hardware { get; set; }
|
||||
}
|
||||
|
||||
public class SetHWRequestValidator : AbstractValidator<SetHWRequest>
|
||||
{
|
||||
public SetHWRequestValidator()
|
||||
{
|
||||
RuleFor(r => r.Email).NotEmpty()
|
||||
.WithErrorCode(ExceptionEnum.EmailLengthIncorrect.ToString())
|
||||
.WithMessage(_ => BusinessException.GetMessage(ExceptionEnum.EmailLengthIncorrect));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Azaion.Common.Requests;
|
||||
|
||||
public class UpdateDetectionClassRequest
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? ShortName { get; set; }
|
||||
public string? Color { get; set; }
|
||||
public double? MaxSizeM { get; set; }
|
||||
public string? PhotoMode { get; set; }
|
||||
}
|
||||
|
||||
public class UpdateDetectionClassValidator : AbstractValidator<UpdateDetectionClassRequest>
|
||||
{
|
||||
public UpdateDetectionClassValidator()
|
||||
{
|
||||
RuleFor(r => r.Name!).NotEmpty().MaximumLength(120).When(r => r.Name != null);
|
||||
RuleFor(r => r.ShortName!).NotEmpty().MaximumLength(20).When(r => r.ShortName != null);
|
||||
RuleFor(r => r.Color!).NotEmpty().MaximumLength(20).When(r => r.Color != null);
|
||||
RuleFor(r => r.MaxSizeM!.Value).GreaterThan(0).When(r => r.MaxSizeM != null);
|
||||
RuleFor(r => r.PhotoMode!).MaximumLength(20).When(r => r.PhotoMode != null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using Azaion.Common.Database;
|
||||
using Azaion.Common.Entities;
|
||||
using LinqToDB;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Azaion.Services;
|
||||
|
||||
public interface IAuditLog
|
||||
{
|
||||
Task RecordLoginFailed (string email, CancellationToken ct = default);
|
||||
Task RecordLoginLockout(string email, CancellationToken ct = default);
|
||||
Task RecordLoginSuccess(string email, CancellationToken ct = default);
|
||||
|
||||
// AZ-556 — per-category internal forensics. Wire response is uniformly
|
||||
// `InvalidCredentials`; these recorders keep SecOps's audit trail honest.
|
||||
Task RecordLoginFailedUnknownEmail(string email, CancellationToken ct = default);
|
||||
Task RecordLoginFailedDisabled (string email, CancellationToken ct = default);
|
||||
|
||||
// AZ-534 — MFA lifecycle + login auth-event audit.
|
||||
Task RecordMfaEnroll (string email, CancellationToken ct = default);
|
||||
Task RecordMfaConfirm (string email, CancellationToken ct = default);
|
||||
Task RecordMfaDisable (string email, CancellationToken ct = default);
|
||||
Task RecordMfaLoginSuccess (string email, CancellationToken ct = default);
|
||||
Task RecordMfaLoginFailed (string email, CancellationToken ct = default);
|
||||
Task RecordMfaRecoveryUsed (string email, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Count of failure-audit rows for the given email within the last
|
||||
/// <paramref name="windowSeconds"/> that feed the per-account sliding-window rate
|
||||
/// limit. Includes BOTH password (<c>login_failed</c>) and TOTP
|
||||
/// (<c>mfa_login_failed</c>) failures (AZ-537 AC-2 + AZ-557 AC-3). Disabled-account
|
||||
/// and unknown-email rejections are intentionally excluded — they don't reflect an
|
||||
/// account-credential attack that the lockout/rate-limit policy should escalate.
|
||||
/// </summary>
|
||||
Task<int> CountRecentFailedLogins(string email, int windowSeconds, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public class AuditLog(IDbFactory dbFactory, IHttpContextAccessor httpContextAccessor) : IAuditLog
|
||||
{
|
||||
public Task RecordLoginFailed (string email, CancellationToken ct = default)
|
||||
=> Insert(AuditEventTypes.LoginFailed, email, ct);
|
||||
|
||||
public Task RecordLoginLockout(string email, CancellationToken ct = default)
|
||||
=> Insert(AuditEventTypes.LoginLockout, email, ct);
|
||||
|
||||
public Task RecordLoginSuccess(string email, CancellationToken ct = default)
|
||||
=> Insert(AuditEventTypes.LoginSuccess, email, ct);
|
||||
|
||||
public Task RecordLoginFailedUnknownEmail(string email, CancellationToken ct = default)
|
||||
=> Insert(AuditEventTypes.LoginFailedUnknownEmail, email, ct);
|
||||
|
||||
public Task RecordLoginFailedDisabled(string email, CancellationToken ct = default)
|
||||
=> Insert(AuditEventTypes.LoginFailedDisabled, email, ct);
|
||||
|
||||
public Task RecordMfaEnroll (string email, CancellationToken ct = default)
|
||||
=> Insert(AuditEventTypes.MfaEnroll, email, ct);
|
||||
public Task RecordMfaConfirm (string email, CancellationToken ct = default)
|
||||
=> Insert(AuditEventTypes.MfaConfirm, email, ct);
|
||||
public Task RecordMfaDisable (string email, CancellationToken ct = default)
|
||||
=> Insert(AuditEventTypes.MfaDisable, email, ct);
|
||||
public Task RecordMfaLoginSuccess (string email, CancellationToken ct = default)
|
||||
=> Insert(AuditEventTypes.MfaLoginSuccess, email, ct);
|
||||
public Task RecordMfaLoginFailed (string email, CancellationToken ct = default)
|
||||
=> Insert(AuditEventTypes.MfaLoginFailed, email, ct);
|
||||
public Task RecordMfaRecoveryUsed (string email, CancellationToken ct = default)
|
||||
=> Insert(AuditEventTypes.MfaRecoveryUsed, email, ct);
|
||||
|
||||
public async Task<int> CountRecentFailedLogins(string email, int windowSeconds, CancellationToken ct = default)
|
||||
{
|
||||
var cutoff = DateTime.UtcNow.AddSeconds(-windowSeconds);
|
||||
var normalised = email.ToLowerInvariant();
|
||||
// AZ-557 — MFA failures feed the same per-account sliding-window count as
|
||||
// password failures so an attacker who got past factor 1 can't brute-force
|
||||
// factor 2 from rotating IPs without tripping the per-account throttle.
|
||||
return await dbFactory.Run(async db =>
|
||||
await db.AuditEvents
|
||||
.Where(e => (e.EventType == AuditEventTypes.LoginFailed
|
||||
|| e.EventType == AuditEventTypes.MfaLoginFailed)
|
||||
&& e.Email == normalised
|
||||
&& e.OccurredAt >= cutoff)
|
||||
.CountAsync(token: ct));
|
||||
}
|
||||
|
||||
private async Task Insert(string eventType, string email, CancellationToken ct)
|
||||
{
|
||||
var ip = httpContextAccessor.HttpContext?.Connection.RemoteIpAddress?.ToString();
|
||||
var normalised = email.ToLowerInvariant();
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
{
|
||||
await db.InsertAsync(new AuditEvent
|
||||
{
|
||||
EventType = eventType,
|
||||
OccurredAt = DateTime.UtcNow,
|
||||
Email = normalised,
|
||||
Ip = ip
|
||||
}, token: ct);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Azaion.Common.Configs;
|
||||
using Azaion.Common.Entities;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -12,11 +11,27 @@ namespace Azaion.Services;
|
||||
public interface IAuthService
|
||||
{
|
||||
Task<User?> GetCurrentUser();
|
||||
string CreateToken(User user);
|
||||
|
||||
/// <summary>
|
||||
/// AZ-531 / AZ-532 — mint a 15-minute ES256 access token. <paramref name="sessionId"/>
|
||||
/// is stamped as the <c>sid</c> claim (logout / family-revocation key in AZ-535)
|
||||
/// and <paramref name="jti"/> is the per-token unique id (AZ-535 access denylist).
|
||||
/// AZ-534 — <paramref name="amr"/> values are stamped as repeated <c>amr</c>
|
||||
/// claims so verifiers can require step-up MFA. Defaults to <c>["pwd"]</c>.
|
||||
/// </summary>
|
||||
AccessToken CreateToken(User user, Guid sessionId, Guid jti, IEnumerable<string>? amr = null);
|
||||
}
|
||||
|
||||
public class AuthService(IHttpContextAccessor httpContextAccessor, IOptions<JwtConfig> jwtConfig, IUserService userService) : IAuthService
|
||||
public sealed record AccessToken(string Jwt, DateTime ExpiresAt);
|
||||
|
||||
public class AuthService(
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IOptions<JwtConfig> jwtConfig,
|
||||
IJwtSigningKeyProvider signingKeys,
|
||||
IUserService userService) : IAuthService
|
||||
{
|
||||
private readonly JwtConfig _jwt = jwtConfig.Value;
|
||||
|
||||
private string? GetCurrentUserEmail()
|
||||
{
|
||||
var claims = httpContextAccessor.HttpContext?.User.Claims.ToDictionary(x => x.Type);
|
||||
@@ -29,25 +44,38 @@ public class AuthService(IHttpContextAccessor httpContextAccessor, IOptions<JwtC
|
||||
return await userService.GetByEmail(email);
|
||||
}
|
||||
|
||||
public string CreateToken(User user)
|
||||
public AccessToken CreateToken(User user, Guid sessionId, Guid jti, IEnumerable<string>? amr = null)
|
||||
{
|
||||
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.Value.Secret));
|
||||
var active = signingKeys.Active;
|
||||
var signingCredentials = new SigningCredentials(active.SecurityKey, SecurityAlgorithms.EcdsaSha256);
|
||||
|
||||
var expires = DateTime.UtcNow.AddMinutes(_jwt.AccessTokenLifetimeMinutes);
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
||||
new(ClaimTypes.Name, user.Email),
|
||||
new(ClaimTypes.Role, user.Role.ToString()),
|
||||
new(JwtRegisteredClaimNames.Sid, sessionId.ToString()),
|
||||
new(JwtRegisteredClaimNames.Jti, jti.ToString())
|
||||
};
|
||||
|
||||
// AZ-534 — stamp authentication-methods-reference per RFC 8176. Multi-valued:
|
||||
// password+TOTP login produces ["pwd","mfa"]; recovery-code login adds "recovery".
|
||||
var amrValues = amr?.ToArray() ?? ["pwd"];
|
||||
foreach (var v in amrValues)
|
||||
claims.Add(new Claim("amr", v));
|
||||
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var tokenDescriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity([
|
||||
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
|
||||
new Claim(ClaimTypes.Name, user.Email),
|
||||
new Claim(ClaimTypes.Role, user.Role.ToString())
|
||||
]),
|
||||
Expires = DateTime.UtcNow.AddHours(jwtConfig.Value.TokenLifetimeHours),
|
||||
Issuer = jwtConfig.Value.Issuer,
|
||||
Audience = jwtConfig.Value.Audience,
|
||||
SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature)
|
||||
Subject = new ClaimsIdentity(claims),
|
||||
Expires = expires,
|
||||
Issuer = _jwt.Issuer,
|
||||
Audience = _jwt.Audience,
|
||||
SigningCredentials = signingCredentials
|
||||
};
|
||||
|
||||
var token = tokenHandler.CreateToken(tokenDescriptor);
|
||||
return tokenHandler.WriteToken(token);
|
||||
return new AccessToken(tokenHandler.WriteToken(token), expires);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,11 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Konscious.Security.Cryptography.Argon2" Version="1.3.1" />
|
||||
<PackageReference Include="LazyCache.AspNetCore" Version="2.4.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
|
||||
<PackageReference Include="Otp.NET" Version="1.4.1" />
|
||||
<PackageReference Include="QRCoder" Version="1.8.0" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.1.2" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
using Azaion.Common.Database;
|
||||
using Azaion.Common.Entities;
|
||||
using Azaion.Common.Requests;
|
||||
using LinqToDB;
|
||||
|
||||
namespace Azaion.Services;
|
||||
|
||||
public interface IDetectionClassService
|
||||
{
|
||||
Task<DetectionClass> Create(CreateDetectionClassRequest request, CancellationToken ct = default);
|
||||
Task<DetectionClass?> Update(int id, UpdateDetectionClassRequest request, CancellationToken ct = default);
|
||||
Task<bool> Delete(int id, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public class DetectionClassService(IDbFactory dbFactory) : IDetectionClassService
|
||||
{
|
||||
public async Task<DetectionClass> Create(CreateDetectionClassRequest request, CancellationToken ct = default) =>
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
{
|
||||
var entity = new DetectionClass
|
||||
{
|
||||
Name = request.Name,
|
||||
ShortName = request.ShortName,
|
||||
Color = request.Color,
|
||||
MaxSizeM = request.MaxSizeM,
|
||||
PhotoMode = request.PhotoMode,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
var newId = await db.InsertWithInt32IdentityAsync(entity, token: ct);
|
||||
entity.Id = newId;
|
||||
return entity;
|
||||
});
|
||||
|
||||
public async Task<DetectionClass?> Update(int id, UpdateDetectionClassRequest request, CancellationToken ct = default) =>
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
{
|
||||
var existing = await db.DetectionClasses.FirstOrDefaultAsync(x => x.Id == id, token: ct);
|
||||
if (existing == null)
|
||||
return null;
|
||||
|
||||
if (request.Name != null) existing.Name = request.Name;
|
||||
if (request.ShortName != null) existing.ShortName = request.ShortName;
|
||||
if (request.Color != null) existing.Color = request.Color;
|
||||
if (request.MaxSizeM.HasValue) existing.MaxSizeM = request.MaxSizeM.Value;
|
||||
if (request.PhotoMode != null) existing.PhotoMode = request.PhotoMode;
|
||||
|
||||
await db.UpdateAsync(existing, token: ct);
|
||||
return existing;
|
||||
});
|
||||
|
||||
public async Task<bool> Delete(int id, CancellationToken ct = default) =>
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
{
|
||||
var deleted = await db.DetectionClasses.DeleteAsync(x => x.Id == id, token: ct);
|
||||
return deleted > 0;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
using System.Security.Cryptography;
|
||||
using Azaion.Common.Configs;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Azaion.Services;
|
||||
|
||||
/// <summary>
|
||||
/// AZ-532 — loads ES256 signing keys from <see cref="JwtConfig.KeysFolder"/>.
|
||||
/// One key is "active" (used to sign new tokens); the rest stay in JWKS so
|
||||
/// in-flight tokens minted with older keys still verify during the rotation
|
||||
/// overlap window. The kid of each key is its filename without <c>.pem</c>.
|
||||
/// </summary>
|
||||
public interface IJwtSigningKeyProvider
|
||||
{
|
||||
JwtSigningKey Active { get; }
|
||||
IReadOnlyList<JwtSigningKey> All { get; }
|
||||
}
|
||||
|
||||
public sealed class JwtSigningKey
|
||||
{
|
||||
public string Kid { get; }
|
||||
public ECDsa Ecdsa { get; }
|
||||
public ECDsaSecurityKey SecurityKey { get; }
|
||||
|
||||
public JwtSigningKey(string kid, ECDsa ecdsa)
|
||||
{
|
||||
Kid = kid;
|
||||
Ecdsa = ecdsa;
|
||||
SecurityKey = new ECDsaSecurityKey(ecdsa) { KeyId = kid };
|
||||
}
|
||||
}
|
||||
|
||||
public class JwtSigningKeyProvider : IJwtSigningKeyProvider, IDisposable
|
||||
{
|
||||
private readonly Dictionary<string, JwtSigningKey> _byKid;
|
||||
private readonly JwtSigningKey _active;
|
||||
|
||||
public JwtSigningKeyProvider(IOptions<JwtConfig> jwtConfig, ILogger<JwtSigningKeyProvider> logger)
|
||||
{
|
||||
var folder = jwtConfig.Value.KeysFolder;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(folder) || !Directory.Exists(folder))
|
||||
throw new InvalidOperationException(
|
||||
$"JwtConfig.KeysFolder '{folder}' does not exist. " +
|
||||
"Generate a key with scripts/generate-jwt-key.sh and ensure the folder is mounted into the container.");
|
||||
|
||||
var pemFiles = Directory.EnumerateFiles(folder, "*.pem").OrderBy(p => p).ToList();
|
||||
if (pemFiles.Count == 0)
|
||||
throw new InvalidOperationException(
|
||||
$"No *.pem keys found in '{folder}'. Generate a key with scripts/generate-jwt-key.sh.");
|
||||
|
||||
_byKid = new Dictionary<string, JwtSigningKey>(StringComparer.Ordinal);
|
||||
foreach (var path in pemFiles)
|
||||
{
|
||||
var kid = Path.GetFileNameWithoutExtension(path);
|
||||
var ecdsa = ECDsa.Create();
|
||||
try
|
||||
{
|
||||
ecdsa.ImportFromPem(File.ReadAllText(path));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ecdsa.Dispose();
|
||||
throw new InvalidOperationException($"Failed to load JWT signing key from '{path}'.", ex);
|
||||
}
|
||||
|
||||
EnsureP256(ecdsa, path);
|
||||
_byKid[kid] = new JwtSigningKey(kid, ecdsa);
|
||||
}
|
||||
|
||||
var requestedActive = jwtConfig.Value.ActiveKid;
|
||||
if (!string.IsNullOrEmpty(requestedActive))
|
||||
{
|
||||
if (!_byKid.TryGetValue(requestedActive, out var resolved))
|
||||
throw new InvalidOperationException(
|
||||
$"JwtConfig.ActiveKid '{requestedActive}' is not present in '{folder}'.");
|
||||
_active = resolved;
|
||||
}
|
||||
else
|
||||
{
|
||||
_active = _byKid[Path.GetFileNameWithoutExtension(pemFiles[0])];
|
||||
logger.LogInformation(
|
||||
"JwtConfig.ActiveKid not set; falling back to first key by filename: {Kid}", _active.Kid);
|
||||
}
|
||||
}
|
||||
|
||||
public JwtSigningKey Active => _active;
|
||||
public IReadOnlyList<JwtSigningKey> All => _byKid.Values.OrderBy(k => k.Kid, StringComparer.Ordinal).ToList();
|
||||
|
||||
private static void EnsureP256(ECDsa ecdsa, string path)
|
||||
{
|
||||
// ES256 ⇒ P-256 (prime256v1 / secp256r1). Reject anything else so we don't
|
||||
// silently sign with the wrong curve and break verifiers expecting ES256.
|
||||
var p = ecdsa.ExportParameters(includePrivateParameters: false);
|
||||
var oid = p.Curve.Oid?.Value ?? p.Curve.Oid?.FriendlyName;
|
||||
if (oid is not ("1.2.840.10045.3.1.7" or "nistP256" or "ECDSA_P256"))
|
||||
throw new InvalidOperationException(
|
||||
$"Key '{path}' is not on the P-256 curve (got '{oid ?? "unknown"}'). ES256 requires P-256.");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var k in _byKid.Values) k.Ecdsa.Dispose();
|
||||
_byKid.Clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using Azaion.Common;
|
||||
using Azaion.Common.Configs;
|
||||
using Azaion.Common.Database;
|
||||
using Azaion.Common.Entities;
|
||||
using Azaion.Common.Requests;
|
||||
using LinqToDB;
|
||||
using LinqToDB.Data;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using OtpNet;
|
||||
using QRCoder;
|
||||
|
||||
namespace Azaion.Services;
|
||||
|
||||
/// <summary>
|
||||
/// AZ-534 — RFC 6238 TOTP enrollment + login validation, with single-use recovery codes.
|
||||
/// MfaSecret is encrypted at rest via <see cref="IDataProtector"/>; recovery codes are
|
||||
/// stored as SHA-256 hashes (high-entropy secrets need a fast hash, not Argon2id —
|
||||
/// same reasoning the refresh-token store uses).
|
||||
/// </summary>
|
||||
public interface IMfaService
|
||||
{
|
||||
Task<MfaEnrollResponse> Enroll(Guid userId, string password, CancellationToken ct = default);
|
||||
Task Confirm(Guid userId, string code, CancellationToken ct = default);
|
||||
Task Disable(Guid userId, string password, string code, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Issued at /login when the user has MFA enabled — a 5-minute JWT (aud=azaion-mfa-step2)
|
||||
/// the client carries to /login/mfa for the second-factor verification.
|
||||
/// </summary>
|
||||
string IssueMfaStepToken(Guid userId);
|
||||
|
||||
/// <summary>
|
||||
/// Decode the step-1 token, returning the userId. Throws BusinessException(InvalidMfaToken)
|
||||
/// on bad signature, audience mismatch, or expired token.
|
||||
/// </summary>
|
||||
Guid ValidateMfaStepToken(string token);
|
||||
|
||||
/// <summary>
|
||||
/// AZ-534 AC-3 + AC-4 — second-factor verification at login. Returns the
|
||||
/// <c>amr</c> values the access token should carry (always includes <c>"pwd"</c>
|
||||
/// and <c>"mfa"</c>; <c>"recovery"</c> is added when a recovery code was used).
|
||||
/// </summary>
|
||||
Task<string[]> VerifyForLogin(Guid userId, string code, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public class MfaService(
|
||||
IDbFactory dbFactory,
|
||||
IUserService userService,
|
||||
IDataProtectionProvider dataProtectionProvider,
|
||||
IJwtSigningKeyProvider signingKeys,
|
||||
IOptions<JwtConfig> jwtConfig,
|
||||
IOptions<AuthConfig> authConfig,
|
||||
IAuditLog auditLog) : IMfaService
|
||||
{
|
||||
private const string MfaSecretPurpose = "Azaion.Mfa.Secret.v1";
|
||||
private const string MfaStepAudience = "azaion-mfa-step2";
|
||||
private const int MfaStepLifetimeSeconds = 300; // 5 min — matches AC-3
|
||||
private const int SecretBytes = 20; // 160 bits — RFC 6238 §3
|
||||
private const int RecoveryCodeCount = 10;
|
||||
private const int RecoveryCodeBytes = 10; // base32(10) = 16 chars (≥12 per AC-1)
|
||||
|
||||
private readonly IDataProtector _protector = dataProtectionProvider.CreateProtector(MfaSecretPurpose);
|
||||
private readonly JwtConfig _jwt = jwtConfig.Value;
|
||||
private readonly AuthConfig _auth = authConfig.Value;
|
||||
|
||||
public async Task<MfaEnrollResponse> Enroll(Guid userId, string password, CancellationToken ct = default)
|
||||
{
|
||||
var user = await userService.GetById(userId, ct)
|
||||
?? throw new BusinessException(ExceptionEnum.NoEmailFound);
|
||||
|
||||
// Re-auth with password — AC-1 requires this to defend a stolen access token
|
||||
// from being usable to silently flip the user into MFA.
|
||||
var verify = Security.VerifyPassword(password, user.PasswordHash);
|
||||
if (!verify.Valid)
|
||||
throw new BusinessException(ExceptionEnum.WrongPassword);
|
||||
|
||||
if (user.MfaEnabled)
|
||||
throw new BusinessException(ExceptionEnum.MfaAlreadyEnabled);
|
||||
|
||||
var secretBytes = KeyGeneration.GenerateRandomKey(SecretBytes);
|
||||
var secretBase32 = Base32Encoding.ToString(secretBytes); // 32 chars (per AC-1)
|
||||
|
||||
var otpAuthUrl = new OtpUri(
|
||||
schema: OtpType.Totp,
|
||||
secret: secretBase32,
|
||||
user: user.Email,
|
||||
issuer: _jwt.Issuer,
|
||||
algorithm: OtpHashMode.Sha1,
|
||||
digits: 6,
|
||||
period: 30).ToString();
|
||||
|
||||
var qrPng = GenerateQrPng(otpAuthUrl);
|
||||
|
||||
var recoveryPlain = new string[RecoveryCodeCount];
|
||||
var recoveryStore = new RecoveryCodeStore[RecoveryCodeCount];
|
||||
for (var i = 0; i < RecoveryCodeCount; i++)
|
||||
{
|
||||
var code = Base32Encoding.ToString(KeyGeneration.GenerateRandomKey(RecoveryCodeBytes));
|
||||
recoveryPlain[i] = code;
|
||||
recoveryStore[i] = new RecoveryCodeStore { Hash = HashRecoveryCode(code), UsedAt = null };
|
||||
}
|
||||
|
||||
var encryptedSecret = _protector.Protect(secretBase32);
|
||||
var recoveryJson = JsonSerializer.Serialize(recoveryStore);
|
||||
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
await db.Users.UpdateAsync(
|
||||
u => u.Id == userId,
|
||||
u => new User
|
||||
{
|
||||
MfaSecret = encryptedSecret,
|
||||
MfaRecoveryCodes = recoveryJson,
|
||||
MfaEnabled = false, // confirm step flips this true
|
||||
MfaEnrolledAt = null
|
||||
},
|
||||
token: ct));
|
||||
|
||||
await auditLog.RecordMfaEnroll(user.Email, ct);
|
||||
|
||||
return new MfaEnrollResponse
|
||||
{
|
||||
Secret = secretBase32,
|
||||
OtpAuthUrl = otpAuthUrl,
|
||||
QrPngBase64 = qrPng,
|
||||
RecoveryCodes = recoveryPlain
|
||||
};
|
||||
}
|
||||
|
||||
public async Task Confirm(Guid userId, string code, CancellationToken ct = default)
|
||||
{
|
||||
var user = await userService.GetById(userId, ct)
|
||||
?? throw new BusinessException(ExceptionEnum.NoEmailFound);
|
||||
|
||||
if (user.MfaEnabled)
|
||||
throw new BusinessException(ExceptionEnum.MfaAlreadyEnabled);
|
||||
|
||||
if (string.IsNullOrEmpty(user.MfaSecret))
|
||||
throw new BusinessException(ExceptionEnum.MfaNotEnrolling);
|
||||
|
||||
var secret = _protector.Unprotect(user.MfaSecret);
|
||||
if (!VerifyTotpCode(secret, code, lastUsedWindow: null, out _))
|
||||
throw new BusinessException(ExceptionEnum.InvalidMfaCode);
|
||||
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
await db.Users.UpdateAsync(
|
||||
u => u.Id == userId,
|
||||
u => new User
|
||||
{
|
||||
MfaEnabled = true,
|
||||
MfaEnrolledAt = DateTime.UtcNow
|
||||
},
|
||||
token: ct));
|
||||
|
||||
await auditLog.RecordMfaConfirm(user.Email, ct);
|
||||
}
|
||||
|
||||
public async Task Disable(Guid userId, string password, string code, CancellationToken ct = default)
|
||||
{
|
||||
var user = await userService.GetById(userId, ct)
|
||||
?? throw new BusinessException(ExceptionEnum.NoEmailFound);
|
||||
|
||||
if (!user.MfaEnabled)
|
||||
throw new BusinessException(ExceptionEnum.MfaNotEnabled);
|
||||
|
||||
var verify = Security.VerifyPassword(password, user.PasswordHash);
|
||||
if (!verify.Valid)
|
||||
throw new BusinessException(ExceptionEnum.WrongPassword);
|
||||
|
||||
var secret = _protector.Unprotect(user.MfaSecret!);
|
||||
if (!VerifyTotpCode(secret, code, lastUsedWindow: null, out _))
|
||||
throw new BusinessException(ExceptionEnum.InvalidMfaCode);
|
||||
|
||||
// Raw SQL: setting mfa_recovery_codes (jsonb) to NULL via the LinqToDB UPDATE
|
||||
// expression sends an untyped NULL literal that Postgres parses as text and
|
||||
// rejects (42804). A small parameterized SQL avoids the type-inference dance.
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
await db.ExecuteAsync(
|
||||
@"UPDATE public.users
|
||||
SET mfa_enabled = false,
|
||||
mfa_secret = NULL,
|
||||
mfa_recovery_codes = NULL::jsonb,
|
||||
mfa_enrolled_at = NULL,
|
||||
mfa_last_used_window = NULL
|
||||
WHERE id = @id",
|
||||
new DataParameter("id", userId, DataType.Guid)));
|
||||
|
||||
await auditLog.RecordMfaDisable(user.Email, ct);
|
||||
}
|
||||
|
||||
public string IssueMfaStepToken(Guid userId)
|
||||
{
|
||||
var active = signingKeys.Active;
|
||||
var creds = new SigningCredentials(active.SecurityKey, SecurityAlgorithms.EcdsaSha256);
|
||||
var expires = DateTime.UtcNow.AddSeconds(MfaStepLifetimeSeconds);
|
||||
|
||||
var descriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity([
|
||||
new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
|
||||
new Claim("token_use", "mfa_step")
|
||||
]),
|
||||
Expires = expires,
|
||||
Issuer = _jwt.Issuer,
|
||||
// AZ-534 — narrow audience: this token is ONLY usable at /login/mfa.
|
||||
// The main JwtBearer middleware accepts _jwt.Audience and rejects this one.
|
||||
Audience = MfaStepAudience,
|
||||
SigningCredentials = creds
|
||||
};
|
||||
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
return handler.WriteToken(handler.CreateToken(descriptor));
|
||||
}
|
||||
|
||||
public Guid ValidateMfaStepToken(string token)
|
||||
{
|
||||
try
|
||||
{
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var principal = handler.ValidateToken(token, new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = _jwt.Issuer,
|
||||
ValidAudience = MfaStepAudience,
|
||||
ValidAlgorithms = [SecurityAlgorithms.EcdsaSha256],
|
||||
IssuerSigningKeyResolver = (_, _, _, _) =>
|
||||
signingKeys.All.Select(k => (SecurityKey)k.SecurityKey)
|
||||
}, out _);
|
||||
|
||||
var sub = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value
|
||||
?? throw new BusinessException(ExceptionEnum.InvalidMfaToken);
|
||||
return Guid.Parse(sub);
|
||||
}
|
||||
catch (BusinessException) { throw; }
|
||||
catch (Exception)
|
||||
{
|
||||
throw new BusinessException(ExceptionEnum.InvalidMfaToken);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string[]> VerifyForLogin(Guid userId, string code, CancellationToken ct = default)
|
||||
{
|
||||
var user = await userService.GetById(userId, ct)
|
||||
?? throw new BusinessException(ExceptionEnum.InvalidCredentials);
|
||||
|
||||
if (!user.MfaEnabled || string.IsNullOrEmpty(user.MfaSecret))
|
||||
throw new BusinessException(ExceptionEnum.MfaNotEnabled);
|
||||
|
||||
// AZ-557 — active lockout from EITHER the password or the MFA side rejects
|
||||
// the request before the TOTP verify runs, with the same wire shape the
|
||||
// password path uses (`InvalidCredentials` + Retry-After).
|
||||
if (user.LockoutUntil is { } until && until > DateTime.UtcNow)
|
||||
{
|
||||
var remaining = (int)Math.Ceiling((until - DateTime.UtcNow).TotalSeconds);
|
||||
throw new BusinessException(ExceptionEnum.InvalidCredentials, Math.Max(remaining, 1));
|
||||
}
|
||||
|
||||
// AZ-557 — per-account sliding-window rate limit applies to MFA failures too
|
||||
// (CountRecentFailedLogins counts login_failed + mfa_login_failed). Without
|
||||
// this an attacker with a leaked password could brute-force the 6-digit TOTP
|
||||
// from rotating IPs without ever tripping the per-account throttle.
|
||||
var recentFailures = await auditLog.CountRecentFailedLogins(
|
||||
user.Email, _auth.RateLimit.PerAccountWindowSeconds, ct);
|
||||
if (recentFailures >= _auth.RateLimit.PerAccountPermitLimit)
|
||||
throw new BusinessException(ExceptionEnum.InvalidCredentials, _auth.RateLimit.PerAccountWindowSeconds);
|
||||
|
||||
var secret = _protector.Unprotect(user.MfaSecret);
|
||||
if (VerifyTotpCode(secret, code, user.MfaLastUsedWindow, out var window))
|
||||
{
|
||||
// Persist last-used window so a re-presented code in the same 30 s
|
||||
// step is rejected even if the attacker presents it before the next step.
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
await db.Users.UpdateAsync(
|
||||
u => u.Id == userId,
|
||||
u => new User { MfaLastUsedWindow = window },
|
||||
token: ct));
|
||||
// AZ-557 — TOTP success also resets the failure counter so a user who
|
||||
// fat-fingered a few codes before getting it right doesn't drift toward
|
||||
// lockout. Mirrors the password-side reset in RegisterSuccessfulLogin.
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
await db.Users.UpdateAsync(
|
||||
u => u.Id == userId,
|
||||
u => new User { FailedLoginCount = 0, LockoutUntil = null },
|
||||
token: ct));
|
||||
await auditLog.RecordMfaLoginSuccess(user.Email, ct);
|
||||
return ["pwd", "mfa"];
|
||||
}
|
||||
|
||||
// TOTP failed — try recovery code (single-use). Recovery codes are
|
||||
// high-entropy and intentionally NOT counted by the lockout pipeline; a
|
||||
// locked-out user can still escape via a recovery code.
|
||||
if (await TryConsumeRecoveryCode(user, code, ct))
|
||||
{
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
await db.Users.UpdateAsync(
|
||||
u => u.Id == user.Id,
|
||||
u => new User { FailedLoginCount = 0, LockoutUntil = null },
|
||||
token: ct));
|
||||
await auditLog.RecordMfaRecoveryUsed(user.Email, ct);
|
||||
return ["pwd", "mfa", "recovery"];
|
||||
}
|
||||
|
||||
// AZ-557 — feed the shared failure-accounting helper. It records the audit
|
||||
// row (mfa_login_failed), bumps failed_login_count, and on threshold-crossing
|
||||
// throws InvalidCredentials + Retry-After (which we let propagate). If it
|
||||
// does NOT throw, we fall through and throw the bare InvalidCredentials so
|
||||
// the wire response is uniform with the password path.
|
||||
await userService.RegisterMfaFailedLogin(user, ct);
|
||||
throw new BusinessException(ExceptionEnum.InvalidCredentials);
|
||||
}
|
||||
|
||||
private static bool VerifyTotpCode(string secretBase32, string code, long? lastUsedWindow, out long matchedWindow)
|
||||
{
|
||||
matchedWindow = 0;
|
||||
var totp = new Totp(Base32Encoding.ToBytes(secretBase32));
|
||||
if (!totp.VerifyTotp(code, out matchedWindow, VerificationWindow.RfcSpecifiedNetworkDelay))
|
||||
return false;
|
||||
if (lastUsedWindow.HasValue && matchedWindow <= lastUsedWindow.Value)
|
||||
return false; // replay within or before the last accepted window
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task<bool> TryConsumeRecoveryCode(User user, string code, CancellationToken ct)
|
||||
{
|
||||
if (string.IsNullOrEmpty(user.MfaRecoveryCodes)) return false;
|
||||
|
||||
var codes = JsonSerializer.Deserialize<RecoveryCodeStore[]>(user.MfaRecoveryCodes)
|
||||
?? Array.Empty<RecoveryCodeStore>();
|
||||
var candidateHash = HashRecoveryCode(code);
|
||||
|
||||
var matchIdx = -1;
|
||||
for (var i = 0; i < codes.Length; i++)
|
||||
{
|
||||
if (codes[i].UsedAt != null) continue;
|
||||
if (CryptographicOperations.FixedTimeEquals(
|
||||
System.Text.Encoding.ASCII.GetBytes(codes[i].Hash),
|
||||
System.Text.Encoding.ASCII.GetBytes(candidateHash)))
|
||||
{
|
||||
matchIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matchIdx < 0) return false;
|
||||
|
||||
codes[matchIdx] = codes[matchIdx] with { UsedAt = DateTime.UtcNow };
|
||||
var updated = JsonSerializer.Serialize(codes);
|
||||
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
await db.Users.UpdateAsync(
|
||||
// Conditional update on the prior JSON to avoid a race where two
|
||||
// concurrent /login/mfa calls both consume the same code.
|
||||
u => u.Id == user.Id && u.MfaRecoveryCodes == user.MfaRecoveryCodes,
|
||||
u => new User { MfaRecoveryCodes = updated },
|
||||
token: ct));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string GenerateQrPng(string text)
|
||||
{
|
||||
using var generator = new QRCodeGenerator();
|
||||
using var data = generator.CreateQrCode(text, QRCodeGenerator.ECCLevel.M);
|
||||
var pngBytes = new PngByteQRCode(data).GetGraphic(pixelsPerModule: 6);
|
||||
return Convert.ToBase64String(pngBytes);
|
||||
}
|
||||
|
||||
private static string HashRecoveryCode(string code)
|
||||
{
|
||||
var bytes = System.Text.Encoding.UTF8.GetBytes(code);
|
||||
var digest = SHA256.HashData(bytes);
|
||||
return Convert.ToHexString(digest);
|
||||
}
|
||||
|
||||
private sealed record RecoveryCodeStore
|
||||
{
|
||||
public string Hash { get; init; } = "";
|
||||
public DateTime? UsedAt { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Azaion.Common;
|
||||
using Azaion.Common.Configs;
|
||||
using Azaion.Common.Database;
|
||||
using Azaion.Common.Entities;
|
||||
using Azaion.Common.Requests;
|
||||
using LinqToDB;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace Azaion.Services;
|
||||
|
||||
/// <summary>
|
||||
/// AZ-533 — issues long-lived single-use access tokens for offline UAV missions.
|
||||
/// Distinct from <see cref="IAuthService"/> because:
|
||||
/// <list type="bullet">
|
||||
/// <item>Lifetime is per-mission (≤ 12 h), not per-session policy.</item>
|
||||
/// <item>Audience is narrowed to <c>satellite-provider</c>, not the broad admin audience.</item>
|
||||
/// <item>No refresh: a single token covers the entire flight, then dies.</item>
|
||||
/// <item>Carries mission-specific claims (mission_id, aircraft_id, valid_region).</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public interface IMissionTokenService
|
||||
{
|
||||
Task<MissionSessionResponse> Issue(Guid pilotUserId, MissionSessionRequest request, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public class MissionTokenService(
|
||||
IDbFactory dbFactory,
|
||||
IJwtSigningKeyProvider signingKeys,
|
||||
IOptions<JwtConfig> jwtConfig) : IMissionTokenService
|
||||
{
|
||||
private const string MissionAudience = "satellite-provider";
|
||||
private const double MaxDurationHours = 12.0;
|
||||
private const double MinDurationHours = 0.1;
|
||||
private const double LifetimeBufferHours = 1.0; // covers post-flight reconnect grace
|
||||
|
||||
private static readonly Regex MissionIdPattern =
|
||||
new(@"^M-\d{4}-\d{2}-\d{2}-\d{3}$", RegexOptions.Compiled);
|
||||
|
||||
private readonly JwtConfig _jwt = jwtConfig.Value;
|
||||
|
||||
public async Task<MissionSessionResponse> Issue(Guid pilotUserId, MissionSessionRequest request, CancellationToken ct = default)
|
||||
{
|
||||
Validate(request);
|
||||
|
||||
// Aircraft must exist with Role=CompanionPC. Anything else is a config error.
|
||||
var aircraft = await dbFactory.Run(async db =>
|
||||
await db.Users.FirstOrDefaultAsync(u => u.Id == request.AircraftId, token: ct));
|
||||
if (aircraft == null || aircraft.Role != RoleEnum.CompanionPC)
|
||||
throw new BusinessException(ExceptionEnum.AircraftNotFound);
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
var expAt = now.AddHours(request.PlannedDurationH + LifetimeBufferHours);
|
||||
var sid = Guid.NewGuid();
|
||||
var jti = Guid.NewGuid();
|
||||
|
||||
// Persist the session BEFORE we mint the token so revocation lookups can
|
||||
// never miss a token that's already in the wild.
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
await db.InsertAsync(new Session
|
||||
{
|
||||
Id = sid,
|
||||
UserId = pilotUserId,
|
||||
FamilyId = sid, // mission sessions are their own family — no rotation
|
||||
IssuedAt = now,
|
||||
LastUsedAt = now,
|
||||
ExpiresAt = expAt,
|
||||
FamilyStartedAt = now,
|
||||
Class = SessionClasses.Mission,
|
||||
AircraftId = request.AircraftId,
|
||||
// RefreshHash null — no refresh value backs a mission token.
|
||||
}, token: ct));
|
||||
|
||||
var token = MintToken(pilotUserId, request, sid, jti, expAt);
|
||||
|
||||
return new MissionSessionResponse
|
||||
{
|
||||
AccessToken = token,
|
||||
AccessExp = expAt,
|
||||
TokenClass = SessionClasses.Mission,
|
||||
SessionId = sid,
|
||||
};
|
||||
}
|
||||
|
||||
private static void Validate(MissionSessionRequest request)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(request.MissionId) || !MissionIdPattern.IsMatch(request.MissionId))
|
||||
throw new BusinessException(ExceptionEnum.InvalidMissionRequest);
|
||||
|
||||
if (request.PlannedDurationH < MinDurationHours || request.PlannedDurationH > MaxDurationHours)
|
||||
throw new BusinessException(ExceptionEnum.InvalidMissionRequest);
|
||||
}
|
||||
|
||||
private string MintToken(Guid pilotUserId, MissionSessionRequest request, Guid sid, Guid jti, DateTime expAt)
|
||||
{
|
||||
var active = signingKeys.Active;
|
||||
var creds = new SigningCredentials(active.SecurityKey, SecurityAlgorithms.EcdsaSha256);
|
||||
|
||||
var claims = new List<Claim>
|
||||
{
|
||||
new(ClaimTypes.NameIdentifier, pilotUserId.ToString()),
|
||||
new(JwtRegisteredClaimNames.Sid, sid.ToString()),
|
||||
new(JwtRegisteredClaimNames.Jti, jti.ToString()),
|
||||
new("mission_id", request.MissionId),
|
||||
new("aircraft_id", request.AircraftId.ToString()),
|
||||
new("token_class", SessionClasses.Mission),
|
||||
};
|
||||
|
||||
if (request.RequestedScope is { Count: > 0 })
|
||||
foreach (var p in request.RequestedScope)
|
||||
claims.Add(new Claim("permissions", p));
|
||||
|
||||
if (request.ValidRegion != null)
|
||||
claims.Add(new Claim(
|
||||
"valid_region",
|
||||
JsonSerializer.Serialize(request.ValidRegion),
|
||||
JsonClaimValueTypes.Json));
|
||||
|
||||
var descriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity(claims),
|
||||
Expires = expAt,
|
||||
Issuer = _jwt.Issuer,
|
||||
// AZ-533 — narrowed audience: satellite-provider only, not the broad
|
||||
// interactive audience. Verifiers downstream gate on this claim.
|
||||
Audience = MissionAudience,
|
||||
SigningCredentials = creds
|
||||
};
|
||||
|
||||
var handler = new JwtSecurityTokenHandler();
|
||||
var token = handler.CreateToken(descriptor);
|
||||
return handler.WriteToken(token);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Azaion.Common;
|
||||
using Azaion.Common.Configs;
|
||||
using Azaion.Common.Database;
|
||||
using Azaion.Common.Entities;
|
||||
using LinqToDB;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Azaion.Services;
|
||||
|
||||
/// <summary>
|
||||
/// AZ-531 — issues, rotates, and validates opaque refresh tokens. Reuse-detection
|
||||
/// kills the entire session family per OAuth 2.1 §6.1.
|
||||
/// </summary>
|
||||
public interface IRefreshTokenService
|
||||
{
|
||||
/// <summary>
|
||||
/// Mint a fresh refresh token at login; starts a new session family. Returns
|
||||
/// the opaque token (NEVER persisted; only its sha256 lands in the DB) and
|
||||
/// the session row that backs it. <paramref name="mfaAuthenticated"/> is pinned
|
||||
/// to the session so refresh-token rotation inherits the original AMR strength.
|
||||
/// </summary>
|
||||
Task<(string OpaqueToken, Session Session)> IssueForNewLogin(Guid userId, bool mfaAuthenticated = false, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Rotate <paramref name="opaqueToken"/>. On success returns the new token +
|
||||
/// the new session row. On reuse-detection or invalid token throws
|
||||
/// <see cref="BusinessException"/> with <see cref="ExceptionEnum.InvalidRefreshToken"/>;
|
||||
/// reuse also revokes every active row in the same family.
|
||||
/// </summary>
|
||||
Task<(string OpaqueToken, Session Session)> Rotate(string opaqueToken, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public class RefreshTokenService(IDbFactory dbFactory, IOptions<SessionConfig> sessionConfig) : IRefreshTokenService
|
||||
{
|
||||
private const int OpaqueTokenBytes = 32; // 256 bits → 43-char base64url string.
|
||||
|
||||
private readonly SessionConfig _cfg = sessionConfig.Value;
|
||||
|
||||
public async Task<(string OpaqueToken, Session Session)> IssueForNewLogin(Guid userId, bool mfaAuthenticated = false, CancellationToken ct = default)
|
||||
{
|
||||
var (opaque, hash) = GenerateToken();
|
||||
var now = DateTime.UtcNow;
|
||||
var session = new Session
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
RefreshHash = hash,
|
||||
FamilyId = Guid.NewGuid(), // self-rooted family
|
||||
IssuedAt = now,
|
||||
LastUsedAt = now,
|
||||
ExpiresAt = now.AddHours(_cfg.RefreshSlidingHours),
|
||||
FamilyStartedAt = now,
|
||||
MfaAuthenticated = mfaAuthenticated,
|
||||
};
|
||||
// family_id should equal id for the root row so SELECT family_id from
|
||||
// any row returns a stable handle even if id is renamed later.
|
||||
session.FamilyId = session.Id;
|
||||
|
||||
await dbFactory.RunAdmin(async db => await db.InsertAsync(session, token: ct));
|
||||
return (opaque, session);
|
||||
}
|
||||
|
||||
public async Task<(string OpaqueToken, Session Session)> Rotate(string opaqueToken, CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(opaqueToken))
|
||||
throw new BusinessException(ExceptionEnum.InvalidRefreshToken);
|
||||
|
||||
var hash = HashToken(opaqueToken);
|
||||
var now = DateTime.UtcNow;
|
||||
|
||||
return await dbFactory.RunAdmin(async db =>
|
||||
{
|
||||
// Use a serializable transaction so two concurrent refreshes can't both
|
||||
// observe the row as un-rotated and both succeed.
|
||||
await using var tx = await db.BeginTransactionAsync(System.Data.IsolationLevel.Serializable, ct);
|
||||
|
||||
var current = await db.Sessions.FirstOrDefaultAsync(s => s.RefreshHash == hash, token: ct);
|
||||
if (current == null)
|
||||
throw new BusinessException(ExceptionEnum.InvalidRefreshToken);
|
||||
|
||||
// Reuse detection: presenting an already-rotated token kills the family.
|
||||
if (current.RevokedAt.HasValue)
|
||||
{
|
||||
if (current.RevokedReason == SessionRevokedReasons.Rotated)
|
||||
{
|
||||
await db.Sessions
|
||||
.Where(s => s.FamilyId == current.FamilyId && s.RevokedAt == null)
|
||||
.Set(s => s.RevokedAt, now)
|
||||
.Set(s => s.RevokedReason, SessionRevokedReasons.ReuseDetected)
|
||||
.UpdateAsync(token: ct);
|
||||
await tx.CommitAsync(ct);
|
||||
}
|
||||
throw new BusinessException(ExceptionEnum.InvalidRefreshToken);
|
||||
}
|
||||
|
||||
// Sliding expiry — each rotation restarts the window from `now`.
|
||||
if (current.ExpiresAt < now)
|
||||
throw new BusinessException(ExceptionEnum.InvalidRefreshToken);
|
||||
|
||||
// Absolute expiry — the family cannot live past this regardless of rotations.
|
||||
if ((now - current.FamilyStartedAt).TotalHours > _cfg.RefreshAbsoluteHours)
|
||||
throw new BusinessException(ExceptionEnum.InvalidRefreshToken);
|
||||
|
||||
var (newOpaque, newHash) = GenerateToken();
|
||||
var newSession = new Session
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = current.UserId,
|
||||
RefreshHash = newHash,
|
||||
FamilyId = current.FamilyId,
|
||||
IssuedAt = now,
|
||||
LastUsedAt = now,
|
||||
ExpiresAt = now.AddHours(_cfg.RefreshSlidingHours),
|
||||
FamilyStartedAt = current.FamilyStartedAt,
|
||||
ParentSessionId = current.Id,
|
||||
MfaAuthenticated = current.MfaAuthenticated,
|
||||
};
|
||||
|
||||
await db.Sessions
|
||||
.Where(s => s.Id == current.Id && s.RevokedAt == null)
|
||||
.Set(s => s.RevokedAt, now)
|
||||
.Set(s => s.RevokedReason, SessionRevokedReasons.Rotated)
|
||||
.Set(s => s.LastUsedAt, now)
|
||||
.UpdateAsync(token: ct);
|
||||
|
||||
await db.InsertAsync(newSession, token: ct);
|
||||
await tx.CommitAsync(ct);
|
||||
return (newOpaque, newSession);
|
||||
});
|
||||
}
|
||||
|
||||
private static (string Opaque, string Hash) GenerateToken()
|
||||
{
|
||||
var raw = RandomNumberGenerator.GetBytes(OpaqueTokenBytes);
|
||||
var opaque = Base64Url(raw);
|
||||
var hash = HashToken(opaque);
|
||||
return (opaque, hash);
|
||||
}
|
||||
|
||||
private static string HashToken(string opaque)
|
||||
{
|
||||
var bytes = Encoding.ASCII.GetBytes(opaque);
|
||||
var digest = SHA256.HashData(bytes);
|
||||
return Convert.ToHexString(digest);
|
||||
}
|
||||
|
||||
private static string Base64Url(byte[] bytes) =>
|
||||
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
}
|
||||
@@ -8,8 +8,6 @@ namespace Azaion.Services;
|
||||
|
||||
public interface IResourcesService
|
||||
{
|
||||
(string?, Stream?) GetInstaller(bool isStage);
|
||||
Task<Stream> GetEncryptedResource(string? dataFolder, string fileName, string key, CancellationToken cancellationToken = default);
|
||||
Task SaveResource(string? dataFolder, IFormFile data, CancellationToken cancellationToken = default);
|
||||
Task<IEnumerable<string>> ListResources(string? dataFolder, string? search, CancellationToken cancellationToken = default);
|
||||
void ClearFolder(string? dataFolder);
|
||||
@@ -24,29 +22,6 @@ public class ResourcesService(IOptions<ResourcesConfig> resourcesConfig, ILogger
|
||||
: Path.Combine(resourcesConfig.Value.ResourcesFolder, dataFolder);
|
||||
}
|
||||
|
||||
public (string?, Stream?) GetInstaller(bool isStage)
|
||||
{
|
||||
var suiteFolder = Path.Combine(resourcesConfig.Value.ResourcesFolder, isStage
|
||||
? resourcesConfig.Value.SuiteStageInstallerFolder
|
||||
: resourcesConfig.Value.SuiteInstallerFolder);
|
||||
var installer = new DirectoryInfo(suiteFolder).GetFiles("AzaionSuite.Iterative*").FirstOrDefault();
|
||||
if (installer == null)
|
||||
return (null, null);
|
||||
|
||||
var fileStream = new FileStream(installer.FullName, FileMode.Open, FileAccess.Read);
|
||||
return (installer.Name, fileStream);
|
||||
}
|
||||
|
||||
public async Task<Stream> GetEncryptedResource(string? dataFolder, string fileName, string key, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var fileStream = new FileStream(Path.Combine(GetResourceFolder(dataFolder), fileName), FileMode.Open, FileAccess.Read);
|
||||
|
||||
var ms = new MemoryStream();
|
||||
await fileStream.EncryptTo(ms, key, cancellationToken);
|
||||
ms.Seek(0, SeekOrigin.Begin);
|
||||
return ms;
|
||||
}
|
||||
|
||||
public async Task SaveResource(string? dataFolder, IFormFile data, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (data == null)
|
||||
|
||||
+135
-47
@@ -1,64 +1,152 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Azaion.Common.Entities;
|
||||
using Konscious.Security.Cryptography;
|
||||
|
||||
namespace Azaion.Services;
|
||||
|
||||
// Password hashing — Argon2id (RFC 9106) for new + lazy migration of legacy SHA-384.
|
||||
// Stored format: PHC string `$argon2id$v=19$m=<KiB>,t=<iters>,p=<lanes>$<salt-b64>$<hash-b64>`.
|
||||
// Legacy format: 64-char base64 of unsalted SHA-384 (no `$` prefix). Detected by prefix.
|
||||
//
|
||||
// AZ-536 (Epic AZ-530, CMMC IA.L2-3.5.10).
|
||||
public static class Security
|
||||
{
|
||||
private const int BUFFER_SIZE = 524288; // 512 KB buffer size
|
||||
// Conservative defaults per RFC 9106 §4. Bump in the future and the verify path
|
||||
// will surface NeedsRehash=true for any hash whose params are weaker.
|
||||
private const int Argon2MemoryKib = 65536; // 64 MiB
|
||||
private const int Argon2Iterations = 3;
|
||||
private const int Argon2Parallelism = 1;
|
||||
private const int SaltLengthBytes = 16; // 128 bits — RFC 9106 recommended minimum
|
||||
private const int HashLengthBytes = 32; // 256 bits
|
||||
private const string PhcPrefix = "$argon2id$";
|
||||
private const int LegacySha384B64Length = 64; // Convert.ToBase64String(48 bytes) == 64 chars
|
||||
|
||||
public static string ToHash(this string str) =>
|
||||
Convert.ToBase64String(SHA384.HashData(Encoding.UTF8.GetBytes(str)));
|
||||
public sealed record VerifyResult(bool Valid, bool NeedsRehash);
|
||||
|
||||
public static string GetHWHash(string hardware) =>
|
||||
$"Azaion_{hardware}_%$$$)0_".ToHash();
|
||||
// AZ-556 — timing equalizer for unknown-email and disabled-account branches of
|
||||
// `UserService.ValidateUser`. Pre-computed once with the same Argon2id parameters
|
||||
// as a real hash so a `VerifyDummy(plaintext)` call costs ~the same wall-clock as
|
||||
// a real `VerifyPassword(plaintext, user.PasswordHash)`. The result is always
|
||||
// discarded — this is a side-channel mitigation, not a control-flow path.
|
||||
private static readonly string DummyHashForTiming = HashPassword(
|
||||
"az-556-timing-equalizer-dummy-do-not-store-in-db");
|
||||
|
||||
public static string GetApiEncryptionKey(string email, string password, string? hardwareHash) =>
|
||||
$"{email}-{password}-{hardwareHash}-#%@AzaionKey@%#---".ToHash();
|
||||
|
||||
public static async Task EncryptTo(this Stream inputStream, Stream toStream, string key, CancellationToken cancellationToken = default)
|
||||
/// <summary>
|
||||
/// AZ-556 — run the same Argon2id work a real verify would do, then discard the
|
||||
/// result. Used to keep the unknown-email and disabled-account login branches
|
||||
/// timing-indistinguishable from a wrong-password branch.
|
||||
/// </summary>
|
||||
public static void VerifyDummy(string plaintext)
|
||||
{
|
||||
inputStream.Seek(0, SeekOrigin.Begin);
|
||||
if (inputStream is { CanRead: false }) throw new ArgumentNullException(nameof(inputStream));
|
||||
if (key is not { Length: > 0 }) throw new ArgumentNullException(nameof(key));
|
||||
|
||||
using var aes = Aes.Create();
|
||||
aes.Mode = CipherMode.CBC;
|
||||
aes.Padding = PaddingMode.PKCS7;
|
||||
aes.Key = SHA256.HashData(Encoding.UTF8.GetBytes(key));
|
||||
aes.GenerateIV();
|
||||
using var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
|
||||
|
||||
await using var cs = new CryptoStream(toStream, encryptor, CryptoStreamMode.Write, leaveOpen: true);
|
||||
|
||||
await toStream.WriteAsync(aes.IV.AsMemory(0, aes.IV.Length), cancellationToken);
|
||||
|
||||
var buffer = new byte[BUFFER_SIZE];
|
||||
int bytesRead;
|
||||
while ((bytesRead = await inputStream.ReadAsync(buffer, cancellationToken)) > 0)
|
||||
await cs.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken);
|
||||
_ = VerifyPassword(plaintext, DummyHashForTiming);
|
||||
}
|
||||
|
||||
public static async Task DecryptTo(this Stream encryptedStream, Stream toStream, string key, CancellationToken cancellationToken = default)
|
||||
public static string HashPassword(string plaintext)
|
||||
{
|
||||
encryptedStream.Seek(0, SeekOrigin.Begin);
|
||||
using var aes = Aes.Create();
|
||||
aes.Key = SHA256.HashData(Encoding.UTF8.GetBytes(key));
|
||||
if (plaintext == null) throw new ArgumentNullException(nameof(plaintext));
|
||||
|
||||
var iv = new byte[aes.BlockSize / 8];
|
||||
_ = await encryptedStream.ReadAsync(iv, cancellationToken);
|
||||
aes.IV = iv;
|
||||
aes.Mode = CipherMode.CBC;
|
||||
aes.Padding = PaddingMode.PKCS7;
|
||||
using var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
|
||||
|
||||
await using var cryptoStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read, leaveOpen: true);
|
||||
|
||||
var buffer = new byte[BUFFER_SIZE];
|
||||
int bytesRead;
|
||||
while ((bytesRead = await cryptoStream.ReadAsync(buffer, cancellationToken)) > 0)
|
||||
await toStream.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken);
|
||||
toStream.Seek(0, SeekOrigin.Begin);
|
||||
var salt = RandomNumberGenerator.GetBytes(SaltLengthBytes);
|
||||
var hash = ComputeArgon2id(plaintext, salt, Argon2MemoryKib, Argon2Iterations, Argon2Parallelism);
|
||||
return EncodePhc(Argon2MemoryKib, Argon2Iterations, Argon2Parallelism, salt, hash);
|
||||
}
|
||||
|
||||
public static VerifyResult VerifyPassword(string plaintext, string stored)
|
||||
{
|
||||
if (plaintext == null) throw new ArgumentNullException(nameof(plaintext));
|
||||
if (string.IsNullOrEmpty(stored)) return new VerifyResult(Valid: false, NeedsRehash: false);
|
||||
|
||||
if (stored.StartsWith(PhcPrefix, StringComparison.Ordinal))
|
||||
{
|
||||
if (!TryDecodePhc(stored, out var p))
|
||||
return new VerifyResult(Valid: false, NeedsRehash: false);
|
||||
|
||||
var candidate = ComputeArgon2id(plaintext, p.Salt, p.MemoryKib, p.Iterations, p.Parallelism);
|
||||
var valid = CryptographicOperations.FixedTimeEquals(candidate, p.Hash);
|
||||
// NeedsRehash true if defaults are stronger than the stored params — supports later upgrades.
|
||||
var needsRehash = valid && (p.MemoryKib < Argon2MemoryKib
|
||||
|| p.Iterations < Argon2Iterations
|
||||
|| p.Parallelism < Argon2Parallelism);
|
||||
return new VerifyResult(valid, needsRehash);
|
||||
}
|
||||
|
||||
if (IsLegacySha384(stored))
|
||||
{
|
||||
var legacyHash = SHA384.HashData(Encoding.UTF8.GetBytes(plaintext));
|
||||
var legacyB64Bytes = Encoding.ASCII.GetBytes(Convert.ToBase64String(legacyHash));
|
||||
var storedBytes = Encoding.ASCII.GetBytes(stored);
|
||||
var valid = storedBytes.Length == legacyB64Bytes.Length
|
||||
&& CryptographicOperations.FixedTimeEquals(storedBytes, legacyB64Bytes);
|
||||
return new VerifyResult(valid, NeedsRehash: valid);
|
||||
}
|
||||
|
||||
return new VerifyResult(Valid: false, NeedsRehash: false);
|
||||
}
|
||||
|
||||
private static bool IsLegacySha384(string stored) =>
|
||||
stored.Length == LegacySha384B64Length && !stored.StartsWith('$');
|
||||
|
||||
private static byte[] ComputeArgon2id(string plaintext, byte[] salt, int memoryKib, int iterations, int parallelism)
|
||||
{
|
||||
using var argon = new Argon2id(Encoding.UTF8.GetBytes(plaintext))
|
||||
{
|
||||
Salt = salt,
|
||||
MemorySize = memoryKib,
|
||||
Iterations = iterations,
|
||||
DegreeOfParallelism = parallelism
|
||||
};
|
||||
return argon.GetBytes(HashLengthBytes);
|
||||
}
|
||||
|
||||
private static string EncodePhc(int memoryKib, int iterations, int parallelism, byte[] salt, byte[] hash) =>
|
||||
$"$argon2id$v=19$m={memoryKib},t={iterations},p={parallelism}${ToB64NoPad(salt)}${ToB64NoPad(hash)}";
|
||||
|
||||
private static bool TryDecodePhc(string stored, out PhcParams parsed)
|
||||
{
|
||||
parsed = default!;
|
||||
// $argon2id$v=19$m=65536,t=3,p=1$<salt>$<hash>
|
||||
var parts = stored.Split('$');
|
||||
if (parts.Length != 6) return false;
|
||||
if (parts[1] != "argon2id") return false;
|
||||
if (parts[2] != "v=19") return false;
|
||||
|
||||
var paramFields = parts[3].Split(',');
|
||||
if (paramFields.Length != 3) return false;
|
||||
if (!TryParseKv(paramFields[0], "m", out var m)) return false;
|
||||
if (!TryParseKv(paramFields[1], "t", out var t)) return false;
|
||||
if (!TryParseKv(paramFields[2], "p", out var p)) return false;
|
||||
|
||||
if (!TryFromB64NoPad(parts[4], out var salt)) return false;
|
||||
if (!TryFromB64NoPad(parts[5], out var hash)) return false;
|
||||
|
||||
parsed = new PhcParams(m, t, p, salt, hash);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TryParseKv(string field, string key, out int value)
|
||||
{
|
||||
value = 0;
|
||||
var eq = field.IndexOf('=');
|
||||
if (eq <= 0 || field[..eq] != key) return false;
|
||||
return int.TryParse(field.AsSpan(eq + 1), out value) && value > 0;
|
||||
}
|
||||
|
||||
private static string ToB64NoPad(byte[] bytes) =>
|
||||
Convert.ToBase64String(bytes).TrimEnd('=');
|
||||
|
||||
private static bool TryFromB64NoPad(string s, out byte[] bytes)
|
||||
{
|
||||
var padded = s.Length % 4 == 0 ? s : s + new string('=', 4 - s.Length % 4);
|
||||
try
|
||||
{
|
||||
bytes = Convert.FromBase64String(padded);
|
||||
return true;
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
bytes = Array.Empty<byte>();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private readonly record struct PhcParams(int MemoryKib, int Iterations, int Parallelism, byte[] Salt, byte[] Hash);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
using Azaion.Common;
|
||||
using Azaion.Common.Database;
|
||||
using Azaion.Common.Entities;
|
||||
using LinqToDB;
|
||||
|
||||
namespace Azaion.Services;
|
||||
|
||||
/// <summary>
|
||||
/// AZ-535 — logout/revocation surface. Distinct from <see cref="IRefreshTokenService"/>:
|
||||
/// refresh-token service rotates and reuse-detects; this service expresses the
|
||||
/// human / admin / system intent to kill a session and exposes the verifier-poll
|
||||
/// snapshot that powers cross-service denylists.
|
||||
/// </summary>
|
||||
public interface ISessionService
|
||||
{
|
||||
/// <summary>
|
||||
/// Revoke a single session by id. Returns the revocation status BEFORE this
|
||||
/// call: <c>true</c> if it was already revoked (idempotent no-op),
|
||||
/// <c>false</c> if this call is the one that revoked it.
|
||||
/// </summary>
|
||||
Task<bool> RevokeBySid(Guid sessionId, Guid? byUserId, string reason, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Revoke every active session for a user. Returns the count of rows newly
|
||||
/// revoked by this call.
|
||||
/// </summary>
|
||||
Task<int> RevokeAllForUser(Guid userId, Guid? byUserId, string reason, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// AZ-533 — auto-revoke every open mission session belonging to <paramref name="aircraftId"/>.
|
||||
/// Fired on successful /login or /token/refresh from the aircraft's own user.
|
||||
/// </summary>
|
||||
Task<int> RevokeMissionsForAircraft(Guid aircraftId, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// AZ-535 AC-4 — verifier-poll snapshot. Returns sessions revoked since
|
||||
/// <paramref name="since"/> whose <c>exp</c> is still in the future, so the
|
||||
/// list stays bounded.
|
||||
/// </summary>
|
||||
Task<IReadOnlyList<RevokedSession>> GetRevokedSince(DateTime since, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public sealed record RevokedSession(Guid Sid, DateTime Exp, DateTime RevokedAt, string? Reason);
|
||||
|
||||
public class SessionService(IDbFactory dbFactory) : ISessionService
|
||||
{
|
||||
public async Task<bool> RevokeBySid(Guid sessionId, Guid? byUserId, string reason, CancellationToken ct = default)
|
||||
{
|
||||
return await dbFactory.RunAdmin(async db =>
|
||||
{
|
||||
var existing = await db.Sessions.FirstOrDefaultAsync(s => s.Id == sessionId, token: ct);
|
||||
if (existing == null)
|
||||
throw new BusinessException(ExceptionEnum.SessionNotFound);
|
||||
|
||||
if (existing.RevokedAt.HasValue)
|
||||
return true; // idempotent — already revoked, no DB write needed
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
await db.Sessions
|
||||
.Where(s => s.Id == sessionId && s.RevokedAt == null)
|
||||
.Set(s => s.RevokedAt, now)
|
||||
.Set(s => s.RevokedReason, reason)
|
||||
.Set(s => s.RevokedByUserId, byUserId)
|
||||
.UpdateAsync(token: ct);
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<int> RevokeAllForUser(Guid userId, Guid? byUserId, string reason, CancellationToken ct = default) =>
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
return await db.Sessions
|
||||
.Where(s => s.UserId == userId && s.RevokedAt == null)
|
||||
.Set(s => s.RevokedAt, now)
|
||||
.Set(s => s.RevokedReason, reason)
|
||||
.Set(s => s.RevokedByUserId, byUserId)
|
||||
.UpdateAsync(token: ct);
|
||||
});
|
||||
|
||||
public async Task<int> RevokeMissionsForAircraft(Guid aircraftId, CancellationToken ct = default) =>
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
return await db.Sessions
|
||||
.Where(s => s.AircraftId == aircraftId
|
||||
&& s.Class == SessionClasses.Mission
|
||||
&& s.RevokedAt == null)
|
||||
.Set(s => s.RevokedAt, now)
|
||||
.Set(s => s.RevokedReason, SessionRevokedReasons.PostFlightReconnect)
|
||||
.UpdateAsync(token: ct);
|
||||
});
|
||||
|
||||
public async Task<IReadOnlyList<RevokedSession>> GetRevokedSince(DateTime since, CancellationToken ct = default)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
return await dbFactory.Run(async db =>
|
||||
(await db.Sessions
|
||||
.Where(s => s.RevokedAt != null
|
||||
&& s.RevokedAt > since
|
||||
&& s.ExpiresAt > now) // AZ-535 AC-4: prune expired
|
||||
.Select(s => new RevokedSession(s.Id, s.ExpiresAt, s.RevokedAt!.Value, s.RevokedReason))
|
||||
.ToListAsync(token: ct)));
|
||||
}
|
||||
}
|
||||
+244
-67
@@ -1,48 +1,121 @@
|
||||
using Azaion.Common;
|
||||
using System.Security.Cryptography;
|
||||
using Azaion.Common;
|
||||
using Azaion.Common.Configs;
|
||||
using Azaion.Common.Database;
|
||||
using Azaion.Common.Entities;
|
||||
using Azaion.Common.Extensions;
|
||||
using Azaion.Common.Requests;
|
||||
using LinqToDB;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Npgsql;
|
||||
|
||||
namespace Azaion.Services;
|
||||
|
||||
public interface IUserService
|
||||
{
|
||||
Task RegisterUser(RegisterUserRequest request, CancellationToken ct = default);
|
||||
Task<RegisterDeviceResponse> RegisterDevice(CancellationToken ct = default);
|
||||
Task<User> ValidateUser(LoginRequest request, CancellationToken ct = default);
|
||||
Task<User?> GetByEmail(string? email, CancellationToken ct = default);
|
||||
Task UpdateHardware(string email, string? hardware = null, CancellationToken ct = default);
|
||||
Task<User?> GetById(Guid userId, CancellationToken ct = default);
|
||||
Task UpdateQueueOffsets(string email, UserQueueOffsets queueOffsets, CancellationToken ct = default);
|
||||
Task<IEnumerable<User>> GetUsers(string? searchEmail, RoleEnum? searchRole, CancellationToken ct = default);
|
||||
Task<string> CheckHardwareHash(User user, string hardware, CancellationToken ct = default);
|
||||
Task ChangeRole(string email, RoleEnum newRole, CancellationToken ct = default);
|
||||
Task SetEnableStatus(string email, bool isEnabled, CancellationToken ct = default);
|
||||
Task RemoveUser(string email, CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// AZ-557 — shared failure-accounting path for MFA-side failures. Mirrors what the
|
||||
/// password-side path in <see cref="ValidateUser"/> does on a wrong-password event:
|
||||
/// records the appropriate audit row, increments <c>failed_login_count</c>,
|
||||
/// crosses-the-threshold trips <c>lockout_until</c>, and signals lockout by throwing
|
||||
/// <see cref="BusinessException"/> with <see cref="ExceptionEnum.InvalidCredentials"/>
|
||||
/// + <see cref="BusinessException.RetryAfterSeconds"/>. Callers (e.g.,
|
||||
/// <c>MfaService.VerifyForLogin</c>) MUST handle the throw branch and rethrow their
|
||||
/// own opaque error if the threshold was not crossed.
|
||||
/// </summary>
|
||||
Task RegisterMfaFailedLogin(User user, CancellationToken ct = default);
|
||||
}
|
||||
|
||||
public class UserService(IDbFactory dbFactory, ICache cache) : IUserService
|
||||
public class UserService(
|
||||
IDbFactory dbFactory,
|
||||
ICache cache,
|
||||
IAuditLog auditLog,
|
||||
IOptions<AuthConfig> authConfig) : IUserService
|
||||
{
|
||||
private readonly AuthConfig _auth = authConfig.Value;
|
||||
|
||||
private const string DeviceEmailPrefix = "azj-";
|
||||
private const string DeviceEmailDomain = "@azaion.com";
|
||||
private const int SerialNumberStart = 4; // index of NNNN inside "azj-NNNN..." (length of DeviceEmailPrefix)
|
||||
private const int SerialNumberLength = 4;
|
||||
private const int DevicePasswordBytes = 16; // hex-encoded → 32 chars
|
||||
|
||||
public async Task RegisterUser(RegisterUserRequest request, CancellationToken ct = default)
|
||||
{
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
try
|
||||
{
|
||||
var existingUser = await db.Users.FirstOrDefaultAsync(u => u.Email == request.Email, token: ct);
|
||||
if (existingUser != null)
|
||||
throw new BusinessException(ExceptionEnum.EmailExists);
|
||||
|
||||
await db.InsertAsync(new User
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Email = request.Email,
|
||||
PasswordHash = request.Password.ToHash(),
|
||||
Role = request.Role,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
IsEnabled = true
|
||||
}, token: ct);
|
||||
});
|
||||
await db.InsertAsync(new User
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Email = request.Email,
|
||||
PasswordHash = Security.HashPassword(request.Password),
|
||||
Role = request.Role,
|
||||
CreatedAt = DateTime.UtcNow,
|
||||
IsEnabled = true
|
||||
}, token: ct);
|
||||
});
|
||||
}
|
||||
catch (PostgresException ex) when (ex.SqlState == PostgresErrorCodes.UniqueViolation)
|
||||
{
|
||||
throw new BusinessException(ExceptionEnum.EmailExists);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<RegisterDeviceResponse> RegisterDevice(CancellationToken ct = default)
|
||||
{
|
||||
var (serial, email) = await NextDeviceIdentity(ct);
|
||||
var password = Convert.ToHexString(RandomNumberGenerator.GetBytes(DevicePasswordBytes)).ToLowerInvariant();
|
||||
|
||||
await RegisterUser(new RegisterUserRequest
|
||||
{
|
||||
Email = email,
|
||||
Password = password,
|
||||
Role = RoleEnum.CompanionPC
|
||||
}, ct);
|
||||
|
||||
return new RegisterDeviceResponse
|
||||
{
|
||||
Serial = serial,
|
||||
Email = email,
|
||||
Password = password
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<(string Serial, string Email)> NextDeviceIdentity(CancellationToken ct) =>
|
||||
await dbFactory.Run(async db =>
|
||||
{
|
||||
var lastEmail = await db.Users
|
||||
.Where(u => u.Role == RoleEnum.CompanionPC)
|
||||
.OrderByDescending(u => u.CreatedAt)
|
||||
.Select(u => u.Email)
|
||||
.FirstOrDefaultAsync(token: ct);
|
||||
|
||||
var nextNumber = 0;
|
||||
if (!string.IsNullOrEmpty(lastEmail) && lastEmail.Length >= SerialNumberStart + SerialNumberLength)
|
||||
{
|
||||
var serialPart = lastEmail.Substring(SerialNumberStart, SerialNumberLength);
|
||||
if (int.TryParse(serialPart, out var current))
|
||||
nextNumber = current + 1;
|
||||
}
|
||||
|
||||
var serial = $"{DeviceEmailPrefix}{nextNumber.ToString($"D{SerialNumberLength}")}";
|
||||
var email = $"{serial}{DeviceEmailDomain}";
|
||||
return (serial, email);
|
||||
});
|
||||
|
||||
public async Task<User?> GetByEmail(string? email, CancellationToken ct = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(email)) throw new ArgumentNullException(nameof(email));
|
||||
@@ -52,32 +125,165 @@ public class UserService(IDbFactory dbFactory, ICache cache) : IUserService
|
||||
await db.Users.FirstOrDefaultAsync(x => x.Email == email, ct)));
|
||||
}
|
||||
|
||||
|
||||
public async Task<User> ValidateUser(LoginRequest request, CancellationToken ct = default) =>
|
||||
await dbFactory.Run(async db =>
|
||||
{
|
||||
var user = await db.Users.FirstOrDefaultAsync(x => x.Email == request.Email, token: ct);
|
||||
if (user == null)
|
||||
throw new BusinessException(ExceptionEnum.NoEmailFound);
|
||||
|
||||
if (request.Password.ToHash() != user.PasswordHash)
|
||||
throw new BusinessException(ExceptionEnum.WrongPassword);
|
||||
|
||||
if (!user.IsEnabled)
|
||||
throw new BusinessException(ExceptionEnum.UserDisabled);
|
||||
|
||||
return user;
|
||||
});
|
||||
public async Task<User?> GetById(Guid userId, CancellationToken ct = default) =>
|
||||
await dbFactory.Run(async db => await db.Users.FirstOrDefaultAsync(x => x.Id == userId, token: ct));
|
||||
|
||||
|
||||
public async Task UpdateHardware(string email, string? hardware = null, CancellationToken ct = default)
|
||||
public async Task<User> ValidateUser(LoginRequest request, CancellationToken ct = default)
|
||||
{
|
||||
var user = await dbFactory.Run(async db =>
|
||||
await db.Users.FirstOrDefaultAsync(x => x.Email == request.Email, token: ct));
|
||||
|
||||
// AZ-556 — unknown email: equalize timing with a dummy Argon2id verify so a
|
||||
// wall-clock observer can't distinguish "no such email" from "wrong password".
|
||||
// No counter to increment (there is no row), so this path skips lockout
|
||||
// accounting entirely; the audit row preserves the attempted email for SecOps.
|
||||
if (user == null)
|
||||
{
|
||||
Security.VerifyDummy(request.Password);
|
||||
await auditLog.RecordLoginFailedUnknownEmail(request.Email, ct);
|
||||
throw new BusinessException(ExceptionEnum.InvalidCredentials);
|
||||
}
|
||||
|
||||
// AZ-537 AC-3 — active lockout takes precedence over the password check; even
|
||||
// a correct password is rejected until the lockout expires. AZ-556 collapses
|
||||
// the response code to `InvalidCredentials` while keeping the Retry-After
|
||||
// header so legitimate clients can self-throttle.
|
||||
if (user.LockoutUntil is { } until && until > DateTime.UtcNow)
|
||||
{
|
||||
var remaining = (int)Math.Ceiling((until - DateTime.UtcNow).TotalSeconds);
|
||||
throw new BusinessException(ExceptionEnum.InvalidCredentials, Math.Max(remaining, 1));
|
||||
}
|
||||
|
||||
// AZ-537 AC-2 — per-account sliding-window rate limit. Counts only failure
|
||||
// events in the recent window (login_failed + mfa_login_failed per AZ-557) so
|
||||
// legitimate retries after a success aren't punished.
|
||||
var recentFailures = await auditLog.CountRecentFailedLogins(
|
||||
user.Email, _auth.RateLimit.PerAccountWindowSeconds, ct);
|
||||
if (recentFailures >= _auth.RateLimit.PerAccountPermitLimit)
|
||||
throw new BusinessException(ExceptionEnum.InvalidCredentials, _auth.RateLimit.PerAccountWindowSeconds);
|
||||
|
||||
// AZ-556 F-AUTH-3 — disabled-account check moved BEFORE password verify. An
|
||||
// attacker who knows the password of a disabled account no longer learns that
|
||||
// fact via a distinct error code (or via the missing-Argon2id timing tell).
|
||||
// Still run the dummy verify so the wall-clock equalises against a real
|
||||
// wrong-password branch.
|
||||
if (!user.IsEnabled)
|
||||
{
|
||||
Security.VerifyDummy(request.Password);
|
||||
await auditLog.RecordLoginFailedDisabled(user.Email, ct);
|
||||
throw new BusinessException(ExceptionEnum.InvalidCredentials);
|
||||
}
|
||||
|
||||
var verify = Security.VerifyPassword(request.Password, user.PasswordHash);
|
||||
if (!verify.Valid)
|
||||
{
|
||||
// RegisterFailedLogin may itself throw InvalidCredentials + Retry-After
|
||||
// when the threshold trips; otherwise we fall through and throw the
|
||||
// non-Retry-After variant below.
|
||||
await RegisterFailedLogin(user, ct);
|
||||
throw new BusinessException(ExceptionEnum.InvalidCredentials);
|
||||
}
|
||||
|
||||
await RegisterSuccessfulLogin(user, request.Password, verify.NeedsRehash, ct);
|
||||
return user;
|
||||
}
|
||||
|
||||
// Lazy migration of legacy SHA-384 hashes (and future Argon2 param upgrades).
|
||||
// Conditional on the original hash to avoid clobbering a concurrent rehash from
|
||||
// a parallel login of the same account.
|
||||
private async Task RegisterSuccessfulLogin(User user, string plaintext, bool rehash, CancellationToken ct)
|
||||
{
|
||||
var newHash = rehash ? Security.HashPassword(plaintext) : null;
|
||||
var oldHash = user.PasswordHash;
|
||||
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
{
|
||||
await db.Users.UpdateAsync(x => x.Email == email,
|
||||
u => new User { Hardware = hardware }, token: ct);
|
||||
if (newHash != null)
|
||||
{
|
||||
await db.Users.UpdateAsync(
|
||||
u => u.Id == user.Id && u.PasswordHash == oldHash,
|
||||
u => new User
|
||||
{
|
||||
PasswordHash = newHash,
|
||||
FailedLoginCount = 0,
|
||||
LockoutUntil = null
|
||||
},
|
||||
token: ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
await db.Users.UpdateAsync(
|
||||
u => u.Id == user.Id,
|
||||
u => new User
|
||||
{
|
||||
FailedLoginCount = 0,
|
||||
LockoutUntil = null
|
||||
},
|
||||
token: ct);
|
||||
}
|
||||
});
|
||||
cache.Invalidate(User.GetCacheKey(email));
|
||||
|
||||
if (newHash != null)
|
||||
user.PasswordHash = newHash;
|
||||
user.FailedLoginCount = 0;
|
||||
user.LockoutUntil = null;
|
||||
cache.Invalidate(User.GetCacheKey(user.Email));
|
||||
|
||||
await auditLog.RecordLoginSuccess(user.Email, ct);
|
||||
}
|
||||
|
||||
private Task RegisterFailedLogin(User user, CancellationToken ct) =>
|
||||
RegisterFailedLoginCore(user, FailureKind.Password, ct);
|
||||
|
||||
public Task RegisterMfaFailedLogin(User user, CancellationToken ct = default) =>
|
||||
RegisterFailedLoginCore(user, FailureKind.Mfa, ct);
|
||||
|
||||
// AZ-557 — single accounting path shared by the password-side (`ValidateUser`) and
|
||||
// the MFA-side (`MfaService.VerifyForLogin`) failure branches. The audit row type
|
||||
// diverges (`login_failed` vs `mfa_login_failed`) so SecOps can analyse the two
|
||||
// categories separately, but the counter / lockout / Retry-After semantics are
|
||||
// identical. On lockout-trip we throw `InvalidCredentials` + Retry-After so the
|
||||
// caller can rethrow its opaque wire response without losing the cooldown hint.
|
||||
private async Task RegisterFailedLoginCore(User user, FailureKind kind, CancellationToken ct)
|
||||
{
|
||||
if (kind == FailureKind.Password)
|
||||
await auditLog.RecordLoginFailed(user.Email, ct);
|
||||
else
|
||||
await auditLog.RecordMfaLoginFailed(user.Email, ct);
|
||||
|
||||
var newCount = user.FailedLoginCount + 1;
|
||||
var triggersLock = newCount >= _auth.Lockout.MaxAttempts;
|
||||
DateTime? newLockoutUntil = triggersLock
|
||||
? DateTime.UtcNow.AddSeconds(_auth.Lockout.DurationSeconds)
|
||||
: user.LockoutUntil;
|
||||
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
await db.Users.UpdateAsync(
|
||||
u => u.Id == user.Id,
|
||||
u => new User
|
||||
{
|
||||
FailedLoginCount = newCount,
|
||||
LockoutUntil = newLockoutUntil
|
||||
},
|
||||
token: ct));
|
||||
|
||||
cache.Invalidate(User.GetCacheKey(user.Email));
|
||||
|
||||
if (triggersLock)
|
||||
{
|
||||
await auditLog.RecordLoginLockout(user.Email, ct);
|
||||
// AZ-556 — promote a threshold-crossing failure into the unified lockout
|
||||
// response. The caller sees `InvalidCredentials` + Retry-After regardless
|
||||
// of whether the threshold was crossed by a password or an MFA attempt.
|
||||
throw new BusinessException(ExceptionEnum.InvalidCredentials, _auth.Lockout.DurationSeconds);
|
||||
}
|
||||
}
|
||||
|
||||
private enum FailureKind
|
||||
{
|
||||
Password,
|
||||
Mfa,
|
||||
}
|
||||
|
||||
public async Task UpdateQueueOffsets(string email, UserQueueOffsets queueOffsets, CancellationToken ct = default)
|
||||
@@ -106,35 +312,6 @@ public class UserService(IDbFactory dbFactory, ICache cache) : IUserService
|
||||
u => u.Role == searchRole)
|
||||
.ToListAsync(token: ct));
|
||||
|
||||
public async Task<string> CheckHardwareHash(User user, string hardware, CancellationToken ct = default)
|
||||
{
|
||||
var requestHWHash = Security.GetHWHash(hardware);
|
||||
|
||||
//For the new users Hardware would be empty, fill it with actual hardware on the very first request
|
||||
if (string.IsNullOrEmpty(user.Hardware))
|
||||
{
|
||||
await UpdateHardware(user.Email, hardware, ct);
|
||||
cache.Invalidate(User.GetCacheKey(user.Email));
|
||||
await UpdateLastLoginDate(user, ct);
|
||||
return requestHWHash;
|
||||
}
|
||||
|
||||
var userHWHash = Security.GetHWHash(user.Hardware);
|
||||
if (userHWHash != requestHWHash)
|
||||
throw new BusinessException(ExceptionEnum.HardwareIdMismatch);
|
||||
await UpdateLastLoginDate(user, ct);
|
||||
return userHWHash;
|
||||
}
|
||||
|
||||
private async Task UpdateLastLoginDate(User user, CancellationToken ct = default)
|
||||
{
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
await db.Users.UpdateAsync(x => x.Email == user.Email, u => new User
|
||||
{
|
||||
LastLogin = DateTime.UtcNow
|
||||
}, ct));
|
||||
}
|
||||
|
||||
public async Task ChangeRole(string email, RoleEnum newRole, CancellationToken ct = default)
|
||||
{
|
||||
await dbFactory.RunAdmin(async db =>
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FluentAssertions" Version="6.12.2" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
|
||||
<PackageReference Include="xunit" Version="2.9.2" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Azaion.Services\Azaion.Services.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user