mirror of
https://github.com/azaion/satellite-provider.git
synced 2026-06-22 21:21:15 +00:00
Compare commits
106 Commits
098f905796
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| 62d6b8310a | |||
| 32bc5c1e48 | |||
| 8fca6e0209 | |||
| ac40a8b352 | |||
| 6207ab7c27 | |||
| ec0eb909a1 | |||
| b763da3f24 | |||
| bbe87835a9 | |||
| 490902c80a | |||
| 5e056b2334 | |||
| 34ee1e0b83 | |||
| fcd494f67e | |||
| 0810a89ef1 | |||
| 06d160daf0 | |||
| 8c13cd4f30 | |||
| a49f6c941b | |||
| 30d99e09ad | |||
| bc04ba7f99 | |||
| 865dfdb3b9 | |||
| dceaddc436 | |||
| 7d3ba1c3fd | |||
| 19c0371fd6 | |||
| af661359c7 | |||
| ba3bdb1918 | |||
| 5d84d2839e | |||
| c74a2339aa | |||
| da40534b49 | |||
| 909f69cb3a | |||
| 3c7cd4e56b | |||
| aa1a1bf19f | |||
| ea278afb37 | |||
| 0e05fc519a | |||
| 61612044fb | |||
| c646aa93e2 | |||
| f6197499a4 | |||
| ab437a15df | |||
| 8e509b550c | |||
| e31f59211d | |||
| af4219fce6 | |||
| de609cffa1 | |||
| 813136326f | |||
| c0f004d2c9 | |||
| ca0ca9f2a4 | |||
| 65cdfae970 | |||
| 314d1dec39 | |||
| e42bf62152 | |||
| 495605f51b | |||
| f979e18811 | |||
| 080441db5d | |||
| 745f4840e6 | |||
| c396740644 | |||
| 9cfd80babe | |||
| 76076cbd90 | |||
| b69cf5640e | |||
| e9f4e84adb | |||
| cbbb26bd28 | |||
| 5214a4a647 | |||
| e3cd388577 | |||
| 98cdcd17c1 | |||
| dc3dabe7bd | |||
| 1802d32107 | |||
| 11b7074485 | |||
| f64d0d760a | |||
| 753be43d11 | |||
| 96cd3c4495 | |||
| 8e15e53782 | |||
| 42a3cc7467 | |||
| 18609656f9 | |||
| 51b572108a | |||
| e9d6db077c | |||
| 687d6bdd5b | |||
| 5ba58b6c8d | |||
| 08451df027 | |||
| 9a53bff92e | |||
| 6099d1c86b | |||
| 534ab41b8e | |||
| 68359350fc | |||
| 8fee955bb5 | |||
| a7c622204f | |||
| fae0d1cc34 | |||
| 7736cfd761 | |||
| 89b4bfd245 | |||
| 1ca8c80d7b | |||
| 7c37636fdf | |||
| 45f7852fb2 | |||
| 23ab05766d | |||
| 6d98c8f8d1 | |||
| aa8beaa684 | |||
| 4456542cec | |||
| 1dcd089d39 | |||
| ee42b1716b | |||
| ea1ca714f6 | |||
| 6f23120c49 | |||
| 70a0a2c4d5 | |||
| 3603dd319c | |||
| 10d31b4c1c | |||
| 23d513b24c | |||
| 7729cee2d3 | |||
| c98f6fde48 | |||
| 1b62b3268a | |||
| bcb9bf5130 | |||
| f7ad7aa5ab | |||
| d327000fb6 | |||
| d2d9f6352b | |||
| 4c88201e5c | |||
| 89260d0ec4 |
+136
-72
@@ -11,10 +11,20 @@ If you want to run a specific skill directly (without the orchestrator), use the
|
||||
```
|
||||
/problem — interactive problem gathering → _docs/00_problem/
|
||||
/research — solution drafts → _docs/01_solution/
|
||||
/plan — architecture, components, tests → _docs/02_document/
|
||||
/decompose — atomic task specs → _docs/02_tasks/todo/
|
||||
/implement — batched parallel implementation → _docs/03_implementation/
|
||||
/deploy — containerization, CI/CD, observability → _docs/04_deploy/
|
||||
/plan — architecture, ADRs, components, tests, epics → _docs/02_document/
|
||||
/test-spec — blackbox/perf/resilience/security test specs → _docs/02_document/tests/
|
||||
/decompose — atomic task specs (multi-mode) → _docs/02_tasks/todo/
|
||||
/implement — sequential dependency-aware batches with code review and completeness gates → _docs/03_implementation/
|
||||
/test-run — runs the test suite (functional / perf modes) with gating
|
||||
/code-review — multi-phase review used by /implement
|
||||
/refactor — 8-phase structured refactoring (incl. testability sub-mode) → _docs/04_refactoring/
|
||||
/security — OWASP-driven audit → _docs/05_security/
|
||||
/deploy — containerization, CI/CD, environments, observability, procedures, scripts → _docs/04_deploy/
|
||||
/release — execute deploy artifacts in prod, smoke-test, watch, decide rollback → _docs/04_release/
|
||||
/document — bottom-up reverse-engineering of an existing codebase → _docs/02_document/
|
||||
/new-task — interactive feature planning for an existing codebase → _docs/02_tasks/todo/
|
||||
/ui-design — HTML+CSS mockups + design system → _docs/02_document/ui_mockups/
|
||||
/retrospective — metrics + lessons log → _docs/06_metrics/ + _docs/LESSONS.md
|
||||
```
|
||||
|
||||
## How It Works
|
||||
@@ -41,148 +51,201 @@ The state file tracks completed steps, key decisions, blockers, and session cont
|
||||
|
||||
Skills auto-chain without pausing between them. The only pauses are:
|
||||
- **BLOCKING gates** inside each skill (user must confirm before proceeding)
|
||||
- **Session boundary** after decompose (suggests new conversation before implement)
|
||||
- **Session boundaries** declared in each flow's auto-chain rules (e.g., after `decompose`, after `decompose tests`) — suggested new-conversation breakpoints to keep context fresh
|
||||
|
||||
A typical project runs in 2-4 conversations:
|
||||
- Session 1: Problem → Research → Research decision
|
||||
- Session 2: Plan → Decompose
|
||||
- Session 3: Implement (may span multiple sessions)
|
||||
- Session 4: Deploy
|
||||
There are three flows, resolved on every invocation (see `skills/autodev/SKILL.md` § Flow Resolution):
|
||||
|
||||
Re-entry is seamless: type `/autodev` in a new conversation and the orchestrator reads the state file to pick up exactly where you left off.
|
||||
| Flow | When | Steps |
|
||||
|------|------|-------|
|
||||
| **greenfield** | empty workspace, no source yet | 17 steps: Problem → Research → Plan → UI Design → Test Spec → Decompose → Implement → Code Testability Revision → Decompose Tests → Implement Tests → Run Tests → Test-Spec Sync → Update Docs → Security Audit (opt) → Performance Test (opt) → Deploy → Release → Retrospective |
|
||||
| **existing-code** | source files present | one-time baseline (Document → Architecture Baseline Scan → Test Spec → Code Testability Revision → Decompose Tests → Implement Tests → Run Tests → optional Refactor) then a feature-cycle loop (New Task → Implement → Run Tests → Test-Spec Sync → Update Docs → Security Audit (opt) → Performance Test (opt) → Deploy → Release → Retrospective → loops back to New Task) |
|
||||
| **meta-repo** | `.gitmodules`, workspace manifest, or multi-component aggregator | uses `monorepo-*` skills + `_docs/_repo-config.yaml` instead of per-component BUILD-SHIP folders |
|
||||
|
||||
A typical greenfield project spans several conversations because of session boundaries. Re-entry is seamless: type `/autodev` in a new conversation and the orchestrator reads `_docs/_autodev_state.md` to pick up exactly where you left off.
|
||||
|
||||
## Skill Descriptions
|
||||
|
||||
### autodev (meta-orchestrator)
|
||||
|
||||
Auto-chaining engine that sequences the full BUILD → SHIP workflow. Persists state to `_docs/_autodev_state.md`, tracks key decisions and session context, and flows through problem → research → plan → decompose → implement → deploy without manual skill invocation. Maximizes work per conversation with seamless cross-session re-entry.
|
||||
Auto-chaining engine that sequences the full BUILD → SHIP → EVOLVE workflow. Persists state to `_docs/_autodev_state.md`, surfaces top-3 lessons from `_docs/LESSONS.md` at every invocation, replays any `_docs/_process_leftovers/` entries, tracks key decisions and session context, and flows through the active flow's steps without manual skill invocation. Maximizes work per conversation with seamless cross-session re-entry.
|
||||
|
||||
### problem
|
||||
|
||||
Interactive interview that builds `_docs/00_problem/`. Asks probing questions across 8 dimensions (problem, scope, hardware, software, acceptance criteria, input data, security, operations) until all required files can be written with concrete, measurable content.
|
||||
Interactive 4-phase interview that builds `_docs/00_problem/`. Asks probing questions across 8 dimensions (problem & goals, scope, hardware & environment, software & tech, acceptance criteria, input data, security, operational) until all required files can be written with concrete, measurable, quantifiable content. Acceptance criteria must include numeric targets; input data must include `expected_results/` mappings.
|
||||
|
||||
### research
|
||||
|
||||
8-step deep research methodology. Mode A produces initial solution drafts. Mode B assesses and revises existing drafts. Includes AC assessment, source tiering, fact extraction, comparison frameworks, and validation. Run multiple rounds until the solution is solid.
|
||||
8-step deep research methodology. Mode A produces initial solution drafts. Mode B assesses and revises existing drafts. Classifies output as **Technical-component selection** (full per-mode API verification gates apply) or **Non-technical investigation** (gates relaxed). Source tiering, fact extraction, comparison frameworks, validation, exact-fit component selection. Run multiple rounds until the solution is solid.
|
||||
|
||||
### plan
|
||||
|
||||
6-step planning workflow. Produces integration test specs, architecture, system flows, data model, deployment plan, component specs with interfaces, risk assessment, test specifications, and work item epics. Heavy interaction at BLOCKING gates.
|
||||
6-step planning workflow with one half-step (4.5: Architecture Decision Records). Produces blackbox test specs (delegated to test-spec), glossary, architecture vision, architecture document, data model, deployment plan, component specs with interfaces, risk assessment, ADRs, test specifications, and work item epics. Heavy interaction at BLOCKING gates (glossary+vision, architecture, components, mitigations, ADRs).
|
||||
|
||||
### test-spec
|
||||
|
||||
4-phase test specification workflow. Phase 1 analyzes input data + expected-results completeness. Phase 2 emits 8 test artifacts (environment, test-data, blackbox, performance, resilience, security, resource-limit, traceability matrix). Phase 3 is the hard gate that requires every test to have quantifiable expected results. Phase 4 emits runner scripts. Cycle-update mode for incremental refresh.
|
||||
|
||||
### decompose
|
||||
|
||||
4-step task decomposition. Produces a bootstrap structure plan, atomic task specs per component, integration test tasks, and a cross-task dependency table. Each task gets a work item ticket and is capped at 8 complexity points.
|
||||
Multi-mode task decomposition with 6 internal step files. Implementation mode runs Step 1 (Bootstrap), 1.5 (Module Layout), 1.7 (System-Pipeline owner tasks), 2 (per-component tasks), 4 (Cross-Verification). Tests-only mode runs Step 1t (Test Infrastructure), 3 (Blackbox tasks), 4. Single-component mode runs Step 2 only. Each task is tracker-prefixed and capped at 5 complexity points. The 1.7 step exists specifically to prevent the GPS-passthrough class of failure (see `meta-rule.mdc`).
|
||||
|
||||
### implement
|
||||
|
||||
Orchestrator that reads task specs, computes dependency-aware execution batches, launches up to 4 parallel implementer subagents, runs code review after each batch, and commits per batch. Does not write code itself.
|
||||
|
||||
### deploy
|
||||
|
||||
7-step deployment planning. Status check, containerization, CI/CD pipeline, environment strategy, observability, deployment procedures, and deployment scripts. Produces documents for steps 1-6 and executable scripts in step 7.
|
||||
Orchestrator that reads task specs, computes dependency-aware execution batches via topological sort, **implements tasks sequentially within each batch** (no subagents, no parallel execution — see `.cursor/rules/no-subagents.mdc`), runs code review after each batch, runs cumulative code review every K batches, and commits per batch. Has a Product Implementation Completeness Gate (Step 15) that compares promises in task specs / architecture against actual production code, plus a System-Pipeline Audit (Step 15.b) that walks architecture-named pipelines and verifies a real production caller wires each adjacent component pair. Either gate's FAIL stops the cycle until remediation tasks are created.
|
||||
|
||||
### code-review
|
||||
|
||||
Multi-phase code review against task specs. Produces structured findings with verdict: PASS, FAIL, or PASS_WITH_WARNINGS.
|
||||
7-phase code review against task specs (Phase 7 is Architecture Compliance against `module-layout.md` and `architecture.md`). Produces structured findings with verdict: PASS, PASS_WITH_WARNINGS, or FAIL. Three modes: full (per batch), baseline (one-time architecture scan of an existing codebase), cumulative (mid-implementation across batches with `## Baseline Delta`).
|
||||
|
||||
### test-run
|
||||
|
||||
Runs the test suite. Functional mode (default): detects pytest/dotnet/cargo/npm or `scripts/run-tests.sh`, applies a System-Under-Test Reality Gate to refuse passes where internal product modules were stubbed, classifies failures and skips, gates on outcome. Perf mode: detects `scripts/run-performance-tests.sh` or k6/locust/artillery/wrk, captures latency/throughput/error metrics, compares against thresholds.
|
||||
|
||||
### refactor
|
||||
|
||||
6-phase structured refactoring: baseline, discovery, analysis, safety net, execution, hardening.
|
||||
8-phase structured refactoring: baseline → discovery → analysis → safety net → execution → test sync → verification → documentation. Two input modes (Automatic / Guided). Testability sub-mode skips Phase 3 by design and emits a `testability_changes_summary.md` for user review. Each run lives in its own `RUN_DIR` under `_docs/04_refactoring/NN-<run-name>/`.
|
||||
|
||||
### security
|
||||
|
||||
OWASP-based security testing and audit.
|
||||
5-phase OWASP-based audit: dependency scan → static analysis → OWASP Top 10 review → infrastructure review → consolidated security report. Severity-ranked, evidence-based, actionable. Complementary to `code-review` Phase 4 (lightweight security quick-scan).
|
||||
|
||||
### deploy
|
||||
|
||||
7-step deployment planning. Produces documents for steps 1–6 (status & env, containerization, CI/CD pipeline, environment strategy, observability, deployment procedures) and executable scripts in step 7 (`deploy.sh`, `pull-images.sh`, `start-services.sh`, `stop-services.sh`, `health-check.sh`).
|
||||
|
||||
### release
|
||||
|
||||
Executes the deployment plan produced by `/deploy` against a target environment. 6 phases: pre-release gate (AC + risk + rollback readiness), strategy select (all-at-once / blue-green / canary / manual), execute (run scripts, monitor exit codes), smoke test (delegate to test-run prod-smoke), watch window (read observability for the configured duration), commit-or-rollback. Outputs `_docs/04_release/release_<version>.md`. Produces a definitive Released / Rolled-Back / Aborted verdict; failure of any phase auto-triggers rollback unless the user opts to investigate.
|
||||
|
||||
### retrospective
|
||||
|
||||
Collects metrics from implementation batch reports, analyzes trends, produces improvement reports.
|
||||
4-step workflow: collect metrics → analyze trends → produce report → update lessons log (`_docs/LESSONS.md`, ring buffer of last 15 entries consumed by `new-task`, `plan`, `decompose`, and `autodev`). Cycle-end (default) and incident modes; incident mode is auto-invoked after a 3-strike failure.
|
||||
|
||||
### document
|
||||
|
||||
Bottom-up codebase documentation. Analyzes existing code from modules through components to architecture, then retrospectively derives problem/restrictions/acceptance criteria. Alternative entry point for existing codebases — produces the same `_docs/` artifacts as problem + plan, but from code analysis instead of user interview.
|
||||
Bottom-up codebase documentation. Analyzes existing code from modules through components to architecture, then retrospectively derives problem/restrictions/acceptance criteria. Alternative entry point for existing codebases — produces the same `_docs/` artifacts as problem + plan, but from code analysis instead of user interview. Two workflow files: `workflows/full.md` (full / focus-area / resume) and `workflows/task.md` (incremental update for a single task).
|
||||
|
||||
### new-task
|
||||
|
||||
Existing-code feature planning loop. Walks the user through Step 1 (description) → Step 2 (complexity assessment, consults `LESSONS.md`) → Step 3 (research if needed) → Step 4 (codebase analysis incl. test-coverage gap) → Step 4.5 (contract & layout check) → Step 5 (validate assumptions) → Step 6 (write task spec) → Step 7 (tracker ticket) → Step 8 (loop or finalize).
|
||||
|
||||
### ui-design
|
||||
|
||||
End-to-end UI workflow. Phase 0 (complexity detection: full vs quick) → Phase 1 (context check) → Phase 2 (requirements) → Phase 3 (direction exploration) → Phase 4 (design system synthesis: `DESIGN.md`) → Phase 5 (HTML+Tailwind code generation) → Phase 6 (visual verification, optional MCP enhancements) → Phase 7 (user review) → Phase 8 (iteration). Has Applicability Check that refuses to run on non-UI projects.
|
||||
|
||||
### monorepo-* (suite-level)
|
||||
|
||||
Six skills for meta-repos: `monorepo-discover` (write/refresh `_docs/_repo-config.yaml`), `monorepo-document` (sync unified docs), `monorepo-cicd` (sync CI/compose/env templates), `monorepo-onboard` (atomic add-component), `monorepo-status` (read-only drift report), `monorepo-e2e` (sync suite-level integration harness). They never cross domains; each touches exactly one artifact class.
|
||||
|
||||
## Developer TODO (Project Mode)
|
||||
|
||||
### BUILD
|
||||
The numbered list below mirrors greenfield-flow ordering. Existing-code projects start at `/document`, then enter the feature-cycle loop at `/new-task`. See `skills/autodev/flows/{greenfield,existing-code,meta-repo}.md` for the authoritative step tables.
|
||||
|
||||
### BUILD (greenfield)
|
||||
|
||||
```
|
||||
0. /problem — interactive interview → _docs/00_problem/
|
||||
- problem.md (required)
|
||||
- restrictions.md (required)
|
||||
- acceptance_criteria.md (required)
|
||||
- input_data/ (required)
|
||||
- security_approach.md (optional)
|
||||
|
||||
1. /research — solution drafts → _docs/01_solution/
|
||||
Run multiple times: Mode A → draft, Mode B → assess & revise
|
||||
|
||||
2. /plan — architecture, data model, deployment, components, risks, tests, epics → _docs/02_document/
|
||||
|
||||
3. /decompose — atomic task specs + dependency table → _docs/02_tasks/todo/
|
||||
|
||||
4. /implement — batched parallel agents, code review, commit per batch → _docs/03_implementation/
|
||||
1. /problem — interactive 4-phase interview → _docs/00_problem/
|
||||
required: problem.md, restrictions.md, acceptance_criteria.md, input_data/
|
||||
optional: security_approach.md
|
||||
2. /research — solution drafts (Mode A draft, Mode B assess) → _docs/01_solution/
|
||||
3. /plan — glossary, architecture vision, architecture, data model, deployment, components,
|
||||
risks, ADRs (Step 4.5), test specs, epics → _docs/02_document/
|
||||
(Step 1 invokes /test-spec internally)
|
||||
4. /ui-design — HTML+Tailwind mockups (UI projects only) → _docs/02_document/ui_mockups/
|
||||
5. /test-spec — produces 8 test-spec artifacts + traceability matrix → _docs/02_document/tests/
|
||||
(already invoked from /plan Step 1; Step 5 here is the explicit autodev step)
|
||||
6. /decompose — implementation tasks + module-layout + system-pipeline owner tasks →
|
||||
_docs/02_tasks/todo/
|
||||
7. /implement — sequential dependency-aware batches; per-batch code-review;
|
||||
Product Completeness Gate + System-Pipeline Audit → _docs/03_implementation/
|
||||
8. (auto) Code Testability Revision — surgical refactor to make code runnable under tests
|
||||
9. /decompose tests — test-only decomposition mode → _docs/02_tasks/todo/
|
||||
10. /implement (tests) — implements test tasks
|
||||
11. /test-run — full functional suite gate
|
||||
12. /test-spec --cycle-update — append implementation-learned scenarios
|
||||
13. /document --task — update affected component / module / architecture docs
|
||||
14. /security — OWASP-based audit (optional gate)
|
||||
15. /test-run --perf — perf/load tests (optional gate)
|
||||
```
|
||||
|
||||
### SHIP
|
||||
|
||||
```
|
||||
5. /deploy — containerization, CI/CD, environments, observability, procedures → _docs/04_deploy/
|
||||
16. /deploy — containerization, CI/CD, environments, observability, procedures, scripts → _docs/04_deploy/
|
||||
17. /release — execute deploy artifacts in prod, smoke-test, watch, decide rollback → _docs/04_release/
|
||||
```
|
||||
|
||||
### EVOLVE
|
||||
|
||||
```
|
||||
6. /refactor — structured refactoring → _docs/04_refactoring/
|
||||
7. /retrospective — metrics, trends, improvement actions → _docs/06_metrics/
|
||||
18. /retrospective — metrics + trends + lessons-log update → _docs/06_metrics/ + _docs/LESSONS.md
|
||||
(cycle-end mode after release; incident mode auto-fires after 3-strike failure)
|
||||
|
||||
After greenfield completes, the state file is rewritten to point at the existing-code flow's
|
||||
feature-cycle loop, which begins with /new-task and ends with /retrospective. The loop runs once
|
||||
per feature with state.cycle incremented.
|
||||
|
||||
Off-cycle:
|
||||
/refactor — full 8-phase refactor → _docs/04_refactoring/NN-<run-name>/
|
||||
/document — full reverse-engineering of an unfamiliar codebase
|
||||
```
|
||||
|
||||
Or just use `/autodev` to run steps 0-5 automatically.
|
||||
Or just use `/autodev` to run all the above automatically — the orchestrator chooses the right flow, sequences steps, surfaces lessons, processes leftovers, and pauses only at BLOCKING gates and declared session boundaries.
|
||||
|
||||
## Available Skills
|
||||
|
||||
| Skill | Triggers | Output |
|
||||
|-------|----------|--------|
|
||||
| **autodev** | "autodev", "auto", "start", "continue", "what's next" | Orchestrates full workflow |
|
||||
| **autodev** | "autodev", "auto", "start", "continue", "what's next" | Orchestrates full workflow (3 flows) |
|
||||
| **problem** | "problem", "define problem", "new project" | `_docs/00_problem/` |
|
||||
| **research** | "research", "investigate" | `_docs/01_solution/` |
|
||||
| **plan** | "plan", "decompose solution" | `_docs/02_document/` |
|
||||
| **plan** | "plan", "decompose solution" | `_docs/02_document/` (incl. ADRs) |
|
||||
| **test-spec** | "test spec", "blackbox tests", "test scenarios" | `_docs/02_document/tests/` + `scripts/` |
|
||||
| **decompose** | "decompose", "task decomposition" | `_docs/02_tasks/todo/` |
|
||||
| **implement** | "implement", "start implementation" | `_docs/03_implementation/` |
|
||||
| **test-run** | "run tests", "test suite", "verify tests" | Test results + verdict |
|
||||
| **code-review** | "code review", "review code" | Verdict: PASS / FAIL / PASS_WITH_WARNINGS |
|
||||
| **decompose** | "decompose", "task decomposition", "decompose tests" | `_docs/02_tasks/todo/` + `_docs/02_document/module-layout.md` |
|
||||
| **implement** | "implement", "start implementation" | `_docs/03_implementation/` (sequential — see `no-subagents.mdc`) |
|
||||
| **test-run** | "run tests", "test suite", "verify tests", "perf test" | Test results + verdict |
|
||||
| **code-review** | "code review", "review code" | Verdict: PASS / FAIL / PASS_WITH_WARNINGS (7 phases) |
|
||||
| **new-task** | "new task", "add feature", "new functionality" | `_docs/02_tasks/todo/` |
|
||||
| **ui-design** | "design a UI", "mockup", "design system" | `_docs/02_document/ui_mockups/` |
|
||||
| **refactor** | "refactor", "improve code" | `_docs/04_refactoring/` |
|
||||
| **security** | "security audit", "OWASP" | `_docs/05_security/` |
|
||||
| **refactor** | "refactor", "improve code", "testability" | `_docs/04_refactoring/NN-<run-name>/` |
|
||||
| **security** | "security audit", "OWASP", "vulnerability scan" | `_docs/05_security/` |
|
||||
| **document** | "document", "document codebase", "reverse-engineer docs" | `_docs/02_document/` + `_docs/00_problem/` + `_docs/01_solution/` |
|
||||
| **deploy** | "deploy", "CI/CD", "observability" | `_docs/04_deploy/` |
|
||||
| **retrospective** | "retrospective", "retro" | `_docs/06_metrics/` |
|
||||
| **deploy** | "deploy", "CI/CD", "observability", "containerize" | `_docs/04_deploy/` (plans + scripts) |
|
||||
| **release** | "release", "ship", "go live", "rollback" | `_docs/04_release/` (executed deploy + verdict) |
|
||||
| **retrospective** | "retrospective", "retro", "metrics review" | `_docs/06_metrics/` + `_docs/LESSONS.md` |
|
||||
| **monorepo-discover** | "discover monorepo", "scan submodules" | `_docs/_repo-config.yaml` |
|
||||
| **monorepo-document** | "sync monorepo docs" | unified `_docs/*.md` |
|
||||
| **monorepo-cicd** | "sync compose", "sync ci" | suite-level CI/compose/env templates |
|
||||
| **monorepo-onboard** | "onboard component", "register submodule" | atomic component addition |
|
||||
| **monorepo-status** | "monorepo status", "drift report" | read-only drift report |
|
||||
| **monorepo-e2e** | "suite e2e", "integration harness" | `e2e/docker-compose.suite-e2e.yml` and fixtures |
|
||||
|
||||
## Tools
|
||||
|
||||
| Tool | Type | Purpose |
|
||||
|------|------|---------|
|
||||
| `implementer` | Subagent | Implements a single task. Launched by `/implement`. |
|
||||
> The `.cursor/agents/` directory is intentionally empty. Per `.cursor/rules/no-subagents.mdc` the main agent does not delegate to subagents in this workspace; `/implement` runs tasks sequentially.
|
||||
|
||||
## Project Folder Structure
|
||||
|
||||
```
|
||||
_project.md — project-specific config (tracker type, project key, etc.)
|
||||
_docs/
|
||||
├── _autodev_state.md — autodev orchestrator state (progress, decisions, session context)
|
||||
├── 00_problem/ — problem definition, restrictions, AC, input data
|
||||
├── _autodev_state.md — autodev orchestrator state (≤30 lines; pointer only)
|
||||
├── _process_leftovers/ — deferred tracker writes replayed at next /autodev (per tracker.mdc)
|
||||
├── _repo-config.yaml — meta-repo only; produced by monorepo-discover
|
||||
├── LESSONS.md — ring buffer of last 15 actionable lessons (consumed by autodev/new-task/plan/decompose)
|
||||
├── 00_problem/ — problem definition, restrictions, AC, input data + expected_results/
|
||||
├── 00_research/ — intermediate research artifacts
|
||||
├── 01_solution/ — solution drafts, tech stack, security analysis
|
||||
├── 02_document/
|
||||
│ ├── architecture.md
|
||||
│ ├── architecture.md — includes ## Architecture Vision (user-confirmed)
|
||||
│ ├── glossary.md — user-confirmed terminology
|
||||
│ ├── system-flows.md
|
||||
│ ├── data_model.md
|
||||
│ ├── module-layout.md — per-component Owns/Imports-from/Public API (decompose Step 1.5)
|
||||
│ ├── architecture_compliance_baseline.md — existing-code baseline scan output
|
||||
│ ├── risk_mitigations.md
|
||||
│ ├── adr/[NNN]_[decision_slug].md — Architectural Decision Records (plan Step 4.5)
|
||||
│ ├── components/[##]_[name]/ — description.md + tests.md per component
|
||||
│ ├── contracts/<component>/<name>.md — versioned public-API contracts
|
||||
│ ├── common-helpers/
|
||||
│ ├── tests/ — environment, test data, blackbox, performance, resilience, security, traceability
|
||||
│ ├── deployment/ — containerization, CI/CD, environments, observability, procedures
|
||||
│ ├── tests/ — environment, test-data, blackbox, performance, resilience, security, resource-limit, traceability matrix
|
||||
│ ├── ui_mockups/ — HTML+CSS mockups, DESIGN.md (ui-design skill)
|
||||
│ ├── diagrams/
|
||||
│ └── FINAL_report.md
|
||||
@@ -192,12 +255,13 @@ _docs/
|
||||
│ ├── backlog/ — parked tasks (not scheduled yet)
|
||||
│ └── done/ — completed/archived tasks
|
||||
├── 02_task_plans/ — per-task research artifacts (new-task skill)
|
||||
├── 03_implementation/ — batch reports, implementation_report_*.md
|
||||
├── 03_implementation/ — batch_*_cycle*.md, implementation_report_*.md, implementation_completeness_cycle*.md, cumulative_review_*.md
|
||||
│ └── reviews/ — code review reports per batch
|
||||
├── 04_deploy/ — containerization, CI/CD, environments, observability, procedures, scripts
|
||||
├── 04_refactoring/ — baseline, discovery, analysis, execution, hardening
|
||||
├── 05_security/ — dependency scan, SAST, OWASP review, security report
|
||||
└── 06_metrics/ — retro_[YYYY-MM-DD].md
|
||||
├── 04_deploy/ — containerization, CI/CD, environments, observability, procedures, deploy_scripts.md, reports/
|
||||
├── 04_refactoring/NN-<run-name>/ — baseline_metrics, discovery, analysis, test_specs, execution_log, test_sync, verification, FINAL_report (one folder per refactor run)
|
||||
├── 04_release/ — release_<version>.md (one per /release invocation), rollback_<version>.md
|
||||
├── 05_security/ — dependency_scan, static_analysis, owasp_review, infrastructure_review, security_report
|
||||
└── 06_metrics/ — retro_<YYYY-MM-DD>.md, structure_<YYYY-MM-DD>.md, perf_<YYYY-MM-DD>_<run-label>.md, incident_<YYYY-MM-DD>_<skill>.md
|
||||
```
|
||||
|
||||
## Standalone Mode
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
---
|
||||
name: implementer
|
||||
description: |
|
||||
Implements a single task from its spec file. Use when implementing tasks from _docs/02_tasks/todo/.
|
||||
Reads the task spec, analyzes the codebase, implements the feature with tests, and verifies acceptance criteria.
|
||||
Launched by the /implement skill as a subagent.
|
||||
---
|
||||
|
||||
You are a professional software developer implementing a single task.
|
||||
|
||||
## Input
|
||||
|
||||
You receive from the `/implement` orchestrator:
|
||||
- Path to a task spec file (e.g., `_docs/02_tasks/todo/[TRACKER-ID]_[short_name].md`)
|
||||
- Files OWNED (exclusive write access — only you may modify these)
|
||||
- Files READ-ONLY (shared interfaces, types — read but do not modify)
|
||||
- Files FORBIDDEN (other agents' owned files — do not touch)
|
||||
|
||||
## Context (progressive loading)
|
||||
|
||||
Load context in this order, stopping when you have enough:
|
||||
|
||||
1. Read the task spec thoroughly — acceptance criteria, scope, constraints, dependencies
|
||||
2. Read `_docs/02_tasks/_dependencies_table.md` to understand where this task fits
|
||||
3. Read project-level context:
|
||||
- `_docs/00_problem/problem.md`
|
||||
- `_docs/00_problem/restrictions.md`
|
||||
- `_docs/01_solution/solution.md`
|
||||
4. Analyze the specific codebase areas related to your OWNED files and task dependencies
|
||||
|
||||
## Boundaries
|
||||
|
||||
**Always:**
|
||||
- Run tests before reporting done
|
||||
- Follow existing code conventions and patterns
|
||||
- Implement error handling per the project's strategy
|
||||
- Stay within the task spec's Scope/Included section
|
||||
|
||||
**Ask first:**
|
||||
- Adding new dependencies or libraries
|
||||
- Creating files outside your OWNED directories
|
||||
- Changing shared interfaces that other tasks depend on
|
||||
|
||||
**Never:**
|
||||
- Modify files in the FORBIDDEN list
|
||||
- Skip writing tests
|
||||
- Change database schema unless the task spec explicitly requires it
|
||||
- Commit secrets, API keys, or passwords
|
||||
- Modify CI/CD configuration unless the task spec explicitly requires it
|
||||
|
||||
## Process
|
||||
|
||||
1. Read the task spec thoroughly — understand every acceptance criterion
|
||||
2. Analyze the existing codebase: conventions, patterns, related code, shared interfaces
|
||||
3. Research best implementation approaches for the tech stack if needed
|
||||
4. If the task has a dependency on an unimplemented component, create a minimal interface mock
|
||||
5. Implement the feature following existing code conventions
|
||||
6. Implement error handling per the project's defined strategy
|
||||
7. Implement unit tests (use Arrange / Act / Assert section comments in language-appropriate syntax)
|
||||
8. Implement integration tests — analyze existing tests, add to them or create new
|
||||
9. Run all tests, fix any failures
|
||||
10. Verify every acceptance criterion is satisfied — trace each AC with evidence
|
||||
|
||||
## Stop Conditions
|
||||
|
||||
- If the same fix fails 3+ times with different approaches, stop and report as blocker
|
||||
- If blocked on an unimplemented dependency, create a minimal interface mock and document it
|
||||
- If the task scope is unclear, stop and ask rather than assume
|
||||
|
||||
## Completion Report
|
||||
|
||||
Report using this exact structure:
|
||||
|
||||
```
|
||||
## Implementer Report: [task_name]
|
||||
|
||||
**Status**: Done | Blocked | Partial
|
||||
**Task**: [TRACKER-ID]_[short_name]
|
||||
|
||||
### Acceptance Criteria
|
||||
| AC | Satisfied | Evidence |
|
||||
|----|-----------|----------|
|
||||
| AC-1 | Yes/No | [test name or description] |
|
||||
| AC-2 | Yes/No | [test name or description] |
|
||||
|
||||
### Files Modified
|
||||
- [path] (new/modified)
|
||||
|
||||
### Test Results
|
||||
- Unit: [X/Y] passed
|
||||
- Integration: [X/Y] passed
|
||||
|
||||
### Mocks Created
|
||||
- [path and reason, or "None"]
|
||||
|
||||
### Blockers
|
||||
- [description, or "None"]
|
||||
```
|
||||
|
||||
## Principles
|
||||
|
||||
- Follow SOLID, KISS, DRY
|
||||
- Dumb code, smart data
|
||||
- No unnecessary comments or logs (only exceptions)
|
||||
- Ask if requirements are ambiguous — do not assume
|
||||
@@ -11,6 +11,7 @@ alwaysApply: true
|
||||
- Avoid boilerplate and unnecessary indirection, but never sacrifice readability for brevity.
|
||||
- Never suppress errors silently — no `2>/dev/null`, empty `catch` blocks, bare `except: pass`, or discarded error returns. These hide the information you need most when something breaks. If an error is truly safe to ignore, log it or comment why.
|
||||
- Do not add comments that merely narrate what the code does. Comments are appropriate for: non-obvious business rules, workarounds with references to issues/bugs, safety invariants, and public API contracts. Make comments as short and concise as possible. Exception: every test must use the Arrange / Act / Assert pattern with language-appropriate comment syntax (`# Arrange` for Python, `// Arrange` for C#/Rust/JS/TS). Omit any section that is not needed (e.g. if there is no setup, skip Arrange; if act and assert are the same line, keep only Assert)
|
||||
- API consumer documentation (OpenAPI / Swagger `Description` and `Summary`, REST API reference docs, public SDK docstrings) is written for the *external API consumer*, not the implementer. Do NOT include task IDs (`AZ-NNN`, `JIRA-NNN`), contract-doc filenames (`tile-inventory.md v2.0.0`), version-bump history, or implementation milestones in these strings. Internal change tracking belongs in commit messages, contract docs, changelogs, and code comments — never in the public API description. Extend an existing pattern only if it already follows this rule; if the existing description leads with internal noise, treat that as a defect and clean it (or surface it to the user) rather than propagating it.
|
||||
- Do not add verbose debug/trace logs by default. Log exceptions, security events (auth failures, permission denials), and business-critical state transitions. Add debug-level logging only when asked.
|
||||
- Do not put code annotations unless it was asked specifically
|
||||
- Write code that takes into account the different environments: development, production
|
||||
@@ -39,8 +40,11 @@ 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
|
||||
- Never force-push to main or dev branches
|
||||
- For new projects, place source code under `src/` (this works for all stacks including .NET). For existing projects, follow the established directory structure. Keep project-level config, tests, and tooling at the repo root.
|
||||
- **Never run e2e or CI tests in quiet mode (`-q`).** Always use `-v --tb=short` (or equivalent verbosity flags) in all Dockerfiles, compose files, and scripts that invoke pytest. Full test output must be visible so failures can be diagnosed without re-running. This applies to both Tier-1 (Colima) and Tier-2 (Jetson) harnesses.
|
||||
- **Never substitute real algorithm execution with a data passthrough to make tests pass.** If a test is designed to validate output from a specific pipeline (e.g. VIO estimation, sensor fusion, inference), the implementation MUST actually run that pipeline — not bypass it by returning the input data directly as output. Tests that pass by skipping the component they are supposed to exercise create false confidence and hide the fact that the component is not integrated. If the real integration cannot be completed in this session, STOP and report the blocker to the user explicitly. A failing test with an honest explanation is always better than a passing test that proves nothing.
|
||||
|
||||
@@ -19,7 +19,7 @@ globs: [".cursor/**"]
|
||||
- Kebab-case filenames
|
||||
|
||||
## Agent Files (.cursor/agents/)
|
||||
- Must have `name` and `description` in frontmatter
|
||||
- The `.cursor/agents/` directory is intentionally empty. Per `.cursor/rules/no-subagents.mdc`, the main agent does not delegate to subagents in this workspace. Do not add agent files here without a corresponding rule change.
|
||||
|
||||
## Security
|
||||
- All `.cursor/` files must be scanned for hidden Unicode before committing (see cursor-security.mdc)
|
||||
@@ -30,10 +30,11 @@ All rules and skills must reference the single source of truth below. Do NOT res
|
||||
|
||||
| Concern | Threshold | Enforcement |
|
||||
|---------|-----------|-------------|
|
||||
| Test coverage on business logic | 75% | Aim (warn below); 100% on critical paths |
|
||||
| Test coverage on business logic | 75% | Aim (warn below); critical-path floor enforced separately (next row) |
|
||||
| Test coverage on critical paths | 90% floor / 100% aim | **90% is the enforcement floor** in CI gates, refactor verification, and release pre-flight. **100% is the aim** — drift below 100% but at-or-above 90% is acceptable; drift below 90% blocks. Critical paths = code paths where a bug would cause data loss, security breach, financial error, or system outage; identify from `acceptance_criteria.md` (must-have) and `_docs/00_problem/security_approach.md`. |
|
||||
| Test scenario coverage (vs AC + restrictions) | 75% | Blocking in test-spec Phase 1 and Phase 3 |
|
||||
| CI coverage gate | 75% | Fail build below |
|
||||
| CI coverage gate | 75% overall, 90% critical-path | Fail build below either threshold |
|
||||
| Lint errors (Critical/High) | 0 | Blocking pre-commit |
|
||||
| Code-review auto-fix | Low + Medium (Style/Maint/Perf) + High (Style/Scope) | Critical and Security always escalate |
|
||||
| Code-review auto-fix | Low + Medium (Style/Maint/Perf) + High (Style/Scope) | Critical and Security always escalate. Full categorization: see `.cursor/skills/implement/SKILL.md` § "Auto-Fix eligibility matrix" |
|
||||
|
||||
When a skill or rule needs to cite a threshold, link to this table instead of hardcoding a different number.
|
||||
When a skill or rule needs to cite a threshold, link to this table instead of hardcoding a different number. The full auto-fix eligibility matrix (severity × category) lives in `implement/SKILL.md`; cite that file rather than re-tabulating the matrix.
|
||||
|
||||
@@ -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.
|
||||
@@ -4,6 +4,26 @@ alwaysApply: true
|
||||
---
|
||||
# Agent Meta Rules
|
||||
|
||||
## Real Results, Not Simulated Ones
|
||||
|
||||
**The goal is a working product, not the appearance of one.**
|
||||
|
||||
- If something does not work, STOP and report it honestly. Do not find a way around it.
|
||||
- Never produce results by bypassing, faking, stubbing, or passthrough-ing the component that is supposed to produce them. A passing test that skips the real pipeline is worse than a failing test — it hides the truth.
|
||||
- If the real implementation is not ready, say so. A clear "this is not implemented yet, here is what is missing" is always the right answer.
|
||||
- Do not measure success by whether the output looks correct. Measure it by whether the output was produced by the real system under test.
|
||||
- Workarounds that produce the right answer via the wrong path are defects, not solutions.
|
||||
|
||||
### When a test reveals missing production code — STOP
|
||||
|
||||
This is the specific failure mode that produced the GPS-passthrough scaffold in `runtime_root._run_replay_loop` (May 2026). Generalised so it never repeats:
|
||||
|
||||
- If, while implementing or running a test, you discover that the production code path the test is supposed to exercise does not exist (no caller, no integration, no main loop, etc.), **STOP immediately**.
|
||||
- Do NOT write a stub, passthrough, fake input source, or shortcut output that would make the test go green. Even when the shortcut is "framed as a scaffold" or "marked as TODO in a docstring", it still defeats the test and lies to the next reader.
|
||||
- Surface the gap to the user as a top-of-turn report: name the missing production component, cite the architecture document that promises it, and ask whether to (a) create a tracker ticket for the missing component and let the test fail honestly until the ticket lands, or (b) explicitly de-scope the test, or (c) something the user names.
|
||||
- The default outcome is (a): a failing test plus a new tracker ticket. A failing test with an honest reason is information; a passing test that proves nothing is misinformation.
|
||||
- Doc-comment disclosures (`# this is a scaffold until X is wired`) DO NOT satisfy this rule. The user must be told in the assistant message, not in code.
|
||||
|
||||
## Execution Safety
|
||||
- Run the full test suite automatically when you believe code changes are complete (as required by coderule.mdc). For other long-running/resource-heavy/security-risky operations (builds, Docker commands, deployments, performance tests), ask the user first — unless explicitly stated in a skill or the user already asked to do so.
|
||||
|
||||
|
||||
@@ -8,8 +8,16 @@ globs: ["**/*test*", "**/*spec*", "**/*Test*", "**/tests/**", "**/test/**"]
|
||||
- One assertion per test when practical; name tests descriptively: `MethodName_Scenario_ExpectedResult`
|
||||
- Test boundary conditions, error paths, and happy paths
|
||||
- Use mocks only for external dependencies; prefer real implementations for internal code
|
||||
- Aim for 75%+ coverage on business logic; 100% on critical paths (code paths where a bug would cause data loss, security breaches, financial errors, or system outages — identify from acceptance criteria marked as must-have or from security_approach.md). The 75% threshold is canonical — see `cursor-meta.mdc` Quality Thresholds.
|
||||
- Aim for 75%+ coverage on business logic; **90% floor / 100% aim on critical paths** (code paths where a bug would cause data loss, security breaches, financial errors, or system outages — identify from acceptance criteria marked as must-have or from `security_approach.md`). 90% is the enforcement floor (blocking in CI / refactor verification / release pre-flight); 100% is the aspirational aim — drift below 100% but at-or-above 90% is acceptable. Both numbers are canonical — see `cursor-meta.mdc` Quality Thresholds.
|
||||
- Integration tests use real database (Postgres testcontainers or dedicated test DB)
|
||||
- Never use Thread Sleep or fixed delays in tests; use polling or async waits
|
||||
- Keep test data factories/builders for reusable test setup
|
||||
- Tests must be independent: no shared mutable state between tests
|
||||
|
||||
## Test environment (this project)
|
||||
|
||||
- **Unit tests** (`tests/unit/`): may run locally on the dev workstation (`pytest tests/unit/` in the project venv). Local PASS is equivalent to Jetson PASS for this tier because the suite is fully synthetic.
|
||||
- **Blackbox / e2e / performance / resilience / security / resource-limit** tests (`tests/e2e/`, `e2e/tests/`, `tests/perf/`, …): MUST run on the Jetson Orin Nano Super (or a Jetson-equivalent arm64 agent). Use `scripts/run-tests-jetson.sh` for local dev; CI runs `.woodpecker/01-test.yml` on the colocated arm64 Jetson Woodpecker agent.
|
||||
- Do NOT run e2e tests on the local workstation and report the result. If the Jetson is unreachable, the e2e verdict is "not run" — record the gap in `_docs/_process_leftovers/` rather than substituting a local result.
|
||||
- Tests gated by `RUN_REPLAY_E2E` or `@pytest.mark.tier2` are expected to SKIP locally; that is correct behaviour, not a failure to investigate.
|
||||
- Canonical source for this policy: `_docs/02_document/tests/environment.md` § Where each tier runs (active policy).
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: autodev
|
||||
description: |
|
||||
Auto-chaining orchestrator that drives the full BUILD-SHIP workflow from problem gathering through deployment.
|
||||
Auto-chaining orchestrator that drives the full BUILD → SHIP → EVOLVE workflow from problem gathering through release and retrospective.
|
||||
Detects current project state from _docs/ folder, resumes from where it left off, and flows through
|
||||
problem → research → plan → test specs → decompose → implement → tests → docs sync → deploy without manual skill invocation.
|
||||
problem → research → plan (incl. ADRs) → test specs → decompose → implement → tests → docs sync → deploy → release → retrospective without manual skill invocation.
|
||||
Maximizes work per conversation by auto-transitioning between skills.
|
||||
Trigger phrases:
|
||||
- "autodev", "auto", "start", "continue"
|
||||
@@ -15,7 +15,7 @@ disable-model-invocation: true
|
||||
|
||||
# Autodev Orchestrator
|
||||
|
||||
Auto-chaining execution engine that drives the full BUILD → SHIP workflow. Detects project state from `_docs/`, resumes from where work stopped, and flows through skills automatically. The user invokes `/autodev` once — the engine handles sequencing, transitions, and re-entry.
|
||||
Auto-chaining execution engine that drives the full BUILD → SHIP → EVOLVE workflow. Detects project state from `_docs/`, resumes from where work stopped, and flows through skills automatically. The user invokes `/autodev` once — the engine handles sequencing, transitions, and re-entry.
|
||||
|
||||
## File Index
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
Workflow for projects with an existing codebase. Structurally it has **two phases**:
|
||||
|
||||
- **Phase A — One-time baseline setup (Steps 1–8)**: runs exactly once per codebase. Documents the code, produces test specs, makes the code testable, writes and runs the initial test suite, optionally refactors with that safety net.
|
||||
- **Phase B — Feature cycle (Steps 9–17, loops)**: runs once per new feature. After Step 17 (Retrospective), the flow loops back to Step 9 (New Task) with `state.cycle` incremented.
|
||||
- **Phase B — Feature cycle (Steps 9–17, loops)**: runs once per new feature. After Step 17 (Retrospective), the flow loops back to Step 9 (New Task) with `state.cycle` incremented. Step 16.5 (Release) sits between Deploy (16) and Retrospective (17).
|
||||
|
||||
A first-time run executes Phase A then Phase B; every subsequent invocation re-enters Phase B.
|
||||
|
||||
@@ -34,6 +34,7 @@ A first-time run executes Phase A then Phase B; every subsequent invocation re-e
|
||||
| 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 |
|
||||
| 16.5 | Release | release/SKILL.md | Phase 1–6 |
|
||||
| 17 | Retrospective | retrospective/SKILL.md (cycle-end mode) | Steps 1–4 |
|
||||
|
||||
After Step 17, the feature cycle completes and the flow loops back to Step 9 with `state.cycle + 1` — see "Re-Entry After Completion" below.
|
||||
@@ -287,21 +288,43 @@ State-driven: reached by auto-chain from Step 15 (completed or skipped).
|
||||
|
||||
Action: Read and execute `.cursor/skills/deploy/SKILL.md`.
|
||||
|
||||
After the deploy skill completes successfully, mark Step 16 as `completed` and auto-chain to Step 17 (Retrospective).
|
||||
After the deploy skill completes successfully, mark Step 16 as `completed` and auto-chain to Step 16.5 (Release).
|
||||
|
||||
---
|
||||
|
||||
**Step 16.5 — Release**
|
||||
State-driven: reached by auto-chain from Step 16, for the current `state.cycle`.
|
||||
|
||||
Action: Read and execute `.cursor/skills/release/SKILL.md`. The release skill owns its own user interaction (Phase 1 pre-release gate, Phase 2 strategy select, Phase 6 escalation). Autodev does NOT add a wrapping A/B/C gate. Pass cycle context (`cycle: state.cycle`).
|
||||
|
||||
After the release skill exits, route on the verdict:
|
||||
|
||||
- **Verdict `Released`** → mark Step 16.5 `completed` and auto-chain to Step 17 (Retrospective in cycle-end mode).
|
||||
- **Verdict `Released-with-override`** → mark Step 16.5 `completed` AND auto-chain to Step 17 (Retrospective in **incident mode**).
|
||||
- **Verdict `Rolled-Back`** → mark Step 16.5 `failed`. Auto-chain to Step 17 (Retrospective in **incident mode**). The cycle does NOT loop back to Step 9.
|
||||
- **Verdict `Aborted`** → mark Step 16.5 `not_started` (no live-system change) OR `failed` (live-system touched before abort). Surface the abort reason and STOP. Next `/autodev` invocation re-evaluates Phase B from the failed step.
|
||||
|
||||
---
|
||||
|
||||
**Step 17 — Retrospective**
|
||||
State-driven: reached by auto-chain from Step 16, for the current `state.cycle`.
|
||||
State-driven: reached by auto-chain from Step 16.5 with a `Released`, `Released-with-override`, or `Rolled-Back` verdict, for the current `state.cycle`.
|
||||
|
||||
Action: Read and execute `.cursor/skills/retrospective/SKILL.md` in **cycle-end mode**. Pass cycle context (`cycle: state.cycle`) so the retro report and LESSONS.md entries record which feature cycle they came from.
|
||||
Action: Read and execute `.cursor/skills/retrospective/SKILL.md`. Mode selection:
|
||||
|
||||
After retrospective completes, mark Step 17 as `completed` and enter "Re-Entry After Completion" evaluation.
|
||||
- Step 16.5 verdict `Released` → cycle-end mode
|
||||
- Step 16.5 verdict `Released-with-override` or `Rolled-Back` → incident mode
|
||||
|
||||
Pass cycle context (`cycle: state.cycle`) so the retro report and LESSONS.md entries record which feature cycle they came from.
|
||||
|
||||
After retrospective completes:
|
||||
|
||||
- If Step 16.5 verdict was `Released` or `Released-with-override` → mark Step 17 as `completed` and enter "Re-Entry After Completion" evaluation (loop back to Step 9 for cycle N+1).
|
||||
- If Step 16.5 verdict was `Rolled-Back` → mark Step 17 as `completed` but do NOT loop back. Surface the incident retro path and STOP.
|
||||
|
||||
---
|
||||
|
||||
**Re-Entry After Completion**
|
||||
State-driven: `state.step == done` OR Step 17 (Retrospective) is completed for `state.cycle`.
|
||||
State-driven: `state.step == done` OR Step 17 (Retrospective) is completed for `state.cycle` AND Step 16.5 verdict was `Released` or `Released-with-override`. A `Rolled-Back` cycle does NOT trigger Re-Entry — the user must explicitly invoke `/autodev` again.
|
||||
|
||||
Action: The project completed a full cycle. Print the status banner and automatically loop back to New Task — do NOT ask the user for confirmation:
|
||||
|
||||
@@ -316,7 +339,7 @@ Action: The project completed a full cycle. Print the status banner and automati
|
||||
|
||||
Set `step: 9`, `status: not_started`, and **increment `cycle`** (`cycle: state.cycle + 1`) in the state file, then auto-chain to Step 9 (New Task). Reset `sub_step` to `phase: 0, name: awaiting-invocation, detail: ""` and `retry_count: 0`.
|
||||
|
||||
Note: the loop (Steps 9 → 17 → 9) ensures every feature cycle includes: New Task → Implement → Run Tests → Test-Spec Sync → Update Docs → Security → Performance → Deploy → Retrospective.
|
||||
Note: the loop (Steps 9 → 17 → 9) ensures every feature cycle includes: New Task → Implement → Run Tests → Test-Spec Sync → Update Docs → Security → Performance → Deploy → Release → Retrospective. The cycle only completes (and loops back to Step 9) on a `Released` or `Released-with-override` verdict; rolled-back or aborted releases stop the cycle.
|
||||
|
||||
## Auto-Chain Rules
|
||||
|
||||
@@ -344,8 +367,13 @@ Note: the loop (Steps 9 → 17 → 9) ensures every feature cycle includes: New
|
||||
| Update Docs (13) | 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) | **Cycle complete** — loop back to New Task (9) with incremented cycle counter |
|
||||
| Deploy (16) | Auto-chain → Release (16.5) |
|
||||
| Release (16.5, verdict Released) | Auto-chain → Retrospective (17, cycle-end mode) |
|
||||
| Release (16.5, verdict Released-with-override) | Auto-chain → Retrospective (17, **incident mode**) |
|
||||
| Release (16.5, verdict Rolled-Back) | Auto-chain → Retrospective (17, **incident mode**); cycle does NOT loop back |
|
||||
| Release (16.5, verdict Aborted) | STOP — surface abort reason; do not auto-chain |
|
||||
| Retrospective (17, after Released / Released-with-override) | **Cycle complete** — loop back to New Task (9) with incremented cycle counter |
|
||||
| Retrospective (17, after Rolled-Back) | Cycle remains incomplete — STOP and surface incident retro path |
|
||||
|
||||
## Status Summary — Step List
|
||||
|
||||
@@ -381,6 +409,7 @@ Flow-specific slot values:
|
||||
| 14 | Security Audit | — |
|
||||
| 15 | Performance Test | — |
|
||||
| 16 | Deploy | — |
|
||||
| 16.5 | Release | `DONE (Released | Released-with-override | Rolled-Back | Aborted)` |
|
||||
| 17 | Retrospective | — |
|
||||
|
||||
All rows accept the shared state tokens (`DONE`, `IN PROGRESS`, `NOT STARTED`, `FAILED (retry N/3)`); rows 2, 4, 8, 12, 13, 14, 15 additionally accept `SKIPPED`.
|
||||
@@ -406,5 +435,6 @@ Row rendering format (renders with a phase separator between Step 8 and Step 9):
|
||||
Step 14 Security Audit [<state token>]
|
||||
Step 15 Performance Test [<state token>]
|
||||
Step 16 Deploy [<state token>]
|
||||
Step 16.5 Release [<state token>]
|
||||
Step 17 Retrospective [<state token>]
|
||||
```
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Greenfield Workflow
|
||||
|
||||
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.
|
||||
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 → Release → Retrospective.
|
||||
|
||||
## Step Reference Table
|
||||
|
||||
@@ -8,7 +8,7 @@ Workflow for new projects built from scratch. Flows linearly: Problem → Resear
|
||||
|------|------|-----------|-------------------|
|
||||
| 1 | Problem | problem/SKILL.md | Phase 1–4 |
|
||||
| 2 | Research | research/SKILL.md | Mode A: Phase 1–4 · Mode B: Step 0–8 |
|
||||
| 3 | Plan | plan/SKILL.md | Step 1–6 + Final |
|
||||
| 3 | Plan | plan/SKILL.md | Step 1, 2, 3, 4, 4.5 (ADR Capture), 5, 6 + Final |
|
||||
| 4 | UI Design | ui-design/SKILL.md | Phase 0–8 (conditional — UI projects only) |
|
||||
| 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 |
|
||||
@@ -22,6 +22,7 @@ Workflow for new projects built from scratch. Flows linearly: Problem → Resear
|
||||
| 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 |
|
||||
| 16.5 | Release | release/SKILL.md | Phase 1–6 |
|
||||
| 17 | Retrospective | retrospective/SKILL.md (cycle-end mode) | Steps 1–4 |
|
||||
|
||||
## Detection Rules
|
||||
@@ -284,21 +285,42 @@ State-driven: reached by auto-chain from Step 15 (after Step 15 is completed or
|
||||
|
||||
Action: Read and execute `.cursor/skills/deploy/SKILL.md`.
|
||||
|
||||
After the deploy skill completes successfully, mark Step 16 as `completed` and auto-chain to Step 17 (Retrospective).
|
||||
After the deploy skill completes successfully, mark Step 16 as `completed` and auto-chain to Step 16.5 (Release).
|
||||
|
||||
---
|
||||
|
||||
**Step 16.5 — Release**
|
||||
State-driven: reached by auto-chain from Step 16.
|
||||
|
||||
Action: Read and execute `.cursor/skills/release/SKILL.md`. The release skill is responsible for selecting the target environment, executing the deploy artifacts, smoke-testing, watching the rollout, and producing a definitive verdict (`Released`, `Released-with-override`, `Rolled-Back`, or `Aborted`).
|
||||
|
||||
The release skill has its own internal BLOCKING gates (Phase 1 pre-release gate, Phase 2 strategy select, Phase 6 user confirmation when soft regression escalates). Autodev does NOT add a wrapping A/B/C gate — the release skill owns its own user interaction.
|
||||
|
||||
After the release skill exits:
|
||||
|
||||
- **Verdict `Released`** → mark Step 16.5 `completed` and auto-chain to Step 17 (Retrospective in cycle-end mode).
|
||||
- **Verdict `Released-with-override`** → mark Step 16.5 `completed` AND auto-chain to Step 17 (Retrospective in **incident mode**) — the override is itself an incident the retrospective must analyze.
|
||||
- **Verdict `Rolled-Back`** → mark Step 16.5 `failed`. Auto-chain to Step 17 (Retrospective in **incident mode**). Do NOT consider the project "Done" — the user owns the next move (re-run /implement on a fix branch, re-run /deploy, re-run /release).
|
||||
- **Verdict `Aborted`** → mark Step 16.5 `not_started` (the release was never started) OR `failed` if the abort came after Phase 3 had already touched the live system. Surface the abort reason and STOP — do not auto-chain to retrospective.
|
||||
|
||||
---
|
||||
|
||||
**Step 17 — Retrospective**
|
||||
State-driven: reached by auto-chain from Step 16.
|
||||
State-driven: reached by auto-chain from Step 16.5 with a `Released` or `Released-with-override` verdict, OR from a `Rolled-Back` verdict (in incident mode).
|
||||
|
||||
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`.
|
||||
Action: Read and execute `.cursor/skills/retrospective/SKILL.md`. Mode selection:
|
||||
|
||||
- Step 16.5 verdict `Released` → cycle-end mode
|
||||
- Step 16.5 verdict `Released-with-override` or `Rolled-Back` → incident mode
|
||||
|
||||
The retrospective closes the cycle's feedback loop by folding metrics into `_docs/06_metrics/retro_<date>.md` (or `incident_<date>_release.md` in incident mode) and appending the top-3 lessons to `_docs/LESSONS.md`.
|
||||
|
||||
After retrospective completes, mark Step 17 as `completed` and enter "Done" evaluation.
|
||||
|
||||
---
|
||||
|
||||
**Done**
|
||||
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.)
|
||||
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. `_docs/04_release/` should contain at least one `release_<version>_<env>_<timestamp>.md` with a `Released` verdict — or the user has explicitly chosen to handle release outside autodev.)
|
||||
|
||||
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:
|
||||
|
||||
@@ -337,7 +359,11 @@ On the next invocation, Flow Resolution rule 1 reads `flow: existing-code` and r
|
||||
| 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) |
|
||||
| Deploy (16) | Auto-chain → Release (16.5) |
|
||||
| Release (16.5, verdict Released) | Auto-chain → Retrospective (17, cycle-end mode) |
|
||||
| Release (16.5, verdict Released-with-override) | Auto-chain → Retrospective (17, **incident mode**) |
|
||||
| Release (16.5, verdict Rolled-Back) | Auto-chain → Retrospective (17, **incident mode**); do NOT enter Done |
|
||||
| Release (16.5, verdict Aborted) | STOP — surface abort reason; do not auto-chain |
|
||||
| Retrospective (17) | Report completion; rewrite state to existing-code flow, step 9 |
|
||||
|
||||
## Status Summary — Step List
|
||||
@@ -362,6 +388,7 @@ Flow name: `greenfield`. Render using the banner template in `protocols.md` →
|
||||
| 14 | Security Audit | — |
|
||||
| 15 | Performance Test | — |
|
||||
| 16 | Deploy | — |
|
||||
| 16.5 | Release | `DONE (Released | Released-with-override | Rolled-Back | Aborted)` |
|
||||
| 17 | Retrospective | — |
|
||||
|
||||
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`.
|
||||
@@ -385,5 +412,6 @@ Row rendering format (step-number column is right-padded to 2 characters for ali
|
||||
Step 14 Security Audit [<state token>]
|
||||
Step 15 Performance Test [<state token>]
|
||||
Step 16 Deploy [<state token>]
|
||||
Step 16.5 Release [<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
|
||||
|
||||
@@ -17,6 +18,7 @@ This flow differs fundamentally from `greenfield` and `existing-code`:
|
||||
| 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) |
|
||||
@@ -184,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):
|
||||
|
||||
```
|
||||
══════════════════════════════════════
|
||||
@@ -205,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.
|
||||
|
||||
---
|
||||
|
||||
@@ -287,11 +421,16 @@ After onboarding completes, the config is updated. Auto-chain back to **Step 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 |
|
||||
| Glossary & Architecture Vision (2.5) | Auto-chain → Status (3) |
|
||||
| Status (3, doc drift) | Auto-chain → Document Sync (4) |
|
||||
| Status (3, suite-e2e drift only) | Auto-chain → Integration Test Sync (4.5) |
|
||||
| Status (3, CI drift only) | Auto-chain → CICD Sync (5) |
|
||||
| Status (3, no drift) | **Cycle complete** — end session, await re-invocation |
|
||||
| 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) |
|
||||
| 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** |
|
||||
@@ -317,11 +456,12 @@ Flow-specific slot values:
|
||||
| 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 2.5, 4, 4.5, 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:
|
||||
|
||||
@@ -330,6 +470,7 @@ Row rendering format:
|
||||
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>]
|
||||
@@ -337,8 +478,12 @@ Row rendering format:
|
||||
|
||||
## Notes for the meta-repo flow
|
||||
|
||||
- **No session boundary except Step 2 and Step 2.5**: unlike existing-code flow (which has boundaries around decompose), meta-repo flow only pauses at config review and the one-shot glossary/vision capture. Once both are confirmed, syncing is fast enough to complete in one session and Step 2.5 idempotently no-ops on every subsequent invocation.
|
||||
- **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`).
|
||||
|
||||
@@ -114,6 +114,7 @@ Before entering a step from this table for the first time in a session, verify t
|
||||
| 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
|
||||
|
||||
@@ -388,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-17 for greenfield, 1-17 for existing-code, 1-6 for meta-repo, or "done"]
|
||||
step: [1-17 for greenfield (incl. fractional 16.5), 1-17 for existing-code (incl. fractional 16.5), 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
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: code-review
|
||||
description: |
|
||||
Multi-phase code review against task specs with structured findings output.
|
||||
6-phase workflow: context loading, spec compliance, code quality, security quick-scan, performance scan, cross-task consistency.
|
||||
7-phase workflow: context loading, spec compliance, code quality, security quick-scan, performance scan, cross-task consistency, architecture compliance.
|
||||
Produces a structured report with severity-ranked findings and a PASS/FAIL/PASS_WITH_WARNINGS verdict.
|
||||
Invoked by /implement skill after each batch, or manually.
|
||||
Trigger phrases:
|
||||
@@ -106,11 +106,12 @@ When multiple tasks were implemented in the same batch:
|
||||
|
||||
## Phase 7: Architecture Compliance
|
||||
|
||||
Verify the implemented code respects the architecture documented in `_docs/02_document/architecture.md` and the component boundaries declared in `_docs/02_document/module-layout.md`.
|
||||
Verify the implemented code respects the architecture documented in `_docs/02_document/architecture.md`, the component boundaries declared in `_docs/02_document/module-layout.md`, and the **accepted Architectural Decision Records** under `_docs/02_document/adr/`.
|
||||
|
||||
**Inputs**:
|
||||
- `_docs/02_document/architecture.md` — layering, allowed dependencies, patterns
|
||||
- `_docs/02_document/module-layout.md` — per-component directories, Public API surface, `Imports from` lists, Allowed Dependencies table
|
||||
- `_docs/02_document/adr/` — every `Status: Accepted` ADR is an enforceable structural rule. `Status: Proposed`, `Status: Deprecated`, and `Status: Superseded` ADRs are NOT enforced (Proposed = not yet ratified; Deprecated/Superseded = a later ADR overturned it). If the directory does not exist or has only the index file, ADRs are skipped — log this skip in the report so the absence is visible.
|
||||
- The cumulative list of changed files (for per-batch invocation) or the full codebase (for baseline invocation)
|
||||
|
||||
**Checks**:
|
||||
@@ -125,6 +126,11 @@ Verify the implemented code respects the architecture documented in `_docs/02_do
|
||||
|
||||
5. **Cross-cutting concerns not locally re-implemented**: if a file under a component directory contains logic that should live in `shared/<concern>/` (e.g., custom logging setup, config loader, error envelope), flag it. Severity: Medium. Category: Architecture.
|
||||
|
||||
6. **ADR compliance**: for each `Status: Accepted` ADR, confirm the changed code does not contradict the ADR's `Decision`. Two failure modes are flagged:
|
||||
- **ADR-Violation**: the changed code does the opposite of an Accepted ADR's `Decision`. Example: ADR-002 says "We will use Postgres for transactional data" and the changed code introduces a SQLite dependency for a transactional path. Severity: **Critical**. Category: Architecture. The finding cites the ADR by `NNN_<slug>` and the offending file/line.
|
||||
- **ADR-Drift**: the changed code does something the ADR did not anticipate AND that materially affects the ADR's `Consequences` (positive or negative). Example: ADR-004 says "Event-driven cross-component comms" and a changed file introduces a new synchronous HTTP call between two components. Severity: **High**. Category: Architecture. The finding either proposes "Update ADR-NNN to acknowledge the new pattern" or "Remove the drift to align with ADR-NNN" — never silently accepts.
|
||||
The check skips ADRs that are explicitly out of scope of the changed batch (e.g., ADR-001 about deployment pipeline when the batch only touches business-logic files). Use the ADR's `Evidence` section to determine scope: if no Evidence path overlaps with any changed file, skip the ADR for this batch.
|
||||
|
||||
**Detection approach (per language)**:
|
||||
|
||||
- Python: parse `import` / `from ... import` statements; optionally AST with `ast` module for reliable symbol resolution.
|
||||
@@ -197,7 +203,7 @@ Produce a structured report with findings deduplicated and sorted by severity:
|
||||
|
||||
Bug, Spec-Gap, Security, Performance, Maintainability, Style, Scope, Architecture
|
||||
|
||||
`Architecture` findings come from Phase 7. They indicate layering violations, Public API bypasses, new cyclic dependencies, duplicate symbols, or cross-cutting concerns re-implemented locally.
|
||||
`Architecture` findings come from Phase 7. They indicate layering violations, Public API bypasses, new cyclic dependencies, duplicate symbols, cross-cutting concerns re-implemented locally, **ADR-Violation** (changed code contradicts an `Accepted` ADR's Decision — Critical), or **ADR-Drift** (changed code introduces a pattern that materially affects an `Accepted` ADR's Consequences without superseding it — High).
|
||||
|
||||
## Verdict Logic
|
||||
|
||||
@@ -232,7 +238,7 @@ The implement skill invokes code-review by:
|
||||
|
||||
1. Reading `.cursor/skills/code-review/SKILL.md`
|
||||
2. Providing the inputs above as context (read the files, pass content to the review phases)
|
||||
3. Executing all 6 phases sequentially
|
||||
3. Executing all 7 phases sequentially
|
||||
4. Consuming the verdict from the output
|
||||
|
||||
### Outputs (returned to the implement skill)
|
||||
|
||||
@@ -65,6 +65,7 @@ Announce the selected entrypoint and resolved paths to the user before proceedin
|
||||
| 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` | ✓ | — | — |
|
||||
| 1.7 System-Pipeline Tasks | `steps/01-7_system-pipeline-tasks.md` | ✓ | — | — |
|
||||
| 2 Task Decomposition | `steps/02_task-decomposition.md` | ✓ | ✓ | — |
|
||||
| 3 Blackbox Test Tasks | `steps/03_blackbox-test-decomposition.md` | — | — | ✓ |
|
||||
| 4 Cross-Verification | `steps/04_cross-verification.md` | ✓ | — | ✓ |
|
||||
@@ -191,6 +192,20 @@ Read and follow `steps/01-5_module-layout.md`.
|
||||
|
||||
---
|
||||
|
||||
### Step 1.7: System-Pipeline Tasks (implementation mode only)
|
||||
|
||||
Read and follow `steps/01-7_system-pipeline-tasks.md`.
|
||||
|
||||
This step exists because per-component task decomposition (Step 2)
|
||||
produces one task per component but NEVER produces a task whose
|
||||
deliverable is "the production code that drives the end-to-end
|
||||
pipeline by calling each component in order against real inputs".
|
||||
The architecture document describes the loop; nobody owns it. The
|
||||
GPS-passthrough incident (May 2026) is the canonical failure this
|
||||
step prevents.
|
||||
|
||||
---
|
||||
|
||||
### Step 2: Task Decomposition (implementation and single component modes)
|
||||
|
||||
Read and follow `steps/02_task-decomposition.md`.
|
||||
@@ -243,6 +258,8 @@ Read and follow `steps/04_cross-verification.md`.
|
||||
│ [BLOCKING: user confirms structure] │
|
||||
│ 1.5 Module Layout → steps/01-5_module-layout.md │
|
||||
│ [BLOCKING: user confirms layout] │
|
||||
│ 1.7 System-Pipeline → steps/01-7_system-pipeline-tasks.md │
|
||||
│ [BLOCKING: user confirms pipeline owners] │
|
||||
│ 2. Component Tasks → steps/02_task-decomposition.md │
|
||||
│ 4. Cross-Verification → steps/04_cross-verification.md │
|
||||
│ [BLOCKING: user confirms dependencies] │
|
||||
|
||||
@@ -16,7 +16,8 @@
|
||||
3. Each component owns ONE top-level directory. Shared code goes under `<root>/shared/` (or language equivalent).
|
||||
4. Public API surface = files in the layout's `public:` list for each component; everything else is internal and MUST NOT be imported from other components.
|
||||
5. Cross-cutting concerns (logging, error handling, config, telemetry, auth middleware, feature flags, i18n) each get ONE entry under Shared / Cross-Cutting; per-component tasks consume them (see Step 2 cross-cutting rule).
|
||||
6. Write `_docs/02_document/module-layout.md` using `templates/module-layout.md` format.
|
||||
6. **ADR cross-check**: if `_docs/02_document/adr/` exists, read every `Status: Accepted` ADR. For each, confirm the proposed module layout does not contradict the ADR's `Decision` (e.g., an ADR mandating an event-bus boundary between two components must show up as a `Imports from` exclusion in the layout; an ADR locking a layering style must show up in the Layering table). If an ADR conflicts with the language-conventional layout from step 2, the ADR wins — record the conflict in a `## ADR-driven exceptions to the conventional layout` section of `module-layout.md` with `See ADR NNN_<slug>` references. If the ADR conflict is irreconcilable (the ADR demands something the language genuinely cannot express), STOP and ask the user A/B/C: (A) update the ADR via plan Step 4.5 supersede flow, (B) accept a layered exception with documented rationale, (C) re-open architecture.
|
||||
7. Write `_docs/02_document/module-layout.md` using `templates/module-layout.md` format. Each Per-Component Mapping entry that is governed by an ADR includes a trailing `> See ADR NNN_<slug>` line.
|
||||
|
||||
## Self-verification
|
||||
|
||||
@@ -26,6 +27,8 @@
|
||||
- [ ] No component's `Imports from` list points at a higher layer
|
||||
- [ ] Paths follow the detected language's convention
|
||||
- [ ] No two components own overlapping paths
|
||||
- [ ] If `_docs/02_document/adr/` exists with Accepted ADRs, every layout decision that an ADR governs has a trailing `> See ADR NNN_<slug>` reference
|
||||
- [ ] No Accepted ADR is contradicted by the layout without a documented exception
|
||||
|
||||
## Save action
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# Step 1.7: System-Pipeline Tasks (implementation mode only)
|
||||
|
||||
**Role**: Professional software architect, integration-focused.
|
||||
**Goal**: For every end-to-end pipeline named in `_docs/02_document/architecture.md` and `_docs/02_document/system-flows.md`, ensure there is exactly ONE explicit task that owns the production code that drives that pipeline against real inputs. This step prevents the failure mode where every individual component is "complete" but no production code wires them together (May 2026 GPS-passthrough incident — see `meta-rule.mdc` "When a test reveals missing production code").
|
||||
|
||||
**Constraints**:
|
||||
|
||||
- This step produces *integration* tasks, not per-component tasks. Per-component tasks come from Step 2.
|
||||
- An integration task's owner is typically the composition root, runtime root, main loop, or whichever component the module layout (Step 1.5) names as the "system spine". It is NEVER a leaf component.
|
||||
- Each integration task must be sized at 5 points or fewer. If the pipeline is too large for one task, split it into per-stage integration tasks (e.g. "wire ingress → C1", then "wire C1 → C5") rather than one giant task.
|
||||
|
||||
## Inputs
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `_docs/02_document/architecture.md` | Source of named end-to-end pipelines and their component sequences |
|
||||
| `_docs/02_document/system-flows.md` | Source of operational flows (per-frame loop, request lifecycle, batch job, etc.) |
|
||||
| `_docs/02_document/module-layout.md` | Produced by Step 1.5. Names the "system spine" component(s) — typically `runtime_root`, `app`, `main`, `composition`, or equivalent. |
|
||||
| `_docs/02_document/components/*/description.md` | Per-component contracts so you can tell which side of a seam each method lives on |
|
||||
|
||||
## Steps
|
||||
|
||||
1. **Enumerate end-to-end pipelines.** Read `architecture.md` and `system-flows.md`. For each named pipeline / flow that spans 2+ components, record:
|
||||
- The pipeline name (e.g. "per-frame nav loop", "tile-cache build", "operator pre-flight verification").
|
||||
- The ordered sequence of components it touches (e.g. `frame_source → c1_vio → c2_vpr → ... → c5_state → replay_sink`).
|
||||
- The trigger (per-frame, per-request, scheduled, manual).
|
||||
- The output (what the pipeline emits and to whom).
|
||||
2. **For each pipeline, locate the owner.** Use `module-layout.md` to find the component that owns the orchestration (the "spine"). If `module-layout.md` does not name one, STOP and ASK the user which component owns the pipeline. Do NOT silently default to the bootstrap structure task — bootstrap is about project skeleton, not behavior.
|
||||
3. **Check whether the pipeline is already covered by an existing task spec or by the bootstrap-structure task.** A pipeline is "covered" only if:
|
||||
- A task spec's `Outcome` or `Acceptance Criteria` section explicitly names "drives the {pipeline_name} end-to-end against real production components", AND
|
||||
- That task's owned files include the orchestration code (typically the spine component's main loop / entrypoint).
|
||||
4. **For every uncovered pipeline, create a system-integration task spec** in `_docs/02_tasks/todo/` using `.cursor/skills/decompose/templates/task.md`:
|
||||
- **Component**: the spine component from step 2 (e.g. `runtime_root`).
|
||||
- **Outcome**: the production callsite that drives the pipeline exists and runs end-to-end on real inputs.
|
||||
- **Scope / Included**: the orchestration code (loop body, dispatcher, scheduler, entrypoint); explicit list of every component it must call in order; the data type at each seam.
|
||||
- **Acceptance Criteria** (write each as testable):
|
||||
- At least one production caller of every component method in the pipeline can be found by grep — name the methods explicitly.
|
||||
- The orchestration runs against the real production component instances (NOT mocks, NOT a passthrough that bypasses them).
|
||||
- At least one integration test exercises the orchestration end-to-end against real inputs.
|
||||
- **Dependencies**: every per-component task whose component appears in the pipeline.
|
||||
- **Complexity points**: ≤5; split the pipeline if it doesn't fit.
|
||||
- **Tracker**: create a ticket immediately (per `decompose/SKILL.md` "Tracker inline" principle); rename the file to `[TRACKER-ID]_pipeline_<name>.md`.
|
||||
5. **Mark the integration task as `Dependencies` for the integration test task.** If `tests-only` decomposition has already produced an e2e/integration test task for this pipeline, append the new integration task to its `Dependencies` field so the test cannot be "made green" before the integration ships.
|
||||
|
||||
## Anti-patterns this step explicitly blocks
|
||||
|
||||
- **"compose_root returns a wired runtime"** prose interpreted as "the loop exists". Composition assembles the graph; it is NOT the loop. The loop is the code that pulls inputs, drives each node, and emits outputs. If grep finds zero callers of the leaf components, the loop does not exist regardless of what compose_root does.
|
||||
- **Treating the bootstrap-structure task as the home of the main loop.** Bootstrap is project skeleton (package layout, CLI scaffold, build files). It is NOT the main loop. Main loop is its own task.
|
||||
- **Per-component tasks claiming integration scope.** A C1 VIO task's deliverable is "C1 works in isolation against unit tests". A C1 task's acceptance criteria MUST NOT include "C1 is wired into the runtime" — that's the integration task's job.
|
||||
|
||||
## Self-verification
|
||||
|
||||
- [ ] Every pipeline named in `architecture.md` / `system-flows.md` is listed in your enumeration.
|
||||
- [ ] Every enumerated pipeline either (a) has an existing covered task, or (b) has a new integration task in `todo/`.
|
||||
- [ ] No integration task exceeds 5 complexity points.
|
||||
- [ ] Every integration task names every component in the pipeline as a `Dependencies` entry.
|
||||
- [ ] No integration task is owned by a leaf component — every owner is named in `module-layout.md` as a spine / orchestrator.
|
||||
- [ ] Every integration task has a tracker ticket created and the filename renamed to `[TRACKER-ID]_pipeline_<name>.md`.
|
||||
|
||||
## Save action
|
||||
|
||||
Write the new integration task files into `_docs/02_tasks/todo/`. They will be picked up by Step 2 (Task Decomposition's dependency-table writer) and by Step 4 (Cross-Verification).
|
||||
|
||||
## Blocking
|
||||
|
||||
**BLOCKING**: Present the pipeline enumeration + the list of new integration tasks to the user. Do NOT proceed to Step 2 until the user confirms:
|
||||
|
||||
- The enumeration matches what they expect from the architecture documents.
|
||||
- Every uncovered pipeline now has an integration task.
|
||||
- The chosen spine owners are correct.
|
||||
|
||||
If the user identifies a pipeline you missed, add it before proceeding. If the user names a different spine owner, update the task and re-run self-verification.
|
||||
@@ -29,7 +29,7 @@ Save as `_docs/04_deploy/ci_cd_pipeline.md`.
|
||||
### Test
|
||||
- Unit tests: [framework and command]
|
||||
- Blackbox tests: [framework and command, uses docker-compose.test.yml]
|
||||
- Coverage threshold: 75% overall, 90% critical paths
|
||||
- Coverage threshold: 75% overall, 90% critical-path floor (100% aim) — per `.cursor/rules/cursor-meta.mdc` Quality Thresholds
|
||||
- Coverage report published as pipeline artifact
|
||||
|
||||
### Security
|
||||
|
||||
@@ -64,6 +64,27 @@ 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 for the selected context — **STOP if missing**
|
||||
@@ -103,7 +124,7 @@ TASKS_DIR/
|
||||
|
||||
### 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.
|
||||
@@ -222,6 +243,8 @@ For product implementation, this archive means "batch implementation accepted."
|
||||
|
||||
### 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)
|
||||
@@ -239,7 +262,7 @@ For product implementation, this archive means "batch implementation accepted."
|
||||
|
||||
### 15. Product Implementation Completeness Gate
|
||||
|
||||
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 only when the remaining context is explicitly test implementation or refactoring, as determined by the task files and report filename rules.
|
||||
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.
|
||||
|
||||
@@ -268,19 +291,46 @@ For each completed product task:
|
||||
- **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.
|
||||
|
||||
#### 15.b System-Pipeline Check (runs ONCE per gate invocation, after per-task classification)
|
||||
|
||||
The per-task classification above (steps 1–8) operates on `_docs/02_tasks/done/`. It catches missing component-local behavior but it CANNOT catch a missing *integration* — there is no task to fail if no task ever owned the integration in the first place. The GPS-passthrough incident (May 2026) escaped this gate because every per-component task in `done/` was honestly complete; the missing piece was the cross-component loop, which had no owning task.
|
||||
|
||||
The system-pipeline check fixes that by walking the architecture documents directly, independent of `done/`.
|
||||
|
||||
**Inputs**:
|
||||
- `_docs/02_document/architecture.md`
|
||||
- `_docs/02_document/system-flows.md`
|
||||
- Full source tree under the project's production directory (e.g. `src/`).
|
||||
|
||||
**Procedure**:
|
||||
|
||||
1. **Enumerate end-to-end pipelines.** Read `architecture.md` and `system-flows.md`. For each named pipeline / operational flow that spans 2+ components, record the ordered component sequence and the trigger (per-frame, per-request, scheduled, manual).
|
||||
2. **Grep for production callers of each seam method.** For each adjacent pair `A → B` in a pipeline, find a production source file (not under `tests/`, not under a `bench/` package, not a doc) that calls `A`'s public output method AND passes the result into `B`'s public input method.
|
||||
3. **Classify the pipeline**:
|
||||
- **WIRED**: a production caller exists and the chain is complete from the first to the last component in the sequence.
|
||||
- **PARTIALLY WIRED**: some adjacent pairs have callers but at least one seam is missing.
|
||||
- **NOT WIRED**: no production code calls the pipeline's components in order. Bench tools, unit tests, and microbenchmarks do NOT count as "wiring".
|
||||
4. **Distinguish "wired but stubbed" from "wired with real components"**: a caller that invokes a passthrough / GPS-from-tlog / mock-output-generator instead of the real component is `NOT WIRED` for the purposes of this gate. The seam exists in the source file but the production behavior is faked. Grep for the same scaffold markers Step 15 already enumerates (`placeholder`, `stub`, `passthrough`, `scaffold until`, etc.) inside the caller's body.
|
||||
5. **Output**: append a `## System Pipeline Audit` section to `_docs/03_implementation/implementation_completeness_cycle[N]_report.md`. Per-pipeline row: name, sequence, classification, evidence file (the caller, or "NONE FOUND"), remediation suggestion if not `WIRED`.
|
||||
|
||||
**Pipeline classification feeds the combined gate below.** Any pipeline that is not `WIRED` is a system-level FAIL that the per-task gate cannot rescue.
|
||||
|
||||
**Why this is here and not only in decompose**: decompose Step 1.7 creates integration tasks up front; this check verifies the integration tasks actually got implemented (or, if they were never created, surfaces the gap before the cycle closes). The two layers are belt-and-suspenders by design.
|
||||
|
||||
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
|
||||
- **System Pipeline Audit table** (per pipeline: name, sequence, WIRED / PARTIALLY WIRED / NOT WIRED, evidence file, remediation suggestion)
|
||||
- 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
|
||||
- If every product task is `PASS` or `BLOCKED` with explicit prerequisite evidence, AND every enumerated pipeline is `WIRED`, continue to Final Test Run.
|
||||
- If any product task is `FAIL` OR any pipeline is `PARTIALLY WIRED` / `NOT WIRED`, 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. (For pipeline FAILs the remediation task is a NEW integration task owned by the spine component per `_docs/02_document/module-layout.md`; it is NOT a test task and NOT a doc task; its deliverable is production code that drives the pipeline against real components.)
|
||||
- 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.
|
||||
@@ -309,8 +359,9 @@ After each batch completes, save the batch report to `_docs/03_implementation/ba
|
||||
- **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).
|
||||
|
||||
|
||||
@@ -84,14 +84,46 @@ Assess the change along these dimensions:
|
||||
- **Novelty**: does it involve libraries, protocols, or patterns not already in the codebase?
|
||||
- **Risk**: could it break existing functionality or require architectural changes?
|
||||
|
||||
Classification:
|
||||
### 2a. Complexity-Points Estimate
|
||||
|
||||
Project policy (per the workspace user-rule on ADO points): aim for tasks at 2–3 points (rarely 5). Tasks at 8 points are high risk; tasks at 13 are too complex and MUST be broken down. The new-task skill enforces this here, before producing a single-file task spec.
|
||||
|
||||
Map the Scope/Novelty/Risk profile to a points estimate using this table:
|
||||
|
||||
| Profile | Points | Examples |
|
||||
|---------|--------|----------|
|
||||
| All three low | **1–2** | One-line config change; trivial CRUD field addition |
|
||||
| Two low + one medium | **3** | Localized refactor; add one well-understood endpoint |
|
||||
| One low + two medium, OR all medium | **5** | New small feature touching 2–3 components; integration with a known library |
|
||||
| Any high, OR two medium + one high | **8** | Cross-cutting concern across 4+ components; integration with an unfamiliar protocol; significant architectural change |
|
||||
| Two or three high | **13** | New subsystem; unfamiliar tech across the stack; multiple unknown unknowns |
|
||||
|
||||
If a relevant LESSONS.md entry biases the estimate (e.g., "auth-related changes historically take 2× estimate"), apply the multiplier and round up to the next discrete point on the scale (1, 2, 3, 5, 8, 13).
|
||||
|
||||
### 2b. Routing by Complexity
|
||||
|
||||
| Estimate | Default routing | Override path |
|
||||
|----------|-----------------|---------------|
|
||||
| **1–5** | Continue this skill at Step 3 (Research) or Step 4 (Codebase Analysis) — see classification below | — |
|
||||
| **8** | **STOP this skill and recommend handoff to `/decompose @<feature_description>`** (single-component decompose mode if the affected scope fits inside one component, default mode if it does not). The user may override and proceed in `/new-task`, but the override must be explicitly chosen. | C) Proceed in /new-task anyway with the user's acknowledgement that the resulting task is high-risk and may need to be re-decomposed mid-implementation |
|
||||
| **13** | **STOP this skill — auto-handoff is mandatory.** A 13-point feature cannot be a single task spec. Invoke `/decompose @<feature_description>` (default mode) before writing any task file. Surface the handoff to the user with no override path; this is a hard policy gate. | None — must decompose |
|
||||
|
||||
For the auto-handoff path:
|
||||
|
||||
1. Render a one-paragraph description of the feature suitable to feed `/decompose` (combine Step 1's verbatim user description with the complexity-points reasoning).
|
||||
2. Save it to `_docs/02_task_plans/<feature_slug>/feature-description.md` so the decompose skill has a stable input file.
|
||||
3. Either (a) directly auto-chain into `.cursor/skills/decompose/SKILL.md` in default mode with this file as input, or (b) report the handoff to the user along with the exact `/decompose` invocation and stop. Pick (a) only if the user has explicitly enabled auto-chain across skills (e.g., we are inside an `/autodev` invocation); otherwise pick (b).
|
||||
|
||||
### 2c. Research vs Skip Research (only for ≤5 estimates)
|
||||
|
||||
Classification (independent of points; runs only when points ≤ 5 and Step 2b chose Continue):
|
||||
|
||||
| Category | Criteria | Action |
|
||||
|----------|----------|--------|
|
||||
| **Needs research** | New libraries/frameworks, unfamiliar protocols, significant architectural change, multiple unknowns | Proceed to Step 3 (Research) |
|
||||
| **Needs research** | New libraries/frameworks, unfamiliar protocols, multiple unknowns | Proceed to Step 3 (Research) |
|
||||
| **Skip research** | Extends existing functionality, uses patterns already in codebase, straightforward new component with known tech | Skip to Step 4 (Codebase Analysis) |
|
||||
|
||||
Present the assessment to the user:
|
||||
Present the full assessment to the user:
|
||||
|
||||
```
|
||||
══════════════════════════════════════
|
||||
@@ -100,13 +132,18 @@ Present the assessment to the user:
|
||||
Scope: [low / medium / high]
|
||||
Novelty: [low / medium / high]
|
||||
Risk: [low / medium / high]
|
||||
Points: [1 / 2 / 3 / 5 / 8 / 13] (project aim: 2–3, rarely 5)
|
||||
Routing: [Continue in /new-task | Hand off to /decompose]
|
||||
══════════════════════════════════════
|
||||
Recommendation: [Research needed / Skip research]
|
||||
Reason: [one-line justification]
|
||||
Recommendation: [Research needed | Skip research | Decompose required]
|
||||
Reason: [one-line justification, including any LESSONS.md influence]
|
||||
══════════════════════════════════════
|
||||
```
|
||||
|
||||
**BLOCKING**: Ask the user to confirm or override the recommendation before proceeding.
|
||||
**BLOCKING**:
|
||||
- If points ≤ 5 → ask the user to confirm or override the research recommendation before proceeding.
|
||||
- If points = 8 → ask the user to choose between hand-off to /decompose (recommended) and continuing in /new-task with explicit risk acknowledgement.
|
||||
- If points = 13 → STOP and present the handoff plan; do not offer a continue-anyway override.
|
||||
|
||||
---
|
||||
|
||||
@@ -203,7 +240,13 @@ Apply the four shared-task triggers from `.cursor/skills/decompose/SKILL.md` Ste
|
||||
2. Add the layout edit to the task's deliverables; the implementer writes it alongside the code change.
|
||||
3. If `module-layout.md` does not exist, STOP and instruct the user to run `/document` first (existing-code flow) or `/decompose` default mode (greenfield). Do not guess.
|
||||
|
||||
Record the classification and any contract/layout deliverables in the working notes; they feed Step 5 (Validate Assumptions) and Step 6 (Create Task).
|
||||
- **ADR cross-check** — runs unconditionally for every new-task in any of the three classifications above:
|
||||
1. If `_docs/02_document/adr/` exists, scan every `Status: Accepted` ADR. For each, ask: "would the proposed task either contradict this ADR's `Decision` or materially affect its `Consequences`?"
|
||||
2. **Conflict** (task contradicts an Accepted ADR) → STOP and Choose A/B/C: **A)** Re-scope the task to comply with the ADR, **B)** Propose superseding the ADR — the task spec then includes a deliverable to invoke `/plan --adr-only` (or the next `/plan` cycle's Step 4.5) with `Supersedes: ADR-NNN`, and the new task does NOT proceed until that supersede ADR is `Accepted`, **C)** Park the task in `backlog/` with a `Blocked-By: ADR-NNN review` note. Do not silently approve a contradictory task.
|
||||
3. **Drift** (task changes assumptions an ADR depends on but does not directly contradict it) → record the affected ADR(s) under a new `### ADR Impact` section in the task spec with `> Affects ADR NNN_<slug>: <one-line summary>`. The implementer surfaces this at code-review Phase 7 (which then classifies it as ADR-Drift if not addressed).
|
||||
4. **Aligned** (task implements something an Accepted ADR mandates) → cite the ADR(s) under `### ADR Compliance` in the task spec with `> Implements ADR NNN_<slug>`. Code-review Phase 7 then expects matching evidence in the implemented code.
|
||||
|
||||
Record the classification, any contract/layout deliverables, and any ADR cross-check outcomes in the working notes; they feed Step 5 (Validate Assumptions) and Step 6 (Create Task).
|
||||
|
||||
**BLOCKING**: none — this step surfaces findings; the user confirms them in Step 5.
|
||||
|
||||
@@ -263,6 +306,9 @@ Present using the Choose format for each decision that has meaningful alternativ
|
||||
- [ ] If Step 4.5 classified the task as producer, the `## Contract` section exists and points at a contract file
|
||||
- [ ] If Step 4.5 classified the task as consumer, `### Document Dependencies` lists the relevant contract file
|
||||
- [ ] If Step 4.5 flagged a layout delta, the task's Scope.Included names the `module-layout.md` edit
|
||||
- [ ] If Step 4.5 flagged an ADR conflict, the task is either re-scoped (A), explicitly blocked on a supersede ADR (B), or parked in backlog (C) — never silently bypassed
|
||||
- [ ] If Step 4.5 flagged ADR drift, the task spec has an `### ADR Impact` section listing the affected ADR(s)
|
||||
- [ ] If Step 4.5 flagged ADR alignment, the task spec has an `### ADR Compliance` section citing the implemented ADR(s)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ disable-model-invocation: true
|
||||
|
||||
# Solution Planning
|
||||
|
||||
Decompose a problem and solution into architecture, data model, deployment plan, system flows, components, tests, and work item epics through a systematic 6-step workflow.
|
||||
Decompose a problem and solution into architecture, data model, deployment plan, system flows, components, ADRs, tests, and work item epics through a systematic workflow with seven step files (1, 2, 3, 4, 4.5, 5, 6) plus a Final quality checklist.
|
||||
|
||||
## Core Principles
|
||||
|
||||
@@ -55,7 +55,7 @@ Read `steps/01_artifact-management.md` for directory structure, save timing, sav
|
||||
|
||||
## Progress Tracking
|
||||
|
||||
At the start of execution, create a TodoWrite with all steps (1 through 6 plus Final). Update status as each step completes.
|
||||
At the start of execution, create a TodoWrite with all steps (1, 2, 3, 4, 4.5, 5, 6 plus Final). Update status as each step completes. The fractional Step 4.5 (ADR Capture) sits between Architecture Review (Step 4) and Test Specifications (Step 5).
|
||||
|
||||
## Workflow
|
||||
|
||||
@@ -85,6 +85,16 @@ Read and follow `steps/04_review-risk.md`.
|
||||
|
||||
---
|
||||
|
||||
### Step 4.5: Architecture Decision Records (ADRs)
|
||||
|
||||
Read and follow `steps/04-5_adr-capture.md`.
|
||||
|
||||
This step captures the architecture and tech-stack decisions that were made (or revised) in Steps 2–4 as durable, dated, immutable records under `_docs/02_document/adr/`. ADRs are the single thing in `_docs/` that explain the **why** of each major decision after the conversation history is gone. They are consumed by `decompose` (when bootstrapping module layout), `new-task` (when assessing a new feature against existing decisions), `refactor` (when proposing replacements), and any future code-review cycle that needs to confirm a structural choice was deliberate.
|
||||
|
||||
This step is **BLOCKING**: the ADR set must be reviewed and confirmed by the user before Step 5 begins.
|
||||
|
||||
---
|
||||
|
||||
### Step 5: Test Specifications
|
||||
|
||||
Read and follow `steps/05_test-specifications.md`.
|
||||
@@ -120,7 +130,7 @@ Read and follow `steps/07_quality-checklist.md`.
|
||||
|-----------|--------|
|
||||
| Missing acceptance_criteria.md, restrictions.md, or input_data/ | **STOP** — planning cannot proceed |
|
||||
| Ambiguous requirements | ASK user |
|
||||
| Input data coverage below 75% | Search internet for supplementary data, ASK user to validate |
|
||||
| Input data coverage below the canonical threshold (`cursor-meta.mdc` Quality Thresholds) | Search internet for supplementary data, ASK user to validate |
|
||||
| Technology choice with multiple valid options | ASK user |
|
||||
| Component naming | PROCEED, confirm at next BLOCKING gate |
|
||||
| File structure within templates | PROCEED |
|
||||
@@ -146,6 +156,8 @@ Read and follow `steps/07_quality-checklist.md`.
|
||||
│ [BLOCKING: user confirms components] │
|
||||
│ 4. Review & Risk → risk register, iterations │
|
||||
│ [BLOCKING: user confirms mitigations] │
|
||||
│ 4.5 ADR Capture → _docs/02_document/adr/NNN_*.md │
|
||||
│ [BLOCKING: user confirms ADR set] │
|
||||
│ 5. Test Specifications → per-component test specs │
|
||||
│ 6. Work Item Epics → epic per component + bootstrap │
|
||||
│ ───────────────────────────────────────────────── │
|
||||
|
||||
@@ -26,6 +26,10 @@ DOCUMENT_DIR/
|
||||
│ └── deployment_procedures.md
|
||||
├── risk_mitigations.md
|
||||
├── risk_mitigations_02.md (iterative, ## as sequence)
|
||||
├── adr/
|
||||
│ ├── 001_[decision_slug].md
|
||||
│ ├── 002_[decision_slug].md
|
||||
│ └── ...
|
||||
├── components/
|
||||
│ ├── 01_[name]/
|
||||
│ │ ├── description.md
|
||||
@@ -66,6 +70,8 @@ DOCUMENT_DIR/
|
||||
| Step 3 | Common helpers generated | `common-helpers/[##]_helper_[name].md` |
|
||||
| Step 3 | Diagrams generated | `diagrams/` |
|
||||
| Step 4 | Risk assessment complete | `risk_mitigations.md` |
|
||||
| Step 4.5 | Each ADR captured | `adr/NNN_[decision_slug].md` |
|
||||
| Step 4.5 | ADR index updated | `adr/README.md` |
|
||||
| Step 5 | Tests written per component | `components/[##]_[name]/tests.md` |
|
||||
| Step 6 | Epics created in work item tracker | Tracker via MCP |
|
||||
| Final | All steps complete | `FINAL_report.md` |
|
||||
@@ -85,3 +91,15 @@ If DOCUMENT_DIR already contains artifacts:
|
||||
2. Identify the last completed step based on which artifacts exist
|
||||
3. Resume from the next incomplete step
|
||||
4. Inform the user which steps are being skipped
|
||||
|
||||
#### Step 4.5 (ADR Capture) resumption rule
|
||||
|
||||
ADR files have a `Status` field that disambiguates "step in progress" from "step done":
|
||||
|
||||
- `Status: Proposed` → Step 4.5 is **in progress**. The user has not yet hit the BLOCKING gate (or hit it and chose B/C/D, which kept files at `Proposed`). Resume Step 4.5 at Phase 4.5f and re-present the BLOCKING Choose to the user. Do NOT skip to Step 5.
|
||||
- `Status: Accepted` AND `adr/README.md` index exists AND every Accepted ADR is referenced in the index → Step 4.5 is **done**. Skip to Step 5.
|
||||
- `Status: Accepted` but `adr/README.md` is missing or out of date → Step 4.5 is **partially complete**. Resume at Phase 4.5d (Maintain the ADR Index) before moving on.
|
||||
- Mixed `Proposed` + `Accepted` files in the same directory → Step 4.5 is **in progress** with prior partial confirmations. Resume at Phase 4.5f and re-present only the still-`Proposed` ADRs.
|
||||
- Empty `adr/` directory or no `adr/` directory → Step 4.5 has not started yet. Begin at Phase 4.5a.
|
||||
|
||||
The `Date` field on every Accepted ADR is the date the user confirmed it; do not regenerate it during resumption.
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
# Step 4.5: Architecture Decision Records (ADRs)
|
||||
|
||||
**Role**: Architect / technical writer
|
||||
**Goal**: Capture every major architecture, tech-stack, data-model, and integration decision made during Steps 2–4 as a durable, dated, immutable record under `_docs/02_document/adr/`.
|
||||
**Constraints**: ADRs only — do not re-open architecture; do not make new decisions in this step. Document what has been decided, not what is still open.
|
||||
|
||||
ADRs are the single thing in `_docs/` that explains the **why** of each major decision after the conversation history is gone. They are consumed by:
|
||||
|
||||
- `decompose` Step 1.5 (`steps/01-5_module-layout.md`) — every Accepted ADR is cross-checked against the module-layout proposal; conflicts trigger an explicit Choose between supersede / exception / re-open.
|
||||
- `new-task` Step 4.5 (`SKILL.md` § "Step 4.5: Contract & Layout Check") — every new task is classified against Accepted ADRs as Conflict / Drift / Aligned; conflicts STOP the task with a Choose A/B/C; drift adds an `### ADR Impact` section; alignment adds an `### ADR Compliance` section.
|
||||
- `refactor` Phase 2b.1 (`phases/02-analysis.md`) — every Accepted ADR is diffed against the proposed roadmap; Violations trigger a BLOCKING supersede gate that produces a `supersede_adr_NNN.md` task before any refactor task is created.
|
||||
- `code-review` Phase 7 (`SKILL.md` § "Phase 7: Architecture Compliance") — every changed-files batch is checked against Accepted ADRs; ADR-Violation findings are Critical, ADR-Drift findings are High.
|
||||
|
||||
Discipline that still relies on the human: when a downstream skill detects a Drift case, the resulting task spec MUST land its `## ADR Impact` / `## ADR Compliance` section; the implementer must address it; the next code-review batch then has the context it needs. Drift left undocumented is the silent-failure path — every consumer hook above is designed to make it visible.
|
||||
|
||||
## Inputs
|
||||
|
||||
- `_docs/02_document/architecture.md` (incl. confirmed `## Architecture Vision`)
|
||||
- `_docs/02_document/glossary.md`
|
||||
- `_docs/02_document/data_model.md`
|
||||
- `_docs/02_document/system-flows.md`
|
||||
- `_docs/02_document/risk_mitigations.md` (and any `risk_mitigations_NN.md` iterations from Step 4)
|
||||
- `_docs/02_document/components/[##]_[name]/description.md`
|
||||
- `_docs/02_document/deployment/` (CI/CD, environments, observability)
|
||||
- `_docs/00_problem/restrictions.md` and `_docs/00_problem/acceptance_criteria.md` (each ADR must reference relevant constraints / AC by ID)
|
||||
- Optional: `_docs/01_solution/solution.md` and `_docs/01_solution/tech_stack.md` (research output)
|
||||
- Optional: `_docs/LESSONS.md` — surface any lesson categories of `architecture` / `dependencies` that bias the recommendation
|
||||
|
||||
## What is an ADR (and what is not)
|
||||
|
||||
Capture an ADR when **all** of the following hold:
|
||||
|
||||
1. The decision picks between two or more genuinely valid approaches with meaningful trade-offs.
|
||||
2. The decision has **downstream consequences** that other decisions, code, or tasks inherit from.
|
||||
3. The decision is **non-obvious** to a future reader who only sees the final code — they would ask "why was it built this way?" rather than discovering the answer by reading the source.
|
||||
|
||||
Do NOT create an ADR for:
|
||||
|
||||
- Naming, formatting, or purely cosmetic choices.
|
||||
- A choice that is fully implied by a single explicit restriction (`restrictions.md` is itself the record — link to it from the architecture doc instead).
|
||||
- A choice the team has not actually made yet — open questions live in `risk_mitigations.md` or `_docs/_process_leftovers/`, not in ADRs.
|
||||
- A technology selection where research already produced an exact-fit selection with one viable option (the research doc is the record — link to the relevant `solution_draft*.md` section).
|
||||
|
||||
## Process
|
||||
|
||||
### Phase 4.5a: Decision Inventory
|
||||
|
||||
Walk the inputs and list candidate decisions. For each candidate, record a one-liner:
|
||||
|
||||
```
|
||||
- [decision] — [trade-off summary] — [downstream consumers] — [evidence file:section]
|
||||
```
|
||||
|
||||
Inspect at minimum:
|
||||
|
||||
| Inspection target | Typical decisions surfaced |
|
||||
|-------------------|----------------------------|
|
||||
| `architecture.md` § layering | Layering style (clean vs hex vs n-tier), which layer owns transactions, how cross-cutting concerns enter |
|
||||
| `architecture.md` § Architecture Vision | The North Star principle (e.g., "edge-first, sync-second"); ADR captures the implication for one specific subsystem |
|
||||
| `data_model.md` | Datastore choice (Postgres vs Mongo), partitioning, soft vs hard deletes, schema evolution strategy |
|
||||
| `system-flows.md` | Sync vs async boundaries, idempotency strategy, retry policy ownership, error envelope shape |
|
||||
| `components/*/description.md` § interfaces | Public-API style (REST vs RPC vs event), versioning strategy, auth/authorization placement |
|
||||
| `deployment/containerization.md` | Single container vs sidecar vs init container, base image lineage |
|
||||
| `deployment/ci_cd_pipeline.md` | Trunk-based vs feature-branch, gate ordering, deploy strategy (blue-green / canary / all-at-once) |
|
||||
| `deployment/observability.md` | Logging stack, metric backend, sampling rate decisions, retention |
|
||||
| `risk_mitigations.md` | Risk-acceptance trade-offs (e.g., "we accept N% data loss in exchange for sub-100ms p99") |
|
||||
| Tech-stack from `_docs/01_solution/tech_stack.md` | Anything where research recorded ≥2 candidates and a winner |
|
||||
|
||||
Drop any candidate that fails the three "what is an ADR" criteria above. Keep the rest.
|
||||
|
||||
### Phase 4.5b: Numbering and Slugs
|
||||
|
||||
ADRs are numbered globally per project, monotonically, never re-used.
|
||||
|
||||
1. List existing files under `_docs/02_document/adr/` matching `^[0-9]{3}_.+\.md$`.
|
||||
2. The next ADR number is `max(existing) + 1`, zero-padded to 3 digits.
|
||||
3. The slug is kebab-case, ≤6 words, derived from the decision summary. Example: `001_use-postgres-for-transactional-data.md`, `004_event-driven-cross-component-comms.md`.
|
||||
|
||||
### Phase 4.5c: Render One ADR Per Decision
|
||||
|
||||
For each kept candidate, render the ADR using `templates/adr.md`. Required sections (do NOT omit any):
|
||||
|
||||
| Section | Content |
|
||||
|---------|---------|
|
||||
| **Number** | `NNN` |
|
||||
| **Title** | One-line decision statement (matches slug) |
|
||||
| **Status** | `Proposed` (only during Step 4.5 iteration) → `Accepted` (after user confirmation at the BLOCKING gate) |
|
||||
| **Date** | YYYY-MM-DD (the date the user confirmed) |
|
||||
| **Deciders** | The user (project owner) — the AI is not a decider |
|
||||
| **Context** | The problem this decision addresses, including links to AC IDs, restriction IDs, risks, and (where relevant) the research draft section |
|
||||
| **Decision** | The chosen approach in one sentence, then the supporting detail |
|
||||
| **Alternatives Considered** | Each alternative with a one-line "rejected because…" |
|
||||
| **Consequences** | Positive (what becomes easier / cheaper / faster) and negative (what becomes harder / locked in / costly to undo). Be honest — every decision has a downside. |
|
||||
| **Supersedes / Superseded by** | Empty initially; updated when a future ADR overturns this one |
|
||||
| **Evidence** | File-and-section pointers into `_docs/` showing where the decision is reflected (architecture.md § layering, components/02_*/description.md § interface, etc.) |
|
||||
|
||||
After rendering, write each file to `_docs/02_document/adr/NNN_<slug>.md`. Keep `Status: Proposed` until the BLOCKING gate.
|
||||
|
||||
### Phase 4.5d: Maintain the ADR Index
|
||||
|
||||
Write or update `_docs/02_document/adr/README.md` with this exact shape:
|
||||
|
||||
```markdown
|
||||
# Architecture Decision Records
|
||||
|
||||
This index lists every ADR for this project, in number order. ADRs are immutable once `Accepted` —
|
||||
new decisions that overturn a prior ADR are recorded as new ADRs whose `Supersedes` field points
|
||||
back, and the original ADR's `Superseded by` field is updated.
|
||||
|
||||
| # | Title | Status | Date | Supersedes |
|
||||
|---|-------|--------|------|------------|
|
||||
| 001 | Use Postgres for transactional data | Accepted | 2026-05-21 | — |
|
||||
| 002 | Event-driven cross-component comms | Accepted | 2026-05-21 | — |
|
||||
| ... | ... | ... | ... | ... |
|
||||
```
|
||||
|
||||
Sort by `#` ascending. Include all ADRs ever written, even superseded ones — the audit trail is the point.
|
||||
|
||||
### Phase 4.5e: Cross-Link from architecture.md
|
||||
|
||||
In `architecture.md`, every section that reflects an ADR decision gets a one-line trailing reference:
|
||||
|
||||
```markdown
|
||||
> See ADR 001 (Use Postgres for transactional data), ADR 003 (Event-driven cross-component comms).
|
||||
```
|
||||
|
||||
Place the reference at the end of the section, after the prose. This lets a future reader of `architecture.md` jump straight to the rationale.
|
||||
|
||||
### Phase 4.5f: BLOCKING Gate — User Confirmation
|
||||
|
||||
Present the ADR set to the user using the Choose format from `.cursor/skills/autodev/protocols.md` (or plain text if AskQuestion is unavailable):
|
||||
|
||||
```
|
||||
══════════════════════════════════════
|
||||
DECISION REQUIRED: ADR set captured (N records)
|
||||
══════════════════════════════════════
|
||||
001 — [title]
|
||||
002 — [title]
|
||||
...
|
||||
══════════════════════════════════════
|
||||
A) Accept all ADRs as written
|
||||
B) Edit specific ADRs (numbers and edits)
|
||||
C) Add a missed decision (description)
|
||||
D) Remove an ADR (number and reason)
|
||||
══════════════════════════════════════
|
||||
Recommendation: A — review the rendered set and confirm; corrections are quick on Round 2
|
||||
══════════════════════════════════════
|
||||
```
|
||||
|
||||
Loop:
|
||||
|
||||
- **A** → flip every ADR's `Status` from `Proposed` to `Accepted`, set `Date` to today's date, save, exit step.
|
||||
- **B** → apply edits, re-present the modified ADRs, loop.
|
||||
- **C** → run Phase 4.5a–4.5e for the missed decision only, append to the set, re-present, loop.
|
||||
- **D** → confirm with the user that the candidate fails the three "what is an ADR" criteria, remove the file, update the index, loop.
|
||||
|
||||
Do NOT mark `Accepted` without an explicit user A.
|
||||
|
||||
## Self-verification
|
||||
|
||||
- [ ] Every kept candidate from Phase 4.5a has a corresponding file under `adr/`
|
||||
- [ ] Every ADR has all required sections (none empty except `Supersedes` / `Superseded by`)
|
||||
- [ ] `Decision` sections are one-sentence-then-detail, not "we'll figure it out"
|
||||
- [ ] `Alternatives Considered` lists at least one rejected alternative per ADR
|
||||
- [ ] `Consequences` lists both positive AND negative consequences (an ADR with no negatives is suspect)
|
||||
- [ ] `Evidence` points at real `_docs/` sections that exist on disk
|
||||
- [ ] `adr/README.md` index lists every file in the directory and matches their `Status` / `Date`
|
||||
- [ ] `architecture.md` has a trailing `See ADR …` reference at every section that an ADR reflects
|
||||
- [ ] The user confirmed the set via Choose A; every ADR is `Accepted` with today's date
|
||||
|
||||
## Common mistakes
|
||||
|
||||
- **Re-opening architecture**: Step 4.5 records, it does not decide. If a candidate decision turns out to be unsettled, that's a Step 2 / Step 4 gap — return there, do not paper over it with a wishy-washy ADR.
|
||||
- **Decision-of-the-week**: do not write an ADR for every minor pattern choice. The bar is "non-obvious to a future reader". 5–15 ADRs is typical for a planning round; 40+ is over-capture.
|
||||
- **Negative consequences left empty**: every real decision has costs. If you cannot name one, the decision was not actually weighed.
|
||||
- **Vague evidence**: `architecture.md` is not enough — point at the specific section. `architecture.md § Layering` ≠ `architecture.md`.
|
||||
- **Numbering reuse**: never recycle a number from a deleted ADR. The audit trail is more important than tidy numbering.
|
||||
- **Superseding without recording**: when a later cycle overturns an ADR, the new ADR must point at the old one via `Supersedes`, AND the old ADR's `Superseded by` field must be updated. Index reflects both. (This is enforced when `decompose` or `refactor` later updates ADRs.)
|
||||
|
||||
## Escalation
|
||||
|
||||
| Situation | Action |
|
||||
|-----------|--------|
|
||||
| Candidate decision is unsettled (the team has not actually decided) | Return to the originating step (2 / 3 / 4); do NOT write a placeholder ADR |
|
||||
| Two candidates in Phase 4.5a turn out to be the same decision phrased differently | Merge into one ADR, list both phrasings in `Context` |
|
||||
| User picks D (remove an ADR) and the AI judges the decision is genuinely worth recording | Surface the disagreement, ASK why the user wants it removed, defer to user |
|
||||
| Existing `adr/` directory has files but `adr/README.md` is missing or stale | Rebuild the index from the directory before adding new ADRs |
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**Role**: Professional Quality Assurance Engineer
|
||||
|
||||
**Goal**: Write test specs for each component achieving minimum 75% acceptance criteria coverage
|
||||
**Goal**: Write test specs for each component achieving the canonical minimum acceptance-criteria coverage (currently 75% — see `.cursor/rules/cursor-meta.mdc` Quality Thresholds; do not restate a different number here)
|
||||
|
||||
**Constraints**: Test specs only — no test code. Each test must trace to an acceptance criterion.
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# ADR-{NNN}: {decision-title}
|
||||
|
||||
- **Status**: {Proposed | Accepted | Deprecated | Superseded}
|
||||
- **Date**: {YYYY-MM-DD}
|
||||
- **Deciders**: {user / project owner}
|
||||
- **Supersedes**: {ADR-NNN | —}
|
||||
- **Superseded by**: {ADR-NNN | —}
|
||||
|
||||
## Context
|
||||
|
||||
What problem does this decision address? Cite the relevant constraint(s), acceptance criterion / criteria, and risk(s) by ID.
|
||||
|
||||
- Acceptance criteria addressed: AC-{ID-1}, AC-{ID-2}
|
||||
- Restrictions addressed: R-{ID-1}, R-{ID-2}
|
||||
- Risks addressed: RISK-{ID-1}
|
||||
- Research source (if any): `_docs/01_solution/solution_draftN.md` § {section}
|
||||
|
||||
A short paragraph (3–6 sentences) explaining why a choice is required now and what makes it non-trivial. Do not pre-announce the decision here — that goes in `Decision`. Focus on the forces at play (load, scale, team familiarity, hardware constraints, regulatory drivers, third-party limits).
|
||||
|
||||
## Decision
|
||||
|
||||
One declarative sentence: **"We will …"** Then 1–3 paragraphs of supporting detail explaining how the decision will be implemented at the boundaries between components.
|
||||
|
||||
Be specific. "We will use Postgres" is too thin; "We will use Postgres 16 with logical replication for read scaling, restricting JSONB columns to top-level metadata only, with all transactional data in normalized tables" is the right resolution.
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
| Alternative | Rejected because |
|
||||
|-------------|------------------|
|
||||
| {Alt 1 — short label} | {one line: the cost / mismatch / risk that ruled it out, ideally referencing a measurable criterion} |
|
||||
| {Alt 2 — short label} | {one line} |
|
||||
| {Alt 3 — short label} | {one line} |
|
||||
|
||||
At least one rejected alternative is mandatory. If only one option was ever considered, this is not an ADR — link to the source restriction or research selection from the parent doc instead.
|
||||
|
||||
## Consequences
|
||||
|
||||
### Positive
|
||||
|
||||
- {What becomes easier / cheaper / faster, with concrete examples where possible}
|
||||
- {…}
|
||||
|
||||
### Negative
|
||||
|
||||
- {What becomes harder / locked in / costly to undo}
|
||||
- {…}
|
||||
|
||||
Every real decision has both. If the negatives section is hard to fill, the alternatives were probably not weighed seriously — return to the prior step.
|
||||
|
||||
### Neutral / Open
|
||||
|
||||
- {What is unchanged but worth flagging for future readers (e.g., "this does not change the auth boundary; auth remains in component 02_user_management as decided in ADR-003")}
|
||||
|
||||
## Evidence
|
||||
|
||||
Where this decision is reflected on disk. Use `file:section` links so future readers can jump.
|
||||
|
||||
- `_docs/02_document/architecture.md` § {section}
|
||||
- `_docs/02_document/data_model.md` § {section}
|
||||
- `_docs/02_document/components/{##_name}/description.md` § {section}
|
||||
- `_docs/02_document/system-flows.md` § {flow name}
|
||||
- `_docs/02_document/deployment/{file}.md` § {section}
|
||||
- {add more as needed}
|
||||
|
||||
## Notes
|
||||
|
||||
Optional. Use for caveats that did not fit above, links to external research, or follow-ups that the team agreed to revisit on a known trigger ("re-evaluate after 6 months in production" / "re-evaluate when load exceeds 10× baseline").
|
||||
@@ -1,6 +1,6 @@
|
||||
# Final Planning Report Template
|
||||
|
||||
Use this template after completing all 6 steps and the quality checklist. Save as `_docs/02_document/FINAL_report.md`.
|
||||
Use this template after completing all steps (1, 2, 3, 4, 4.5, 5, 6) and the quality checklist. Save as `_docs/02_document/FINAL_report.md`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -39,6 +39,44 @@ Write `RUN_DIR/analysis/research_findings.md`:
|
||||
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
|
||||
|
||||
### 2b.1. ADR Superseding Gate (BLOCKING)
|
||||
|
||||
A refactor that improves code structure while overturning a documented architecture decision is the silent-drift class the project repeatedly burns on (see `meta-rule.mdc` § GPS-passthrough postmortem and the auto-lessons it produced). This gate makes drift visible and forces a deliberate ADR update.
|
||||
|
||||
1. **List candidate ADRs**: read every `Status: Accepted` file in `_docs/02_document/adr/`. If the directory does not exist or contains only the index, log `No ADRs in scope` to `RUN_DIR/analysis/adr_impact.md` and skip the rest of this gate.
|
||||
2. **Diff each candidate against the proposed refactor roadmap**: for each ADR, ask the same two questions as code-review Phase 7:
|
||||
- **Violation**: does any roadmap item do the *opposite* of the ADR's `Decision`?
|
||||
- **Drift**: does any roadmap item materially affect the ADR's `Consequences` (positive or negative) without contradicting the Decision outright?
|
||||
3. **Classify each impacted ADR** in `RUN_DIR/analysis/adr_impact.md`:
|
||||
|
||||
| ADR | Roadmap item | Impact | Required action |
|
||||
|-----|--------------|--------|-----------------|
|
||||
| NNN | `roadmap-item-NN` | Violation / Drift / Aligned | (filled by Choose A/B/C below) |
|
||||
|
||||
4. **For every Violation row, present a BLOCKING Choose**:
|
||||
|
||||
```
|
||||
══════════════════════════════════════
|
||||
DECISION REQUIRED: Refactor would violate ADR-NNN (<title>)
|
||||
══════════════════════════════════════
|
||||
A) Update the ADR via supersede: the refactor produces a NEW ADR
|
||||
(`Supersedes: NNN`) capturing the new Decision, and ADR-NNN's
|
||||
`Superseded by` field is updated. The supersede ADR is itself a
|
||||
deliverable of this refactor run (added to RUN_DIR/analysis/adr_impact.md
|
||||
and to TASKS_DIR as a task) and must be `Accepted` before Phase 4.
|
||||
B) Reduce the refactor scope to NOT violate ADR-NNN
|
||||
C) Re-evaluate ADR-NNN: keep the refactor but only after ADR-NNN is
|
||||
formally re-opened in a new /plan Step 4.5 round
|
||||
══════════════════════════════════════
|
||||
Recommendation: A — supersede is the only path that keeps the audit
|
||||
trail intact while letting the refactor land
|
||||
══════════════════════════════════════
|
||||
```
|
||||
|
||||
5. **For every Drift row**: do not block, but the roadmap item must include a `## ADR Impact` section in its task spec citing the affected ADR(s). The implementer surfaces this at code-review Phase 7, which would otherwise classify the change as ADR-Drift (High) without context.
|
||||
6. **For every Aligned row**: cite the ADR in the roadmap item's task spec under `## ADR Compliance`. No further action.
|
||||
7. **Self-supersede deliverable**: any Choose A path adds a `[##]_supersede_adr_NNN.md` task file to the refactor run's TASKS_DIR with the new ADR text drafted (using `.cursor/skills/plan/templates/adr.md`). The task's only Acceptance Criterion is "ADR file exists at `_docs/02_document/adr/<next>_<slug>.md` with `Status: Accepted`, ADR-NNN's `Superseded by` field updated, and `_docs/02_document/adr/README.md` index reflects both."
|
||||
|
||||
Present optional hardening tracks for user to include in the roadmap:
|
||||
|
||||
```
|
||||
@@ -67,6 +105,8 @@ Write `RUN_DIR/analysis/refactoring_roadmap.md`:
|
||||
|
||||
**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.
|
||||
|
||||
**BLOCKING ADR-supersede gate**: Before 2c and 2d, every Violation row in `RUN_DIR/analysis/adr_impact.md` (from 2b.1) must be resolved via Choose A, B, or C. A Violation row with no chosen path blocks task creation.
|
||||
|
||||
## 2c. Create Epic
|
||||
|
||||
Create a work item tracker epic for this refactoring run:
|
||||
@@ -111,6 +151,10 @@ Convert the finalized `RUN_DIR/list-of-changes.md` into implementable task files
|
||||
- [ ] Task dependencies are consistent (no circular dependencies)
|
||||
- [ ] `_dependencies_table.md` includes all refactoring tasks
|
||||
- [ ] Every task has a work item ticket (or PENDING placeholder)
|
||||
- [ ] If `_docs/02_document/adr/` exists with Accepted ADRs, `RUN_DIR/analysis/adr_impact.md` has been written and every Violation row is resolved (A/B/C) — no implicit overrides
|
||||
- [ ] For every Violation resolved via Choose A, a `[##]_supersede_adr_NNN.md` task exists in TASKS_DIR with the drafted supersede ADR
|
||||
- [ ] For every Drift row, the corresponding roadmap-item task spec has a `## ADR Impact` section
|
||||
- [ ] For every Aligned row, the corresponding roadmap-item task spec has a `## ADR Compliance` section
|
||||
|
||||
**Save action**: Write analysis artifacts to RUN_DIR, task files to TASKS_DIR
|
||||
|
||||
|
||||
@@ -15,9 +15,9 @@ Before designing or implementing any new tests, check what already exists:
|
||||
1. Scan the project for existing test files (unit tests, integration tests, blackbox tests)
|
||||
2. Run the existing test suite — record pass/fail counts
|
||||
3. Measure current coverage against the areas being refactored (from `RUN_DIR/list-of-changes.md` file paths)
|
||||
4. Assess coverage against thresholds:
|
||||
4. Assess coverage against thresholds (canonical: see `.cursor/rules/cursor-meta.mdc` Quality Thresholds — never hardcode a different number):
|
||||
- Minimum overall coverage: 75%
|
||||
- Critical path coverage: 90%
|
||||
- Critical path coverage: **90% floor / 100% aim** — 90% is the enforcement floor (blocks Phase 4 if not met); 100% is the aspirational target. Refactors are NOT permitted to drop below 90% on the critical paths covered by the in-scope changes.
|
||||
- All public APIs must have blackbox tests
|
||||
- All error handling paths must be tested
|
||||
|
||||
@@ -47,7 +47,7 @@ For each uncovered critical area, write test specs to `RUN_DIR/test_specs/[##]_[
|
||||
4. Document any discovered issues
|
||||
|
||||
**Self-verification**:
|
||||
- [ ] Coverage requirements met (75% overall, 90% critical paths) across existing + new tests
|
||||
- [ ] Coverage requirements met (75% overall, 90% critical-path floor — 100% aim — per canonical `cursor-meta.mdc` Quality Thresholds) across existing + new tests
|
||||
- [ ] All tests pass on current codebase
|
||||
- [ ] All public APIs in refactoring scope have blackbox tests
|
||||
- [ ] Test data fixtures are configured
|
||||
|
||||
@@ -45,7 +45,7 @@ Write `RUN_DIR/test_sync/new_tests.md`:
|
||||
- [ ] All obsolete tests removed or merged
|
||||
- [ ] All pre-existing tests pass after updates
|
||||
- [ ] New code from Phase 4 has test coverage
|
||||
- [ ] Overall coverage meets or exceeds Phase 3 baseline (75% overall, 90% critical paths)
|
||||
- [ ] Overall coverage meets or exceeds Phase 3 baseline (75% overall, 90% critical-path floor / 100% aim — per `.cursor/rules/cursor-meta.mdc` Quality Thresholds)
|
||||
- [ ] No tests reference removed or renamed code
|
||||
|
||||
**Save action**: Write test_sync artifacts; implemented tests go into the project's test folder
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
---
|
||||
name: release
|
||||
description: |
|
||||
Executes the deployment plan produced by /deploy against a target environment.
|
||||
Closes the loop between "we have a plan" and "the new version is running in production with a verdict on disk."
|
||||
6-phase workflow: pre-release gate, strategy select, execute, smoke test, watch window, commit-or-rollback.
|
||||
Outputs _docs/04_release/release_<version>.md with a definitive Released / Rolled-Back / Aborted verdict.
|
||||
Trigger phrases:
|
||||
- "release", "ship", "go live", "release this version"
|
||||
- "deploy to prod", "promote to staging", "roll out"
|
||||
- "rollback", "abort the release"
|
||||
category: ship
|
||||
tags: [release, deployment, rollback, smoke-test, observability, production]
|
||||
disable-model-invocation: true
|
||||
---
|
||||
|
||||
# Release Execution
|
||||
|
||||
The `/deploy` skill produces a plan and scripts. The `/release` skill **runs** them, verifies the live system, watches it for a defined window, and produces a definitive verdict on disk.
|
||||
|
||||
## Core Principles
|
||||
|
||||
- **Real execution, not simulation**: every phase must actually run against the target environment. If a phase cannot be executed (missing scripts, no SSH access, disabled secrets, registry auth failure), STOP — do not pretend a step succeeded. See `meta-rule.mdc` § "Real Results, Not Simulated Ones".
|
||||
- **Verifiable rollback path**: the release does not start until rollback is proven viable for this version. "We can roll back" without evidence is not a rollback path.
|
||||
- **Quiet failure is a release failure**: a deploy script that exits 0 but emits no observable signal in the watch window is treated as a regression, not a success.
|
||||
- **One release per invocation**: a single `/release` execution targets exactly one version against exactly one environment. Multi-stage promotion (staging → prod) is two invocations, not one.
|
||||
- **Never skip the watch window**: even successful deploys can degrade after 5–60 minutes (cache warm-up, scheduled jobs, downstream backpressure). The watch window is mandatory.
|
||||
- **Autonomous rollback on hard regressions**: critical health-check failure, error-rate spike above threshold, or smoke-test failure → automatic rollback. Soft regressions (latency drift, capacity warnings) escalate to the user.
|
||||
|
||||
## Context Resolution
|
||||
|
||||
Fixed paths:
|
||||
|
||||
- DEPLOY_DIR: `_docs/04_deploy/`
|
||||
- RELEASE_DIR: `_docs/04_release/`
|
||||
- SCRIPTS_DIR: `scripts/`
|
||||
- DEPLOY_SCRIPT: `scripts/deploy.sh`
|
||||
- HEALTH_SCRIPT: `scripts/health-check.sh`
|
||||
- ENV_TEMPLATE: `.env.example`
|
||||
- OBSERVABILITY_DOC: `_docs/04_deploy/observability.md`
|
||||
- ENVIRONMENT_DOC: `_docs/04_deploy/environment_strategy.md`
|
||||
- PROCEDURES_DOC: `_docs/04_deploy/deployment_procedures.md`
|
||||
- ARCHITECTURE: `_docs/02_document/architecture.md`
|
||||
- RESTRICTIONS: `_docs/00_problem/restrictions.md`
|
||||
|
||||
Announce the resolved paths and the **target environment + version + strategy** to the user before any phase that touches the live system.
|
||||
|
||||
## Inputs (BLOCKING prerequisites)
|
||||
|
||||
| Input | Required | Source |
|
||||
|-------|----------|--------|
|
||||
| Target environment | Yes — ASK user | `environment_strategy.md` enumerates valid options |
|
||||
| Target version / image tag | Yes — ASK user | Must exist in the registry; verified in Phase 1 |
|
||||
| Rollback target version | Yes — ASK user | Defaults to currently-deployed version if discoverable |
|
||||
| `scripts/deploy.sh` | Yes | Produced by `/deploy` Step 7. STOP if missing → run `/deploy` first |
|
||||
| `scripts/health-check.sh` | Yes | Same |
|
||||
| `_docs/04_deploy/deployment_procedures.md` | Yes | Defines per-environment runbook, manual approval rules, change-window restrictions |
|
||||
| `_docs/04_deploy/observability.md` | Yes | Defines watch metrics, thresholds, and dashboards |
|
||||
| `_docs/04_deploy/environment_strategy.md` | Yes | Defines target hostnames, registries, secrets, deploy strategy per env |
|
||||
|
||||
## Outputs
|
||||
|
||||
```
|
||||
RELEASE_DIR/
|
||||
├── release_<version>_<env>_<YYYY-MM-DD-HHmm>.md (mandatory; one per invocation)
|
||||
├── rollback_<version>_<env>_<YYYY-MM-DD-HHmm>.md (only when rollback fires; pairs with the release file)
|
||||
└── manual_approvals/
|
||||
└── approval_<version>_<env>.md (when restrictions require manual approval, written before Phase 3)
|
||||
```
|
||||
|
||||
The release report (`templates/release-report.md`) is appended to as each phase completes — it is durable across phase failures and reflects partial progress so the next operator can resume or audit.
|
||||
|
||||
## Phases
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────┐
|
||||
│ Release Execution (6-Phase Method) │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ PREREQ: deploy artifacts on disk; tests green at HEAD │
|
||||
│ │
|
||||
│ 1. Pre-Release Gate → AC + change summary + readiness │
|
||||
│ [BLOCKING: user confirms or aborts] │
|
||||
│ 2. Strategy Select → all-at-once / blue-green / canary │
|
||||
│ [BLOCKING: user picks strategy] │
|
||||
│ 3. Execute → run deploy.sh, capture exit + logs │
|
||||
│ [AUTO-ROLLBACK on non-zero exit] │
|
||||
│ 4. Smoke Test → /test-run prod-smoke in target env │
|
||||
│ [AUTO-ROLLBACK on failure] │
|
||||
│ 5. Watch Window → poll observability for N minutes │
|
||||
│ [AUTO-ROLLBACK on hard threshold breach] │
|
||||
│ 6. Commit or Rollback → finalize verdict, update tracker │
|
||||
│ [BLOCKING: user confirms only if soft regression escalated] │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ Verdicts: Released · Rolled-Back · Aborted │
|
||||
└────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Phase 1: Pre-Release Gate
|
||||
|
||||
**Goal**: Refuse to start if the system is not ready for a real release.
|
||||
|
||||
1. **Acceptance criteria check**: read `_docs/00_problem/acceptance_criteria.md`. If any AC is marked unmet OR if any AC has no associated test marked `Passed` in the latest `test-run` report, STOP and surface the unmet items. Do not let the user override with "ship anyway" without a recorded reason in the release report.
|
||||
2. **Test status check**: read the most recent `_docs/06_metrics/perf_*.md` (if perf is required by restrictions) and the latest functional test report. Any failing or skipped test that maps to a critical-path AC blocks the release.
|
||||
3. **Change summary**: read the git log between the version-tag-of-last-release and HEAD (or, if no prior release exists, from the project root commit). Render a short list grouped by component: features, fixes, breaking changes, security fixes. Cross-reference against the latest implementation reports under `_docs/03_implementation/`.
|
||||
4. **Rollback readiness**:
|
||||
- Confirm the previous version's image is still pullable from the registry (do not deploy without this).
|
||||
- Confirm `scripts/deploy.sh --rollback` works as documented (read the script; if `--rollback` flag is missing, STOP — that is a deploy-skill bug).
|
||||
- Confirm a rollback target exists (e.g., previously-deployed image tag) and is recorded in the release report under `Rollback Plan`.
|
||||
5. **Restrictions**: read `_docs/00_problem/restrictions.md` for change-window rules, manual-approval rules, blackout windows, regulatory requirements (e.g., 4-eyes review, ITAR controls). If any apply, gate accordingly — write a `manual_approvals/approval_<version>_<env>.md` file once received.
|
||||
6. **Tracker check**: list tracker tickets in the release scope (per `tracker.mdc` rules). Any ticket still in `In Progress` or `Code Review` that maps to a change in the release scope blocks Phase 1. Move-and-deploy is not allowed.
|
||||
|
||||
**BLOCKING gate**: present the assembled summary to the user using Choose A/B/C:
|
||||
|
||||
```
|
||||
══════════════════════════════════════
|
||||
PRE-RELEASE GATE
|
||||
══════════════════════════════════════
|
||||
Target env: {env}
|
||||
Target version: {version} ({git-sha})
|
||||
Rollback target: {previous-version}
|
||||
Changes: N tickets, M components
|
||||
- {summary list}
|
||||
Open risks: {summary or "none"}
|
||||
Blocking issues: {summary or "none"}
|
||||
══════════════════════════════════════
|
||||
A) Proceed to Strategy Select
|
||||
B) Abort — fix blocking issue and re-invoke
|
||||
C) Edit release scope — exclude a ticket and reassemble
|
||||
══════════════════════════════════════
|
||||
```
|
||||
|
||||
If A → write Phase 1 section to release report, proceed. If B → write `Aborted` verdict to release report with reason, exit. If C → loop back into Phase 1 with edited scope.
|
||||
|
||||
### Phase 2: Strategy Select
|
||||
|
||||
**Goal**: Pick the deployment strategy that fits the change risk and environment capability.
|
||||
|
||||
Read `environment_strategy.md` and `deployment_procedures.md` to learn which strategies the target env supports. Strategies and when each is appropriate:
|
||||
|
||||
| Strategy | When to pick | Risk if wrong |
|
||||
|----------|--------------|---------------|
|
||||
| **all-at-once** | Internal tools, low traffic, well-rehearsed change, env supports nothing else | All users hit the new version simultaneously — bug blast radius is 100% |
|
||||
| **blue-green** | Stateless services with a load balancer, env has dual-stack capability | Cutover is binary — observability must be ready to detect issues fast |
|
||||
| **canary** | Customer-facing, traffic-tier load balancer in place, gradual rollout possible | Canary metric thresholds must be well-tuned or canary fails for harmless reasons |
|
||||
| **manual** | Non-automatable env (one-off VMs, regulated infrastructure, non-Docker host) | The whole release becomes a runbook and the watch window phases are operator-driven; the release skill records but does not execute |
|
||||
|
||||
Recommend a default based on:
|
||||
- Risk level inferred from change summary (any breaking change → bias toward canary or blue-green)
|
||||
- Restrictions (e.g., regulatory rules forcing manual approval at each step)
|
||||
- Environment capability (some envs may only support all-at-once)
|
||||
|
||||
**BLOCKING gate**: Choose A/B/C/D between strategies. Record the choice in the release report.
|
||||
|
||||
### Phase 3: Execute
|
||||
|
||||
**Goal**: Actually run the deploy. Capture exit code and full stdout/stderr.
|
||||
|
||||
1. Validate environment file (`.env`) exists, all required vars from `.env.example` are set, no placeholder secrets remain.
|
||||
2. Source the env file and run `scripts/deploy.sh` against the target host. The script produced by `/deploy` Step 7 is the point of execution; do NOT bypass it. If a strategy-specific flag is needed (e.g., `--canary 5%`), pass it through.
|
||||
3. Stream stdout/stderr to the release report, with timestamps, in a fenced code block under `## Phase 3: Execute`.
|
||||
4. Capture exit code.
|
||||
5. **AUTO-ROLLBACK trigger**: non-zero exit code → immediately invoke Phase 6 with verdict `Rolled-Back: deploy script failure`. Do NOT continue to Phase 4.
|
||||
|
||||
If `deploy.sh` emits no output for more than the configured idle threshold (default 5 minutes; check `deployment_procedures.md` for an explicit value), treat it as hung — capture a snapshot of what's running on the target, kill the script, and AUTO-ROLLBACK with reason `Deploy hung — manual investigation required`.
|
||||
|
||||
**Manual strategy**: if Phase 2 picked `manual`, write a checklist of operator steps from `deployment_procedures.md` to the release report and pause until the user types `done` or `failed`. Phase 3 then records the user's report verbatim.
|
||||
|
||||
### Phase 4: Smoke Test
|
||||
|
||||
**Goal**: Verify the new version is *actually serving traffic correctly* in the target environment.
|
||||
|
||||
1. Resolve the smoke-test command from `_docs/02_document/tests/blackbox-tests.md` § Production Smoke Tests, OR delegate to `/test-run` in `--prod-smoke` mode against the target environment.
|
||||
2. The smoke-test set must (a) hit each public endpoint of each component, (b) include at least one read AND one write per public endpoint where applicable, and (c) complete in under 5 minutes total.
|
||||
3. Capture pass/fail per case to the release report.
|
||||
4. **AUTO-ROLLBACK trigger**: any smoke-test failure → invoke Phase 6 with verdict `Rolled-Back: smoke test failure: <test-name>`.
|
||||
|
||||
If smoke tests are **missing** for the target environment (no production-mode test set), STOP — write a leftover entry to `_docs/_process_leftovers/` per `tracker.mdc`, do not proceed to watch window without smoke coverage. Write `Aborted: smoke tests missing for prod-mode target` and ASK the user.
|
||||
|
||||
### Phase 5: Watch Window
|
||||
|
||||
**Goal**: Observe the live system for a defined window to catch latent regressions.
|
||||
|
||||
1. Read `observability.md` for the project's metrics, dashboards, and threshold definitions. Required watch metrics for any production target (per cursor-meta convention) include error rate, request rate, p99 latency, and saturation (CPU/memory/queue-depth).
|
||||
2. Compute the watch-window duration from `deployment_procedures.md`. If unspecified, default to **15 minutes** for staging and **60 minutes** for production.
|
||||
3. Poll the observability backend at 1-minute intervals (or the configured cadence). For each interval, record metric snapshots to the release report.
|
||||
4. Threshold rules:
|
||||
- **Hard breach** (auto-rollback): error-rate ≥ 2× baseline, p99 latency ≥ 3× baseline, any health-check failure persisting for 2 consecutive intervals.
|
||||
- **Soft breach** (escalate): metric drift between 1.5× and 2× baseline, single-interval health blip, queue-depth steady but elevated.
|
||||
- **No data** (escalate): if metrics are not flowing within the first 3 minutes, treat the absence as a hard breach — observability is itself broken.
|
||||
5. **AUTO-ROLLBACK trigger**: hard breach at any interval. Move to Phase 6 with verdict `Rolled-Back: <metric> breached <multiplier>× baseline at T+<minutes>`.
|
||||
6. **ESCALATE trigger**: soft breach. Pause polling, surface the metric, and ask the user A/B/C:
|
||||
- A) Continue watch — accept current drift, keep polling
|
||||
- B) Roll back now — treat soft drift as hard
|
||||
- C) Extend watch window by N minutes
|
||||
7. End of watch window with no breach → proceed to Phase 6.
|
||||
|
||||
The watch window cannot be skipped. If the user explicitly demands skipping (e.g., emergency rollforward), record the override reason in the release report and continue, but mark the verdict as `Released-with-override` — this triggers an automatic incident retrospective per `retrospective/SKILL.md`.
|
||||
|
||||
### Phase 6: Commit or Rollback
|
||||
|
||||
**Goal**: Finalize the release with a definitive verdict on disk.
|
||||
|
||||
**Path A — Commit (clean release)**:
|
||||
1. Update tracker tickets: every ticket in scope moves to `Released` (or `Done`, per project convention defined in `tracker.mdc` / `_docs/_repo-config.yaml`).
|
||||
2. Tag the git HEAD with `release/<version>` (or the project's tag convention from `deployment_procedures.md`).
|
||||
3. Write the final `Released` verdict to the release report with a summary table.
|
||||
4. Trigger `/retrospective --cycle-end` with this release as the cycle terminus.
|
||||
5. Auto-chain to autodev's next step (Retrospective in greenfield, or feature-cycle loop start in existing-code).
|
||||
|
||||
**Path B — Rollback (auto-fired or user-elected)**:
|
||||
1. Run `scripts/deploy.sh --rollback` with the rollback target captured in Phase 1.
|
||||
2. Stream output to a new file `RELEASE_DIR/rollback_<version>_<env>_<YYYY-MM-DD-HHmm>.md` AND append a summary to the original release report under `## Rollback`.
|
||||
3. Re-run Phase 4 (smoke test) and a 5-minute mini watch window against the rolled-back version. If THAT also fails, escalate immediately — the system is in an unknown state and needs human takeover.
|
||||
4. Update tracker tickets back to `Ready for Release` (or the project's pre-release status).
|
||||
5. Write the final `Rolled-Back` verdict with full reason chain.
|
||||
6. Auto-trigger `/retrospective --incident` with this release as the incident anchor (per `retrospective/SKILL.md` incident mode).
|
||||
7. Do NOT auto-chain to anything else — the user owns the next step.
|
||||
|
||||
**Path C — Aborted**:
|
||||
Reached only via Phase 1 Choose B, Phase 4 smoke-tests-missing escalation, or any phase that detects a precondition violation. Write `Aborted: <reason>` to the release report. Do not auto-chain.
|
||||
|
||||
## Self-verification
|
||||
|
||||
- [ ] Release report exists at `RELEASE_DIR/release_<version>_<env>_<timestamp>.md` with verdict (Released / Rolled-Back / Aborted)
|
||||
- [ ] Every phase that ran has a section in the release report with timestamps and tool output
|
||||
- [ ] On Released: tracker tickets moved to release status; git tag pushed (if convention)
|
||||
- [ ] On Rolled-Back: rollback report exists at `RELEASE_DIR/rollback_<version>_<env>_<timestamp>.md`; tracker tickets moved back to pre-release status; incident retrospective scheduled
|
||||
- [ ] On Aborted: reason recorded; no live-system changes attempted; no tracker movement
|
||||
- [ ] No phase was skipped without an explicit reason recorded in the release report
|
||||
|
||||
## Escalation Rules
|
||||
|
||||
| Situation | Action |
|
||||
|-----------|--------|
|
||||
| `scripts/deploy.sh` missing or `--rollback` unsupported | STOP — return to `/deploy` Step 7, do not patch the script in `/release` |
|
||||
| Registry auth failure during pre-release | STOP — fix credentials at infra layer (per `coderule.mdc`); do not embed creds in the script |
|
||||
| Smoke tests missing for prod target | STOP — write a leftover; do not improvise smoke tests in `/release` |
|
||||
| Observability backend unreachable | STOP — observability blindness is itself a release blocker |
|
||||
| User asks to skip the watch window | Record override, mark verdict `Released-with-override`, fire incident retro |
|
||||
| Rollback also fails its smoke test | ESCALATE to user — system is in unknown state; do not loop deploys |
|
||||
| Tracker MCP returns Unauthorized during ticket movement | Per `tracker.mdc`, write a leftover entry; do NOT silently continue without confirming the move |
|
||||
| Multiple environments named in user request | STOP — one release per invocation; ask user to pick one |
|
||||
| Production smoke test would touch real customer data | STOP — that is a `coderule.mdc` violation; ask user to define a smoke endpoint or test account |
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
- **Skipping the watch window when "everything looks fine after deploy"** — a deploy that exited 0 is not a release that's stable. Watch is mandatory.
|
||||
- **Faking smoke tests** to pass the gate when the prod test set is incomplete. STOP and surface the gap; do not embed prod URLs into ad-hoc curl commands.
|
||||
- **Rolling forward through a failure** ("the next deploy will fix it"). Roll back first, fix the cause, then deploy a real fix.
|
||||
- **Treating the release report as optional** when only an internal tool changed. Every release writes a report — the audit trail is the value, not the prose volume.
|
||||
- **Approving manual gates yourself** without the user's input when restrictions require human approval. The release skill records, the human approves.
|
||||
- **Reusing `release_<version>` filenames** across attempted releases. Always include the timestamp in the filename so re-attempts are visible side-by-side.
|
||||
- **Letting tracker drift silently** between release attempts. If Phase 6 cannot move tickets, the release is not complete — write a leftover and stop.
|
||||
|
||||
## Project Mode vs Standalone
|
||||
|
||||
- **Project mode** (default): autodev invokes `/release` after `/deploy`. State writes occur under `_docs/_autodev_state.md`. Full integration with retrospective and feature-cycle loop.
|
||||
- **Standalone mode**: `/release` invoked directly with `@<artifact>` (rare; usually only for re-running a rollback against a specific version). All outputs still go to `RELEASE_DIR/`.
|
||||
|
||||
## Methodology Quick Reference
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────┐
|
||||
│ Release (6 phases, 3 verdicts) │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ Phase 1 Pre-Release Gate │
|
||||
│ AC + tests + change summary + rollback path │
|
||||
│ [BLOCKING — user A/B/C] │
|
||||
│ Phase 2 Strategy Select │
|
||||
│ all-at-once · blue-green · canary · manual │
|
||||
│ [BLOCKING — user picks] │
|
||||
│ Phase 3 Execute │
|
||||
│ scripts/deploy.sh, capture exit code + logs │
|
||||
│ [AUTO-ROLLBACK on non-zero or hang] │
|
||||
│ Phase 4 Smoke Test │
|
||||
│ /test-run --prod-smoke against target │
|
||||
│ [AUTO-ROLLBACK on any failure] │
|
||||
│ Phase 5 Watch Window │
|
||||
│ Poll observability for N minutes │
|
||||
│ [AUTO-ROLLBACK on hard breach; escalate on soft] │
|
||||
│ Phase 6 Commit or Rollback │
|
||||
│ Released → tracker, tag, retrospective │
|
||||
│ Rolled-Back → tracker reset, incident retrospective │
|
||||
│ Aborted → no live-system change │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ Principles: real execution · verifiable rollback · │
|
||||
│ quiet failure = release failure · │
|
||||
│ watch window mandatory │
|
||||
└────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
@@ -0,0 +1,114 @@
|
||||
# Release Report — {version} → {env}
|
||||
|
||||
- **Date**: {YYYY-MM-DD HH:MM} {timezone}
|
||||
- **Operator**: {user}
|
||||
- **Strategy**: {all-at-once | blue-green | canary | manual}
|
||||
- **Verdict**: {Released | Released-with-override | Rolled-Back | Aborted}
|
||||
- **Verdict reason**: {one-line summary}
|
||||
|
||||
## Pre-Release Gate (Phase 1)
|
||||
|
||||
### Acceptance Criteria
|
||||
|
||||
| AC ID | Status | Evidence |
|
||||
|-------|--------|----------|
|
||||
| AC-001 | Met / Unmet | path:section, test report, etc. |
|
||||
|
||||
### Test Status
|
||||
|
||||
| Suite | Pass | Fail | Skip | Source |
|
||||
|-------|------|------|------|--------|
|
||||
| Functional | N | N | N | _docs/03_implementation/{batch}.md |
|
||||
| Performance | N | N | N | _docs/06_metrics/perf_*.md |
|
||||
|
||||
### Change Summary
|
||||
|
||||
| Component | Tickets | Type |
|
||||
|-----------|---------|------|
|
||||
| {component} | TKT-001, TKT-002 | feature / fix / breaking / security |
|
||||
|
||||
### Rollback Plan
|
||||
|
||||
- Previous version: `{previous-version}` (registry digest: `{sha}`)
|
||||
- Rollback script: `scripts/deploy.sh --rollback`
|
||||
- Rollback target verified pullable: yes / no
|
||||
- Rollback target verified bootable in target env: yes / no
|
||||
|
||||
### Restrictions / Approvals
|
||||
|
||||
- Change-window restrictions: {none | description}
|
||||
- Manual approvals required: {none | reference to approval file}
|
||||
|
||||
### Tracker State at Gate
|
||||
|
||||
- Tickets in scope: {N}
|
||||
- Tickets blocking release: {0 — list any}
|
||||
|
||||
## Strategy Select (Phase 2)
|
||||
|
||||
- Recommended: {strategy} — reasoning
|
||||
- Chosen: {strategy} — reasoning (if differs from recommended)
|
||||
|
||||
## Execute (Phase 3)
|
||||
|
||||
- Start: {timestamp}
|
||||
- End: {timestamp}
|
||||
- Exit code: {0 / non-zero}
|
||||
|
||||
```
|
||||
<scripts/deploy.sh stdout/stderr stream, with timestamps>
|
||||
```
|
||||
|
||||
## Smoke Test (Phase 4)
|
||||
|
||||
- Mode: {/test-run --prod-smoke | manual smoke set}
|
||||
- Start: {timestamp}
|
||||
- End: {timestamp}
|
||||
|
||||
| Test | Result | Notes |
|
||||
|------|--------|-------|
|
||||
| {name} | Pass / Fail | response time, status, etc. |
|
||||
|
||||
## Watch Window (Phase 5)
|
||||
|
||||
- Duration: {minutes}
|
||||
- Cadence: {minutes per poll}
|
||||
- Backend: {observability source — Prometheus, CloudWatch, Datadog, etc.}
|
||||
|
||||
| T+min | error_rate | rps | p99_latency | saturation | health | notes |
|
||||
|-------|------------|-----|-------------|------------|--------|-------|
|
||||
| 0 | … | … | … | … | OK | … |
|
||||
| 1 | … | … | … | … | OK | … |
|
||||
| … | … | … | … | … | … | … |
|
||||
|
||||
### Threshold breaches
|
||||
|
||||
- {None | "p99 latency 1.7× baseline at T+8 — soft breach, user accepted continuation"}
|
||||
|
||||
## Commit or Rollback (Phase 6)
|
||||
|
||||
### If Released
|
||||
|
||||
- Tracker tickets moved: {list}
|
||||
- Git tag pushed: {tag} → {sha}
|
||||
- Retrospective scheduled: yes — {/retrospective --cycle-end output path}
|
||||
|
||||
### If Rolled-Back
|
||||
|
||||
- Trigger: {auto / user-elected}
|
||||
- Reason: {phase + one-line cause}
|
||||
- Rollback start: {timestamp}
|
||||
- Rollback end: {timestamp}
|
||||
- Post-rollback smoke: pass / fail
|
||||
- Tracker tickets moved back: {list}
|
||||
- Incident retrospective scheduled: yes — {/retrospective --incident output path}
|
||||
|
||||
### If Aborted
|
||||
|
||||
- Phase that aborted: {1 / 2 / 3 / 4 / 5}
|
||||
- Reason: {one-line cause}
|
||||
- No live-system changes attempted: yes / no (if live changes, document under Phase 3 above and treat as Rolled-Back instead)
|
||||
|
||||
## Lessons (one-liners; full incident retro if Rolled-Back / Released-with-override)
|
||||
|
||||
- {Optional: short one-liner observations the operator wants the next /retrospective to consider}
|
||||
@@ -2,9 +2,9 @@
|
||||
name: retrospective
|
||||
description: |
|
||||
Collect metrics from implementation batch reports and code review findings, analyze trends across cycles,
|
||||
and produce improvement reports with actionable recommendations.
|
||||
3-step workflow: collect metrics, analyze trends, produce report.
|
||||
Outputs to _docs/06_metrics/.
|
||||
and produce improvement reports plus a lessons-log update with actionable recommendations.
|
||||
4-step workflow: collect metrics, analyze trends, produce report, update lessons log.
|
||||
Outputs to _docs/06_metrics/ and appends to _docs/LESSONS.md (ring buffer, last 15).
|
||||
Trigger phrases:
|
||||
- "retrospective", "retro", "run retro"
|
||||
- "metrics review", "feedback loop"
|
||||
@@ -232,7 +232,7 @@ Present the report summary to the user.
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────┐
|
||||
│ Retrospective (3-Step Method) │
|
||||
│ Retrospective (4-Step Method) │
|
||||
├────────────────────────────────────────────────────────────────┤
|
||||
│ PREREQ: batch reports exist in _docs/03_implementation/ │
|
||||
│ │
|
||||
|
||||
@@ -202,12 +202,12 @@ If invoked in `cycle-update` mode (see "Invocation Modes" above), read and follo
|
||||
| Missing acceptance_criteria.md, restrictions.md, or input_data/ | **STOP** — specification cannot proceed |
|
||||
| Missing input_data/expected_results/results_report.md | **STOP** — ask user to provide expected results mapping using the template |
|
||||
| Ambiguous requirements | ASK user |
|
||||
| Input data coverage below 75% (Phase 1) | Search internet for supplementary data, ASK user to validate |
|
||||
| Input data coverage below the canonical threshold (Phase 1) | Search internet for supplementary data, ASK user to validate. See `.cursor/rules/cursor-meta.mdc` Quality Thresholds for the canonical 75% number — do not hardcode a different threshold here. |
|
||||
| Expected results missing or not quantifiable (Phase 1) | ASK user to provide quantifiable expected results before proceeding |
|
||||
| Test scenario conflicts with restrictions | ASK user to clarify intent |
|
||||
| System interfaces unclear (no architecture.md) | ASK user or derive from solution.md |
|
||||
| Test data or expected result not provided for a test scenario (Phase 3) | WARN user and REMOVE the test |
|
||||
| Final coverage below 75% after removals (Phase 3) | BLOCK — require user to supply data or accept reduced spec |
|
||||
| Final coverage below the canonical threshold after removals (Phase 3) | BLOCK — require user to supply data or accept reduced spec (see `cursor-meta.mdc` Quality Thresholds) |
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
@@ -252,7 +252,8 @@ When the user wants to:
|
||||
│ │
|
||||
│ Phase 3: Test Data & Expected Results Validation Gate (HARD GATE) │
|
||||
│ → phases/03-data-validation-gate.md │
|
||||
│ [BLOCKING: coverage ≥ 75% required to pass] │
|
||||
│ [BLOCKING: coverage ≥ canonical threshold required to pass — │
|
||||
│ see cursor-meta.mdc Quality Thresholds (75%)] │
|
||||
│ │
|
||||
│ Hardware-Dependency Assessment (BLOCKING, pre-Phase-4) │
|
||||
│ → phases/hardware-assessment.md │
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Phase 3: Test Data & Expected Results Validation Gate (HARD GATE)
|
||||
|
||||
**Role**: Professional Quality Assurance Engineer
|
||||
**Goal**: Ensure every test scenario produced in Phase 2 has concrete, sufficient test data. Remove tests that lack data. Verify final coverage stays above 75%.
|
||||
**Goal**: Ensure every test scenario produced in Phase 2 has concrete, sufficient test data. Remove tests that lack data. Verify final coverage stays above the canonical threshold (currently 75% — see `.cursor/rules/cursor-meta.mdc` Quality Thresholds; never hardcode a different number in any phase).
|
||||
**Constraints**: This phase is MANDATORY and cannot be skipped.
|
||||
|
||||
## Step 1 — Build the requirements checklist
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
|
||||
[*.cs]
|
||||
indent_size = 4
|
||||
|
||||
[*.{csproj,props,targets,nuspec,resx}]
|
||||
indent_size = 2
|
||||
|
||||
[*.{json,yml,yaml}]
|
||||
indent_size = 2
|
||||
|
||||
[*.{md,sql}]
|
||||
trim_trailing_whitespace = false
|
||||
|
||||
[*.cs]
|
||||
csharp_new_line_before_open_brace = all
|
||||
csharp_new_line_before_else = true
|
||||
csharp_new_line_before_catch = true
|
||||
csharp_new_line_before_finally = true
|
||||
csharp_new_line_before_members_in_object_initializers = true
|
||||
csharp_new_line_before_members_in_anonymous_types = true
|
||||
csharp_new_line_between_query_expression_clauses = true
|
||||
|
||||
csharp_style_namespace_declarations = file_scoped:suggestion
|
||||
csharp_using_directive_placement = outside_namespace:suggestion
|
||||
|
||||
dotnet_style_qualification_for_field = false:suggestion
|
||||
dotnet_style_qualification_for_property = false:suggestion
|
||||
dotnet_style_qualification_for_method = false:suggestion
|
||||
dotnet_style_qualification_for_event = false:suggestion
|
||||
|
||||
dotnet_diagnostic.CA1001.severity = warning
|
||||
dotnet_diagnostic.CA1051.severity = warning
|
||||
dotnet_diagnostic.CA1816.severity = warning
|
||||
dotnet_diagnostic.CA2227.severity = warning
|
||||
@@ -0,0 +1,35 @@
|
||||
# Satellite Provider environment configuration template.
|
||||
# Copy this file to `.env` and replace placeholder values before running
|
||||
# docker-compose or scripts/run-tests.sh.
|
||||
#
|
||||
# IMPORTANT: `.env` is gitignored on purpose. Never commit real secrets.
|
||||
|
||||
# Google Maps Platform API key for satellite imagery downloads.
|
||||
GOOGLE_MAPS_API_KEY=
|
||||
|
||||
# HMAC-SHA256 signing key for JWT validation (suite-level auth contract,
|
||||
# `suite/_docs/10_auth.md`). MUST be at least 32 bytes (UTF-8) — the API
|
||||
# fails fast on startup if this is unset or shorter.
|
||||
#
|
||||
# Generate a strong secret with, for example:
|
||||
# openssl rand -hex 32
|
||||
#
|
||||
# Test/CI runs may use a clearly tagged TEST-ONLY value (still >=32 bytes).
|
||||
JWT_SECRET=
|
||||
|
||||
# JWT issuer / audience claims (AZ-494). Both are REQUIRED — the API
|
||||
# fails fast at startup if either is unset or whitespace-only.
|
||||
#
|
||||
# Production values MUST be confirmed by the admin team before deploy
|
||||
# (the admin API stamps the `iss` claim; satellite-provider validates
|
||||
# the `aud` claim).
|
||||
#
|
||||
# For local dev / CI: use the DEV-ONLY values below. The integration
|
||||
# test runner and scripts/run-tests.sh read these directly from the
|
||||
# environment (no appsettings fallback on the test side), so leaving
|
||||
# them blank will cause run-tests.sh to refuse to start.
|
||||
#
|
||||
# NEVER ship these DEV-ONLY values to prod — they exist only to make
|
||||
# local-dev mints validate against appsettings.Development.json:
|
||||
JWT_ISSUER=DEV-ONLY-iss-admin-azaion-local
|
||||
JWT_AUDIENCE=DEV-ONLY-aud-satellite-provider
|
||||
@@ -11,3 +11,10 @@ Content/
|
||||
tiles/
|
||||
ready/
|
||||
.DS_Store
|
||||
TestResults/
|
||||
coverage.cobertura.xml
|
||||
coverage.opencover.xml
|
||||
*.coverage
|
||||
_docs/03_implementation/test_runs/
|
||||
_docs/04_run_results/
|
||||
certs/
|
||||
|
||||
Vendored
+35
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
// Use IntelliSense to find out which attributes exist for C# debugging
|
||||
// Use hover for the description of the existing attributes
|
||||
// For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md.
|
||||
"name": ".NET Core Launch (web)",
|
||||
"type": "coreclr",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build",
|
||||
// If you have changed target frameworks, make sure to update the program path.
|
||||
"program": "${workspaceFolder}/SatelliteProvider.Api/bin/Debug/net10.0/SatelliteProvider.Api.dll",
|
||||
"args": [],
|
||||
"cwd": "${workspaceFolder}/SatelliteProvider.Api",
|
||||
"stopAtEntry": false,
|
||||
// Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
|
||||
"serverReadyAction": {
|
||||
"action": "openExternally",
|
||||
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
|
||||
},
|
||||
"env": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"sourceFileMap": {
|
||||
"/Views": "${workspaceFolder}/Views"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": ".NET Core Attach",
|
||||
"type": "coreclr",
|
||||
"request": "attach"
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+41
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "build",
|
||||
"command": "dotnet",
|
||||
"type": "process",
|
||||
"args": [
|
||||
"build",
|
||||
"${workspaceFolder}/SatelliteProvider.sln",
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/consoleloggerparameters:NoSummary;ForceNoAlign"
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "publish",
|
||||
"command": "dotnet",
|
||||
"type": "process",
|
||||
"args": [
|
||||
"publish",
|
||||
"${workspaceFolder}/SatelliteProvider.sln",
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/consoleloggerparameters:NoSummary;ForceNoAlign"
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
"label": "watch",
|
||||
"command": "dotnet",
|
||||
"type": "process",
|
||||
"args": [
|
||||
"watch",
|
||||
"run",
|
||||
"--project",
|
||||
"${workspaceFolder}/SatelliteProvider.sln"
|
||||
],
|
||||
"problemMatcher": "$msCompile"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -7,7 +7,7 @@ labels:
|
||||
|
||||
steps:
|
||||
- name: unit-tests
|
||||
image: mcr.microsoft.com/dotnet/sdk:8.0
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0
|
||||
commands:
|
||||
- dotnet restore SatelliteProvider.sln
|
||||
- dotnet test SatelliteProvider.Tests/SatelliteProvider.Tests.csproj --no-restore --configuration Release --logger "console;verbosity=normal" --logger "trx;LogFileName=test-results.trx" --results-directory /app/test-results
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
## System Overview
|
||||
|
||||
This is a .NET 8.0 ASP.NET Web API service that downloads, stores, and manages satellite imagery tiles from Google Maps. The service supports region-based tile requests, route planning with intermediate points, and geofencing capabilities.
|
||||
This is a .NET 10 ASP.NET Web API service that downloads, stores, and manages satellite imagery tiles from Google Maps. The service supports region-based tile requests, route planning with intermediate points, and geofencing capabilities.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **.NET 8.0** with ASP.NET Core Web API
|
||||
- **.NET 10** with ASP.NET Core Web API
|
||||
- **PostgreSQL** database (via Docker)
|
||||
- **Dapper** for data access (ORM)
|
||||
- **DbUp** for database migrations
|
||||
@@ -177,7 +177,7 @@ docker-compose -f docker-compose.yml -f docker-compose.tests.yml up --build --ab
|
||||
### Configuration Values
|
||||
|
||||
Development defaults:
|
||||
- PostgreSQL: localhost:5432, user/pass: postgres/postgres
|
||||
- PostgreSQL: localhost:5433 (host-side, mapped to container port 5432), user/pass: postgres/postgres
|
||||
- API: http://localhost:5100
|
||||
- Max zoom level: 20
|
||||
- Default zoom level: 18
|
||||
@@ -236,10 +236,12 @@ Development defaults:
|
||||
|
||||
## Dependencies and Versions
|
||||
|
||||
Key packages (all .NET 8.0):
|
||||
- Microsoft.AspNetCore.OpenApi 8.0.21
|
||||
Key packages (all .NET 10):
|
||||
- Microsoft.AspNetCore.OpenApi 10.0.7
|
||||
- Microsoft.AspNetCore.Authentication.JwtBearer 10.0.7
|
||||
- Microsoft.Extensions.* 10.0.7
|
||||
- Swashbuckle.AspNetCore 6.6.2
|
||||
- Serilog.AspNetCore 8.0.3
|
||||
- Serilog.AspNetCore 8.0.3 (intentional — 10.0.0 requires Serilog.Sinks.File ≥ 7.0.0; bumping Serilog.Sinks.File is out of AZ-500 scope per "no unrelated package bumps")
|
||||
- SixLabors.ImageSharp 3.1.11
|
||||
- Newtonsoft.Json 13.0.4
|
||||
- Dapper (check DataAccess csproj)
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
<Project>
|
||||
|
||||
<PropertyGroup>
|
||||
<EnableNETAnalyzers>true</EnableNETAnalyzers>
|
||||
<AnalysisLevel>latest</AnalysisLevel>
|
||||
<AnalysisMode>None</AnalysisMode>
|
||||
<EnforceCodeStyleInBuild>false</EnforceCodeStyleInBuild>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -73,7 +73,7 @@ The service follows a layered architecture:
|
||||
### Download Single Tile
|
||||
|
||||
```http
|
||||
GET /api/satellite/tiles/latlon?Latitude={lat}&Longitude={lon}&ZoomLevel={zoom}
|
||||
GET /api/satellite/tiles/latlon?lat={lat}&lon={lon}&zoom={zoom}
|
||||
```
|
||||
|
||||
Downloads a single tile at specified coordinates and zoom level.
|
||||
@@ -434,7 +434,7 @@ Log level can be adjusted in `appsettings.json` under `Serilog:MinimumLevel`.
|
||||
|
||||
### Service won't start
|
||||
- Check Docker is running
|
||||
- Verify ports 5100 and 5432 are available
|
||||
- Verify ports 5100 and 5433 are available (Postgres host-side; the container itself listens on 5432 inside the docker network)
|
||||
- Check logs: `docker-compose logs api`
|
||||
|
||||
### Tiles not downloading
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
|
||||
namespace SatelliteProvider.Api.Authentication;
|
||||
|
||||
public static class AuthenticationServiceCollectionExtensions
|
||||
{
|
||||
public const string JwtSecretEnvVar = "JWT_SECRET";
|
||||
public const string JwtSecretConfigKey = "Jwt:Secret";
|
||||
public const string JwtIssuerEnvVar = "JWT_ISSUER";
|
||||
public const string JwtIssuerConfigKey = "Jwt:Issuer";
|
||||
public const string JwtAudienceEnvVar = "JWT_AUDIENCE";
|
||||
public const string JwtAudienceConfigKey = "Jwt:Audience";
|
||||
public const int MinSecretByteLength = 32;
|
||||
|
||||
public static IServiceCollection AddSatelliteJwt(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
ArgumentNullException.ThrowIfNull(configuration);
|
||||
|
||||
var secret = ResolveSecretOrThrow(configuration);
|
||||
var issuer = ResolveRequiredOrThrow(configuration, JwtIssuerEnvVar, JwtIssuerConfigKey, "JWT issuer");
|
||||
var audience = ResolveRequiredOrThrow(configuration, JwtAudienceEnvVar, JwtAudienceConfigKey, "JWT audience");
|
||||
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
|
||||
|
||||
services
|
||||
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = signingKey,
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.FromSeconds(30),
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = issuer,
|
||||
ValidateAudience = true,
|
||||
ValidAudience = audience,
|
||||
RequireSignedTokens = true,
|
||||
RequireExpirationTime = true
|
||||
};
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
internal static string ResolveSecretOrThrow(IConfiguration configuration)
|
||||
{
|
||||
var secret = Environment.GetEnvironmentVariable(JwtSecretEnvVar);
|
||||
if (string.IsNullOrWhiteSpace(secret))
|
||||
{
|
||||
secret = configuration[JwtSecretConfigKey];
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(secret))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"JWT secret is not configured. Set the {JwtSecretEnvVar} environment variable " +
|
||||
$"or the {JwtSecretConfigKey} configuration key to a value of at least {MinSecretByteLength} bytes.");
|
||||
}
|
||||
|
||||
var byteLength = Encoding.UTF8.GetByteCount(secret);
|
||||
if (byteLength < MinSecretByteLength)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"JWT secret is too short ({byteLength} bytes). HMAC-SHA256 requires at least {MinSecretByteLength} bytes " +
|
||||
$"per RFC 2104 §3. Set {JwtSecretEnvVar} or {JwtSecretConfigKey} to a longer value.");
|
||||
}
|
||||
|
||||
return secret;
|
||||
}
|
||||
|
||||
// AZ-494: required non-secret config (iss / aud). Fail-fast contract mirrors
|
||||
// JWT_SECRET — missing or whitespace-only values throw at startup so a
|
||||
// production deploy without the operator-confirmed values cannot silently
|
||||
// accept tokens with arbitrary issuer/audience claims.
|
||||
internal static string ResolveRequiredOrThrow(IConfiguration configuration, string envVar, string configKey, string humanLabel)
|
||||
{
|
||||
var value = Environment.GetEnvironmentVariable(envVar);
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
value = configuration[configKey];
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"{humanLabel} is not configured. Set the {envVar} environment variable " +
|
||||
$"or the {configKey} configuration key. (See AZ-494 task spec.)");
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace SatelliteProvider.Api.Authentication;
|
||||
|
||||
// AZ-488: enforces a required permission from the `permissions` JWT claim.
|
||||
// The claim may arrive as either:
|
||||
// - a JWT array claim (multiple ClaimType="permissions" entries — Microsoft.IdentityModel
|
||||
// splits arrays this way), OR
|
||||
// - a single JSON-array string ("[\"GPS\",\"FL\"]") when a producer mis-encodes.
|
||||
// Both shapes are matched so the satellite-provider remains tolerant of upstream
|
||||
// producers that do not split array claims out of the box.
|
||||
public sealed class PermissionsRequirement : IAuthorizationRequirement
|
||||
{
|
||||
public PermissionsRequirement(string requiredPermission)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(requiredPermission))
|
||||
{
|
||||
throw new ArgumentException("Required permission must be a non-empty string.", nameof(requiredPermission));
|
||||
}
|
||||
|
||||
RequiredPermission = requiredPermission;
|
||||
}
|
||||
|
||||
public string RequiredPermission { get; }
|
||||
}
|
||||
|
||||
public sealed class PermissionsAuthorizationHandler : AuthorizationHandler<PermissionsRequirement>
|
||||
{
|
||||
public const string ClaimType = "permissions";
|
||||
|
||||
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionsRequirement requirement)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
ArgumentNullException.ThrowIfNull(requirement);
|
||||
|
||||
var user = context.User;
|
||||
if (user?.Identity?.IsAuthenticated != true)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
if (UserHasPermission(user, requirement.RequiredPermission))
|
||||
{
|
||||
context.Succeed(requirement);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static bool UserHasPermission(ClaimsPrincipal user, string requiredPermission)
|
||||
{
|
||||
foreach (var claim in user.FindAll(ClaimType))
|
||||
{
|
||||
if (string.Equals(claim.Value, requiredPermission, StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (TryReadJsonArray(claim.Value, out var values))
|
||||
{
|
||||
foreach (var value in values)
|
||||
{
|
||||
if (string.Equals(value, requiredPermission, StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TryReadJsonArray(string value, out IReadOnlyList<string> items)
|
||||
{
|
||||
items = Array.Empty<string>();
|
||||
if (string.IsNullOrWhiteSpace(value) || value[0] != '[')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(value);
|
||||
if (document.RootElement.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var result = new List<string>(document.RootElement.GetArrayLength());
|
||||
foreach (var element in document.RootElement.EnumerateArray())
|
||||
{
|
||||
if (element.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
var text = element.GetString();
|
||||
if (!string.IsNullOrEmpty(text))
|
||||
{
|
||||
result.Add(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
items = result;
|
||||
return result.Count > 0;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class SatellitePermissions
|
||||
{
|
||||
public const string Gps = "GPS";
|
||||
public const string UavUploadPolicy = "RequiresGpsPermission";
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace SatelliteProvider.Api.DTOs;
|
||||
|
||||
// AZ-811: query-string record for GET /api/satellite/tiles/latlon.
|
||||
// Bound via `[AsParameters]` so each property maps to one query parameter.
|
||||
// `[FromQuery(Name = "...")]` pins the wire name explicitly — case-sensitive
|
||||
// match against `?lat=&lon=&zoom=`, matching the OSM convention shared with
|
||||
// the rest of the satellite-provider API (`{z, x, y}` for inventory,
|
||||
// `{lat, lon}` for region and route DTOs).
|
||||
//
|
||||
// **Why nullable types**: minimal-API parameter binding throws
|
||||
// BadHttpRequestException for missing-required non-nullable query params
|
||||
// BEFORE endpoint filters run. That short-circuit produces a plain
|
||||
// ProblemDetails via GlobalExceptionHandler — no `errors{}` envelope, no
|
||||
// per-field key. Per AZ-811 ACs 1 & 4 every missing/unknown param must
|
||||
// surface as `errors.<paramName>` in ValidationProblemDetails. Nullable
|
||||
// types let binding always succeed, so:
|
||||
// 1. RejectUnknownQueryParamsEndpointFilter handles unknown keys
|
||||
// (e.g. legacy `?Latitude=`, hostile `?debug=1`).
|
||||
// 2. GetTileByLatLonQueryValidator handles `null` (missing) plus range.
|
||||
// Validator guarantees non-null by the time the handler dereferences.
|
||||
public sealed record GetTileByLatLonQuery(
|
||||
[property: FromQuery(Name = "lat")] double? Lat,
|
||||
[property: FromQuery(Name = "lon")] double? Lon,
|
||||
[property: FromQuery(Name = "zoom")] int? Zoom);
|
||||
@@ -0,0 +1,16 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace SatelliteProvider.Api.DTOs;
|
||||
|
||||
// AZ-488 / `uav-tile-upload.md` v1.0.0 — multipart envelope. `Metadata` carries the
|
||||
// JSON array of UavTileMetadata records; `Files` provides one IFormFile per record
|
||||
// at the matching ordinal index.
|
||||
public record UavTileBatchUploadRequest
|
||||
{
|
||||
[FromForm(Name = "metadata")]
|
||||
public string Metadata { get; init; } = string.Empty;
|
||||
|
||||
[FromForm(Name = "files")]
|
||||
public IFormFileCollection? Files { get; init; }
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
|
||||
WORKDIR /app
|
||||
EXPOSE 8080
|
||||
EXPOSE 8081
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
WORKDIR /src
|
||||
COPY ["SatelliteProvider.Api/SatelliteProvider.Api.csproj", "SatelliteProvider.Api/"]
|
||||
COPY ["SatelliteProvider.Common/SatelliteProvider.Common.csproj", "SatelliteProvider.Common/"]
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.Diagnostics;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
@@ -60,6 +61,30 @@ public sealed class GlobalExceptionHandler : IExceptionHandler
|
||||
{
|
||||
httpContext.Response.StatusCode = badRequest.StatusCode;
|
||||
|
||||
// AZ-795: deserialization failures (unknown field via UnmappedMemberHandling.Disallow,
|
||||
// type mismatch, malformed JSON) surface here as BadHttpRequestException with a
|
||||
// System.Text.Json `JsonException` somewhere in the inner-exception chain. Convert
|
||||
// them to RFC 7807 ValidationProblemDetails so wire-format errors share the same
|
||||
// shape as FluentValidation business-rule errors — see
|
||||
// `_docs/02_document/contracts/api/error-shape.md`.
|
||||
var deserializationErrors = TryExtractDeserializationErrors(badRequest);
|
||||
if (deserializationErrors is not null && badRequest.StatusCode == StatusCodes.Status400BadRequest)
|
||||
{
|
||||
var validation = new ValidationProblemDetails(deserializationErrors)
|
||||
{
|
||||
Status = badRequest.StatusCode,
|
||||
Title = "One or more validation errors occurred.",
|
||||
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1",
|
||||
};
|
||||
|
||||
await httpContext.Response.WriteAsJsonAsync(
|
||||
validation,
|
||||
options: null,
|
||||
contentType: "application/problem+json",
|
||||
cancellationToken: cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
var problem = new ProblemDetails
|
||||
{
|
||||
Status = badRequest.StatusCode,
|
||||
@@ -73,4 +98,36 @@ public sealed class GlobalExceptionHandler : IExceptionHandler
|
||||
contentType: "application/problem+json",
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
private static IDictionary<string, string[]>? TryExtractDeserializationErrors(BadHttpRequestException ex)
|
||||
{
|
||||
var current = ex.InnerException;
|
||||
while (current is not null)
|
||||
{
|
||||
if (current is JsonException jsonEx)
|
||||
{
|
||||
var path = NormalizeJsonPath(jsonEx.Path);
|
||||
var message = string.IsNullOrEmpty(jsonEx.Message)
|
||||
? "Invalid JSON."
|
||||
: jsonEx.Message;
|
||||
|
||||
return new Dictionary<string, string[]>
|
||||
{
|
||||
[path] = new[] { message }
|
||||
};
|
||||
}
|
||||
|
||||
current = current.InnerException;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string NormalizeJsonPath(string? path)
|
||||
{
|
||||
if (string.IsNullOrEmpty(path)) return "$";
|
||||
return path.StartsWith("$.", StringComparison.Ordinal)
|
||||
? path.Substring(2)
|
||||
: path;
|
||||
}
|
||||
}
|
||||
|
||||
+191
-146
@@ -1,10 +1,18 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using FluentValidation;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.OpenApi.Models;
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
using SatelliteProvider.Api;
|
||||
using SatelliteProvider.Api.Authentication;
|
||||
using SatelliteProvider.Api.DTOs;
|
||||
using SatelliteProvider.Api.Swagger;
|
||||
using SatelliteProvider.Api.Validators;
|
||||
using SatelliteProvider.DataAccess;
|
||||
using SatelliteProvider.DataAccess.Repositories;
|
||||
using SatelliteProvider.DataAccess.TypeHandlers;
|
||||
using SatelliteProvider.Common.Configs;
|
||||
using SatelliteProvider.Common.DTO;
|
||||
using SatelliteProvider.Common.Interfaces;
|
||||
@@ -21,13 +29,41 @@ builder.Host.UseSerilog((context, configuration) =>
|
||||
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
|
||||
?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
|
||||
|
||||
DapperEnumTypeHandlers.RegisterAll();
|
||||
|
||||
builder.Services.Configure<MapConfig>(builder.Configuration.GetSection("MapConfig"));
|
||||
builder.Services.Configure<StorageConfig>(builder.Configuration.GetSection("StorageConfig"));
|
||||
builder.Services.Configure<ProcessingConfig>(builder.Configuration.GetSection("ProcessingConfig"));
|
||||
builder.Services.Configure<UavQualityConfig>(builder.Configuration.GetSection("UavQuality"));
|
||||
|
||||
var uavQuality = builder.Configuration.GetSection("UavQuality").Get<UavQualityConfig>() ?? new UavQualityConfig();
|
||||
var uavBatchBodyLimit = checked((long)uavQuality.MaxBatchSize * uavQuality.MaxBytes);
|
||||
builder.Services.Configure<KestrelServerOptions>(options =>
|
||||
{
|
||||
options.Limits.MaxRequestBodySize = uavBatchBodyLimit;
|
||||
// AZ-505: enable HTTP/2 alongside HTTP/1.1 on every Kestrel endpoint so
|
||||
// programmatic clients (httpx http2=True, .NET HttpClient) can multiplex
|
||||
// tile reads on a single TCP connection. Kestrel requires TLS+ALPN for
|
||||
// HTTP/2 — the dev/test compose files mount a self-signed cert at
|
||||
// /app/certs/api.pfx and set ASPNETCORE_URLS=https://+:8080; production
|
||||
// is expected to terminate TLS at the same layer or upstream. Browsers
|
||||
// negotiate HTTP/2 via ALPN once TLS is present; legacy HTTP/1.1
|
||||
// callers continue to work over the same listener. HTTP/3/QUIC is
|
||||
// intentionally out of scope (see AZ-505 task spec § Excluded).
|
||||
options.ConfigureEndpointDefaults(listen =>
|
||||
{
|
||||
listen.Protocols = HttpProtocols.Http1AndHttp2;
|
||||
});
|
||||
});
|
||||
builder.Services.Configure<FormOptions>(options =>
|
||||
{
|
||||
options.MultipartBodyLengthLimit = uavBatchBodyLimit;
|
||||
options.ValueLengthLimit = Math.Max(options.ValueLengthLimit, uavQuality.MaxBatchSize * 512);
|
||||
});
|
||||
|
||||
builder.Services.AddSingleton<ITileRepository>(sp => new TileRepository(connectionString, sp.GetRequiredService<ILogger<TileRepository>>()));
|
||||
builder.Services.AddSingleton<IRegionRepository>(sp => new RegionRepository(connectionString, sp.GetRequiredService<ILogger<RegionRepository>>()));
|
||||
builder.Services.AddSingleton<IRouteRepository>(sp => new RouteRepository(connectionString, sp.GetRequiredService<ILogger<RouteRepository>>()));
|
||||
builder.Services.AddSingleton<IRegionRepository>(sp => new RegionRepository(connectionString));
|
||||
builder.Services.AddSingleton<IRouteRepository>(sp => new RouteRepository(connectionString));
|
||||
|
||||
builder.Services.AddHttpClient();
|
||||
|
||||
@@ -35,6 +71,17 @@ builder.Services.AddTileDownloader();
|
||||
builder.Services.AddRegionProcessing();
|
||||
builder.Services.AddRouteManagement();
|
||||
|
||||
builder.Services.AddSatelliteJwt(builder.Configuration);
|
||||
builder.Services.AddSingleton<IAuthorizationHandler, PermissionsAuthorizationHandler>();
|
||||
builder.Services.AddAuthorization(options =>
|
||||
{
|
||||
options.AddPolicy(SatellitePermissions.UavUploadPolicy, policy =>
|
||||
{
|
||||
policy.RequireAuthenticatedUser();
|
||||
policy.Requirements.Add(new PermissionsRequirement(SatellitePermissions.Gps));
|
||||
});
|
||||
});
|
||||
|
||||
var allowedOrigins = builder.Configuration.GetSection("CorsConfig:AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();
|
||||
var allowAnyOrigin = builder.Configuration.GetValue<bool>("CorsConfig:AllowAnyOrigin");
|
||||
CorsConfigurationValidator.EnsureSafeForEnvironment(allowedOrigins, allowAnyOrigin, builder.Environment.EnvironmentName);
|
||||
@@ -53,32 +100,74 @@ builder.Services.AddCors(options =>
|
||||
builder.Services.AddProblemDetails();
|
||||
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
|
||||
|
||||
// AZ-795: strict JSON parsing — unknown fields are rejected at the deserializer
|
||||
// level instead of being silently dropped. Pairs with the per-endpoint
|
||||
// FluentValidation filter (`WithValidation<T>()`) so the API has a single
|
||||
// uniform RFC 7807 error contract for both wire-format failures and
|
||||
// business-rule failures (`_docs/02_document/contracts/api/error-shape.md`).
|
||||
builder.Services.ConfigureHttpJsonOptions(options =>
|
||||
{
|
||||
options.SerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
|
||||
options.SerializerOptions.PropertyNameCaseInsensitive = true;
|
||||
options.SerializerOptions.UnmappedMemberHandling = System.Text.Json.Serialization.JsonUnmappedMemberHandling.Disallow;
|
||||
options.SerializerOptions.Converters.Add(
|
||||
new System.Text.Json.Serialization.JsonStringEnumConverter(System.Text.Json.JsonNamingPolicy.CamelCase));
|
||||
});
|
||||
|
||||
// AZ-795: register every IValidator<T> in this assembly with DI so the
|
||||
// generic ValidationEndpointFilter<T> can resolve them at request time.
|
||||
// GlobalValidatorConfig.ApplyOnce() centralizes process-wide FluentValidation
|
||||
// configuration (camelCase property paths, etc.) so the API host and the
|
||||
// unit-test fixture share one source of truth — see error-shape.md Inv-4.
|
||||
builder.Services.AddValidatorsFromAssemblyContaining<Program>();
|
||||
GlobalValidatorConfig.ApplyOnce();
|
||||
|
||||
// AZ-810: explicit registration so `.AddEndpointFilter<UavUploadValidationFilter>()`
|
||||
// on the UAV upload endpoint resolves the filter with its `IValidator<…>` + JSON
|
||||
// options constructor deps. Transient so each request gets a fresh instance.
|
||||
builder.Services.AddTransient<UavUploadValidationFilter>();
|
||||
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Satellite Provider API", Version = "v1" });
|
||||
|
||||
c.MapType<UploadImageRequest>(() => new OpenApiSchema
|
||||
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
||||
{
|
||||
Type = "object",
|
||||
Properties = new Dictionary<string, OpenApiSchema>
|
||||
Name = "Authorization",
|
||||
Type = SecuritySchemeType.Http,
|
||||
Scheme = "bearer",
|
||||
BearerFormat = "JWT",
|
||||
In = ParameterLocation.Header,
|
||||
Description = "JWT Authorization header using the Bearer scheme. Example: 'Bearer {token}'"
|
||||
});
|
||||
|
||||
c.AddSecurityRequirement(_ => new OpenApiSecurityRequirement
|
||||
{
|
||||
["timestamp"] = new() { Type = "string", Format = "date-time", Description = "Image capture timestamp" },
|
||||
["image"] = new() { Type = "string", Format = "binary", Description = "Image file to upload" },
|
||||
["lat"] = new() { Type = "number", Format = "double", Description = "Latitude coordinate where image was captured" },
|
||||
["lon"] = new() { Type = "number", Format = "double", Description = "Longitude coordinate where image was captured" },
|
||||
["height"] = new() { Type = "number", Format = "double", Description = "Height/altitude in meters where image was captured" },
|
||||
["focalLength"] = new() { Type = "number", Format = "double", Description = "Camera focal length in millimeters" },
|
||||
["sensorWidth"] = new() { Type = "number", Format = "double", Description = "Camera sensor width in millimeters" },
|
||||
["sensorHeight"] = new() { Type = "number", Format = "double", Description = "Camera sensor height in millimeters" }
|
||||
{
|
||||
new OpenApiSecuritySchemeReference("Bearer"),
|
||||
new List<string>()
|
||||
}
|
||||
});
|
||||
|
||||
c.MapType<UavTileBatchUploadRequest>(() => new OpenApiSchema
|
||||
{
|
||||
Type = JsonSchemaType.Object,
|
||||
Properties = new Dictionary<string, IOpenApiSchema>
|
||||
{
|
||||
["metadata"] = new OpenApiSchema
|
||||
{
|
||||
Type = JsonSchemaType.String,
|
||||
Description = "JSON document `{ \"items\": [ { \"latitude\", \"longitude\", \"tileZoom\", \"tileSizeMeters\", \"capturedAt\" } ] }` where item ordinal index aligns with the matching file in `files`."
|
||||
},
|
||||
Required = new HashSet<string> { "timestamp", "image", "lat", "lon", "height", "focalLength", "sensorWidth", "sensorHeight" }
|
||||
["files"] = new OpenApiSchema
|
||||
{
|
||||
Type = JsonSchemaType.Array,
|
||||
Description = "UAV tile JPEG files in the same order as `metadata.items`.",
|
||||
Items = new OpenApiSchema { Type = JsonSchemaType.String, Format = "binary" }
|
||||
}
|
||||
},
|
||||
Required = new HashSet<string> { "metadata", "files" }
|
||||
});
|
||||
|
||||
c.OperationFilter<ParameterDescriptionFilter>();
|
||||
@@ -113,41 +202,81 @@ if (app.Environment.IsDevelopment())
|
||||
app.UseExceptionHandler();
|
||||
app.UseHttpsRedirection();
|
||||
app.UseCors("TilesCors");
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapGet("/tiles/{z:int}/{x:int}/{y:int}", ServeTile)
|
||||
.RequireAuthorization()
|
||||
.WithOpenApi(op => new(op) { Summary = "Get satellite tile image by z/x/y coordinates (Slippy Map tile server)" });
|
||||
|
||||
app.MapGet("/api/satellite/tiles/latlon", GetTileByLatLon)
|
||||
.RequireAuthorization()
|
||||
.AddEndpointFilter(new RejectUnknownQueryParamsEndpointFilter(new[] { "lat", "lon", "zoom" }))
|
||||
.WithValidation<GetTileByLatLonQuery>()
|
||||
.Produces<DownloadTileResponse>(StatusCodes.Status200OK)
|
||||
.ProducesProblem(StatusCodes.Status400BadRequest)
|
||||
.WithOpenApi(op => new(op) { Summary = "Get satellite tile by latitude and longitude coordinates" });
|
||||
|
||||
app.MapGet("/api/satellite/tiles/mgrs", GetSatelliteTilesByMgrs)
|
||||
.RequireAuthorization()
|
||||
.ProducesProblem(StatusCodes.Status501NotImplemented)
|
||||
.WithOpenApi(op => new(op) { Summary = "Get satellite tiles by MGRS coordinates (NOT IMPLEMENTED)" });
|
||||
|
||||
app.MapPost("/api/satellite/upload", UploadImage)
|
||||
.Accepts<UploadImageRequest>("multipart/form-data")
|
||||
.ProducesProblem(StatusCodes.Status501NotImplemented)
|
||||
.WithOpenApi(op => new(op) { Summary = "Upload image with metadata (NOT IMPLEMENTED)" })
|
||||
app.MapPost("/api/satellite/tiles/inventory", GetTilesInventory)
|
||||
.RequireAuthorization()
|
||||
.WithValidation<TileInventoryRequest>()
|
||||
.Accepts<TileInventoryRequest>("application/json")
|
||||
.Produces<TileInventoryResponse>(StatusCodes.Status200OK)
|
||||
.ProducesProblem(StatusCodes.Status400BadRequest)
|
||||
.WithOpenApi(op => new(op)
|
||||
{
|
||||
Summary = "Bulk tile inventory lookup by (z,x,y) coords or location_hash",
|
||||
Description = "Body MUST populate exactly one of `tiles` (array of `{z, x, y}` slippy-map coordinates) OR `locationHashes` (array of UUIDv5 hashes) — sending both, or neither, is HTTP 400. Response order matches request order; each entry reports `present: true|false`, and when present includes `id`, `capturedAt`, `source`, `flightId`, `resolutionMPerPx`. Hard cap: 5000 entries per request."
|
||||
});
|
||||
|
||||
app.MapPost("/api/satellite/upload", UploadUavTileBatch)
|
||||
.RequireAuthorization(SatellitePermissions.UavUploadPolicy)
|
||||
.AddEndpointFilter<UavUploadValidationFilter>()
|
||||
.Accepts<UavTileBatchUploadRequest>("multipart/form-data")
|
||||
.Produces<UavTileBatchUploadResponse>(StatusCodes.Status200OK)
|
||||
.ProducesProblem(StatusCodes.Status400BadRequest)
|
||||
.WithOpenApi(op => new(op)
|
||||
{
|
||||
Summary = "Upload a batch of UAV-captured satellite tiles",
|
||||
Description = "Multipart form: a JSON `metadata` field and an aligned `files` collection. Each item is graded by the 5-rule quality gate and persisted with `source='uav'` when accepted. Returns 200 with per-item results (mixed accept/reject), 400 for envelope-level errors (malformed metadata, missing files, oversized batch), 401 without a valid JWT, 403 without the `GPS` permission claim."
|
||||
})
|
||||
.DisableAntiforgery();
|
||||
|
||||
app.MapPost("/api/satellite/request", RequestRegion)
|
||||
.RequireAuthorization()
|
||||
.WithValidation<RequestRegionRequest>()
|
||||
.Accepts<RequestRegionRequest>("application/json")
|
||||
.Produces<RegionStatusResponse>(StatusCodes.Status200OK)
|
||||
.ProducesProblem(StatusCodes.Status400BadRequest)
|
||||
.WithOpenApi(op => new(op)
|
||||
{
|
||||
Summary = "Request tiles for a region",
|
||||
Description = "Idempotent (AZ-362): POSTing the same `id` twice returns the existing region resource with HTTP 200 and does not enqueue duplicate background processing.",
|
||||
Description = "Idempotent: POSTing the same `id` twice returns the existing region resource with HTTP 200 and does not enqueue duplicate background processing.",
|
||||
});
|
||||
|
||||
app.MapGet("/api/satellite/region/{id:guid}", GetRegionStatus)
|
||||
.RequireAuthorization()
|
||||
.WithOpenApi(op => new(op) { Summary = "Get region status and file paths" });
|
||||
|
||||
app.MapPost("/api/satellite/route", CreateRoute)
|
||||
.RequireAuthorization()
|
||||
.WithValidation<CreateRouteRequest>()
|
||||
.Accepts<CreateRouteRequest>("application/json")
|
||||
.Produces<RouteResponse>(StatusCodes.Status200OK)
|
||||
.ProducesProblem(StatusCodes.Status400BadRequest)
|
||||
.WithOpenApi(op => new(op)
|
||||
{
|
||||
Summary = "Create a route with intermediate points",
|
||||
Description = "Idempotent (AZ-362): POSTing the same `id` twice returns the existing route resource with HTTP 200 and does not regenerate intermediate points or re-queue geofence regions.",
|
||||
Description = "Idempotent: POSTing the same `id` twice returns the existing route resource with HTTP 200 and does not regenerate intermediate points or re-queue geofence regions.",
|
||||
});
|
||||
|
||||
app.MapGet("/api/satellite/route/{id:guid}", GetRoute)
|
||||
.RequireAuthorization()
|
||||
.WithOpenApi(op => new(op) { Summary = "Get route information with calculated points" });
|
||||
|
||||
app.Run();
|
||||
@@ -160,9 +289,11 @@ async Task<IResult> ServeTile(int z, int x, int y, HttpContext httpContext, ITil
|
||||
return Results.Bytes(tile.Bytes, tile.ContentType);
|
||||
}
|
||||
|
||||
async Task<IResult> GetTileByLatLon([FromQuery] double Latitude, [FromQuery] double Longitude, [FromQuery] int ZoomLevel, ITileService tileService)
|
||||
async Task<IResult> GetTileByLatLon([AsParameters] GetTileByLatLonQuery query, HttpContext httpContext, ITileService tileService)
|
||||
{
|
||||
var tile = await tileService.DownloadAndStoreSingleTileAsync(Latitude, Longitude, ZoomLevel);
|
||||
// AZ-811: GetTileByLatLonQueryValidator guarantees lat/lon/zoom are non-null
|
||||
// by the time the handler runs (CascadeMode.Stop + NotNull rules).
|
||||
var tile = await tileService.DownloadAndStoreSingleTileAsync(query.Lat!.Value, query.Lon!.Value, query.Zoom!.Value, httpContext.RequestAborted);
|
||||
|
||||
var response = new DownloadTileResponse
|
||||
{
|
||||
@@ -173,7 +304,6 @@ async Task<IResult> GetTileByLatLon([FromQuery] double Latitude, [FromQuery] dou
|
||||
TileSizeMeters = tile.TileSizeMeters,
|
||||
TileSizePixels = tile.TileSizePixels,
|
||||
ImageType = tile.ImageType,
|
||||
MapsVersion = tile.MapsVersion,
|
||||
Version = tile.Version,
|
||||
FilePath = tile.FilePath,
|
||||
CreatedAt = tile.CreatedAt,
|
||||
@@ -191,25 +321,50 @@ IResult GetSatelliteTilesByMgrs(string mgrs, double squareSideMeters)
|
||||
detail: "MGRS-based tile retrieval is not implemented.");
|
||||
}
|
||||
|
||||
IResult UploadImage([FromForm] UploadImageRequest request)
|
||||
async Task<IResult> GetTilesInventory(
|
||||
[FromBody] TileInventoryRequest request,
|
||||
HttpContext httpContext,
|
||||
ITileService tileService)
|
||||
{
|
||||
var response = await tileService.GetInventoryAsync(request, httpContext.RequestAborted);
|
||||
return Results.Ok(response);
|
||||
}
|
||||
|
||||
async Task<IResult> UploadUavTileBatch(
|
||||
HttpContext httpContext,
|
||||
IUavTileUploadHandler handler,
|
||||
[FromForm] UavTileBatchUploadRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
|
||||
var files = request.Files ?? (IFormFileCollection)new FormFileCollection();
|
||||
var uploadFiles = new List<UavUploadFile>(files.Count);
|
||||
foreach (var file in files)
|
||||
{
|
||||
await using var stream = file.OpenReadStream();
|
||||
using var buffer = new MemoryStream(checked((int)file.Length));
|
||||
await stream.CopyToAsync(buffer, httpContext.RequestAborted);
|
||||
uploadFiles.Add(new UavUploadFile(file.FileName, file.ContentType, buffer.ToArray()));
|
||||
}
|
||||
|
||||
var result = await handler.HandleAsync(request.Metadata, uploadFiles, httpContext.RequestAborted);
|
||||
if (result.EnvelopeRejected)
|
||||
{
|
||||
return Results.Problem(
|
||||
statusCode: StatusCodes.Status501NotImplemented,
|
||||
title: "Not implemented",
|
||||
detail: "Image upload is not implemented.");
|
||||
statusCode: StatusCodes.Status400BadRequest,
|
||||
title: "Invalid UAV tile batch",
|
||||
detail: result.EnvelopeError);
|
||||
}
|
||||
|
||||
return Results.Ok(result.Response);
|
||||
}
|
||||
|
||||
async Task<IResult> RequestRegion([FromBody] RequestRegionRequest request, IRegionService regionService)
|
||||
{
|
||||
if (request.SizeMeters < 100 || request.SizeMeters > 10000)
|
||||
{
|
||||
return Results.BadRequest(new { error = "Size must be between 100 and 10000 meters" });
|
||||
}
|
||||
|
||||
var status = await regionService.RequestRegionAsync(
|
||||
request.Id,
|
||||
request.Latitude,
|
||||
request.Longitude,
|
||||
request.Lat,
|
||||
request.Lon,
|
||||
request.SizeMeters,
|
||||
request.ZoomLevel,
|
||||
request.StitchTiles);
|
||||
@@ -254,113 +409,3 @@ async Task<IResult> GetRoute(Guid id, IRouteService routeService)
|
||||
|
||||
return Results.Ok(route);
|
||||
}
|
||||
|
||||
public record GetSatelliteTilesResponse
|
||||
{
|
||||
public List<SatelliteTile> Tiles { get; set; } = new();
|
||||
}
|
||||
|
||||
public record SatelliteTile
|
||||
{
|
||||
public string TileId { get; set; } = string.Empty;
|
||||
public byte[] ImageData { get; set; } = Array.Empty<byte>();
|
||||
public double Lat { get; set; }
|
||||
public double Lon { get; set; }
|
||||
public int ZoomLevel { get; set; }
|
||||
}
|
||||
|
||||
public record UploadImageRequest
|
||||
{
|
||||
[Required]
|
||||
public DateTime Timestamp { get; set; }
|
||||
|
||||
[Required]
|
||||
public IFormFile? Image { get; set; }
|
||||
|
||||
[Required]
|
||||
public double Lat { get; set; }
|
||||
|
||||
[Required]
|
||||
public double Lon { get; set; }
|
||||
|
||||
[Required]
|
||||
public double Height { get; set; }
|
||||
|
||||
[Required]
|
||||
public double FocalLength { get; set; }
|
||||
|
||||
[Required]
|
||||
public double SensorWidth { get; set; }
|
||||
|
||||
[Required]
|
||||
public double SensorHeight { get; set; }
|
||||
}
|
||||
|
||||
public record SaveResult
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public string? Exception { get; set; }
|
||||
}
|
||||
|
||||
public record DownloadTileResponse
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public int ZoomLevel { get; set; }
|
||||
public double Latitude { get; set; }
|
||||
public double Longitude { get; set; }
|
||||
public double TileSizeMeters { get; set; }
|
||||
public int TileSizePixels { get; set; }
|
||||
public string ImageType { get; set; } = string.Empty;
|
||||
public string? MapsVersion { get; set; }
|
||||
public int? Version { get; set; }
|
||||
public string FilePath { get; set; } = string.Empty;
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
}
|
||||
|
||||
public record RequestRegionRequest
|
||||
{
|
||||
[Required]
|
||||
public Guid Id { get; set; }
|
||||
|
||||
[Required]
|
||||
public double Latitude { get; set; }
|
||||
|
||||
[Required]
|
||||
public double Longitude { get; set; }
|
||||
|
||||
[Required]
|
||||
public double SizeMeters { get; set; }
|
||||
|
||||
[Required]
|
||||
public int ZoomLevel { get; set; } = 18;
|
||||
|
||||
public bool StitchTiles { get; set; } = false;
|
||||
}
|
||||
|
||||
public class ParameterDescriptionFilter : IOperationFilter
|
||||
{
|
||||
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||
{
|
||||
if (operation.Parameters == null) return;
|
||||
|
||||
var parameterDescriptions = new Dictionary<string, string>
|
||||
{
|
||||
["lat"] = "Latitude coordinate where image was captured",
|
||||
["lon"] = "Longitude coordinate where image was captured",
|
||||
["mgrs"] = "MGRS coordinate string",
|
||||
["squareSideMeters"] = "Square side size in meters",
|
||||
["Latitude"] = "Latitude coordinate of the tile center",
|
||||
["Longitude"] = "Longitude coordinate of the tile center",
|
||||
["ZoomLevel"] = "Zoom level for the tile (higher values = more detail)"
|
||||
};
|
||||
|
||||
foreach (var parameter in operation.Parameters)
|
||||
{
|
||||
if (parameterDescriptions.TryGetValue(parameter.Name, out var description))
|
||||
{
|
||||
parameter.Description = description;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.21"/>
|
||||
<PackageReference Include="FluentValidation" Version="12.0.0" />
|
||||
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.7" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.7"/>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.11" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2"/>
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.7"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
using Microsoft.OpenApi;
|
||||
using Swashbuckle.AspNetCore.SwaggerGen;
|
||||
|
||||
namespace SatelliteProvider.Api.Swagger;
|
||||
|
||||
public class ParameterDescriptionFilter : IOperationFilter
|
||||
{
|
||||
public void Apply(OpenApiOperation operation, OperationFilterContext context)
|
||||
{
|
||||
if (operation.Parameters == null) return;
|
||||
|
||||
var parameterDescriptions = new Dictionary<string, string>
|
||||
{
|
||||
["lat"] = "Latitude coordinate (WGS84, decimal degrees, [-90, 90])",
|
||||
["lon"] = "Longitude coordinate (WGS84, decimal degrees, [-180, 180])",
|
||||
["zoom"] = "Slippy-map zoom level [0, 22] (higher = more detail)",
|
||||
["mgrs"] = "MGRS coordinate string",
|
||||
["squareSideMeters"] = "Square side size in meters"
|
||||
};
|
||||
|
||||
foreach (var parameter in operation.Parameters)
|
||||
{
|
||||
if (parameterDescriptions.TryGetValue(parameter.Name, out var description))
|
||||
{
|
||||
parameter.Description = description;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
using FluentValidation;
|
||||
using SatelliteProvider.Common.DTO;
|
||||
|
||||
namespace SatelliteProvider.Api.Validators;
|
||||
|
||||
// AZ-809: FluentValidation rules for POST /api/satellite/route. Wired
|
||||
// through ValidationEndpointFilter<CreateRouteRequest> at endpoint
|
||||
// registration time (.WithValidation<CreateRouteRequest>() in Program.cs).
|
||||
// Failures are converted to RFC 7807 ValidationProblemDetails per
|
||||
// _docs/02_document/contracts/api/error-shape.md v1.0.0.
|
||||
//
|
||||
// Required-field detection is handled at the deserializer level via
|
||||
// [JsonRequired] on CreateRouteRequest, RoutePoint, GeofencePolygon, and
|
||||
// GeoPoint, plus JsonSerializerOptions.UnmappedMemberHandling.Disallow
|
||||
// (AZ-795 global). This validator covers post-deserialization business
|
||||
// rules: non-zero id, name + description length, range checks on size /
|
||||
// zoom / points-count, per-point lat/lon ranges (via RoutePointValidator),
|
||||
// per-polygon corner ranges + NW-of-SE invariant (via GeofencePolygonValidator),
|
||||
// and the cross-field createTilesZip-implies-requestMaps rule.
|
||||
public sealed class CreateRouteRequestValidator : AbstractValidator<CreateRouteRequest>
|
||||
{
|
||||
private const double MinRegionSizeMeters = 100.0;
|
||||
private const double MaxRegionSizeMeters = 10000.0;
|
||||
private const int MinZoom = 0;
|
||||
private const int MaxZoom = 22;
|
||||
private const int MinPoints = 2;
|
||||
private const int MaxPoints = 500;
|
||||
private const int MaxNameLength = 200;
|
||||
private const int MaxDescriptionLength = 1000;
|
||||
// Geofences are axis-aligned bbox rectangles used for AOI restriction
|
||||
// during route planning (see route-creation.md). Realistic use is 1-10
|
||||
// polygons per route; cap at 50 to give 5x headroom while bounding the
|
||||
// validator's worst-case allocation. The global Kestrel body limit
|
||||
// (500 MiB, sized for the UAV upload endpoint) is not a useful gate
|
||||
// here because polygon JSON is small (~90 bytes per minimum-shape
|
||||
// polygon); without this cap a single authenticated request could
|
||||
// submit millions of polygons and saturate the LOH.
|
||||
private const int MaxPolygons = 50;
|
||||
|
||||
public CreateRouteRequestValidator()
|
||||
{
|
||||
RuleFor(req => req.Id)
|
||||
.NotEmpty()
|
||||
.WithMessage("`id` must be a non-zero GUID (the caller's idempotency key).");
|
||||
|
||||
RuleFor(req => req.Name)
|
||||
.NotEmpty()
|
||||
.WithMessage("`name` is required and must not be empty or whitespace.")
|
||||
.MaximumLength(MaxNameLength)
|
||||
.WithMessage($"`name` must be at most {MaxNameLength} characters.");
|
||||
|
||||
RuleFor(req => req.Description)
|
||||
.MaximumLength(MaxDescriptionLength)
|
||||
.When(req => req.Description is not null)
|
||||
.WithMessage($"`description` must be at most {MaxDescriptionLength} characters.");
|
||||
|
||||
RuleFor(req => req.RegionSizeMeters)
|
||||
.InclusiveBetween(MinRegionSizeMeters, MaxRegionSizeMeters)
|
||||
.WithMessage($"`regionSizeMeters` must be between {MinRegionSizeMeters} and {MaxRegionSizeMeters} meters.");
|
||||
|
||||
RuleFor(req => req.ZoomLevel)
|
||||
.InclusiveBetween(MinZoom, MaxZoom)
|
||||
.WithMessage($"`zoomLevel` must be between {MinZoom} and {MaxZoom} (slippy-map range).");
|
||||
|
||||
RuleFor(req => req.Points)
|
||||
.NotNull().WithMessage("`points` is required.")
|
||||
.Must(p => p is null || p.Count >= MinPoints)
|
||||
.WithMessage($"`points` must contain at least {MinPoints} entries.")
|
||||
.Must(p => p is null || p.Count <= MaxPoints)
|
||||
.WithMessage($"`points` must contain at most {MaxPoints} entries.");
|
||||
|
||||
RuleForEach(req => req.Points)
|
||||
.SetValidator(new RoutePointValidator());
|
||||
|
||||
// Geofences are optional; per-polygon rules apply only when present.
|
||||
// FluentValidation's default property-name policy drops the parent
|
||||
// chain on deep expressions like `req.Geofences!.Polygons` — it emits
|
||||
// only the leaf `polygons`. We OverridePropertyName explicitly so the
|
||||
// wire-format error keys match the JSON path callers actually post:
|
||||
// `errors["geofences.polygons"]` and `errors["geofences.polygons[i].…"]`.
|
||||
When(req => req.Geofences is not null, () =>
|
||||
{
|
||||
RuleFor(req => req.Geofences!.Polygons)
|
||||
.NotNull().WithMessage("`geofences.polygons` is required when `geofences` is present.")
|
||||
.NotEmpty().WithMessage("`geofences.polygons` must contain at least 1 polygon when `geofences` is present.")
|
||||
.Must(polygons => polygons is null || polygons.Count <= MaxPolygons)
|
||||
.WithMessage($"`geofences.polygons` must contain at most {MaxPolygons} polygons.")
|
||||
.OverridePropertyName("geofences.polygons");
|
||||
|
||||
RuleForEach(req => req.Geofences!.Polygons)
|
||||
.SetValidator(new GeofencePolygonValidator())
|
||||
.OverridePropertyName("geofences.polygons");
|
||||
});
|
||||
|
||||
// Cross-field invariant: cannot zip what wasn't downloaded.
|
||||
RuleFor(req => req)
|
||||
.Must(req => !(req.CreateTilesZip && !req.RequestMaps))
|
||||
.WithName("createTilesZip")
|
||||
.WithMessage("`createTilesZip` requires `requestMaps` to be true (can't zip what wasn't downloaded).");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using FluentValidation;
|
||||
using SatelliteProvider.Common.DTO;
|
||||
|
||||
namespace SatelliteProvider.Api.Validators;
|
||||
|
||||
// AZ-809: per-polygon validator invoked via RuleForEach on the parent
|
||||
// CreateRouteRequest (guarded by When(geofences != null) at the parent).
|
||||
// Enforces both corner-point shape and the "NW is north-of and west-of SE"
|
||||
// invariant.
|
||||
//
|
||||
// Error path: errors keys land at `geofences.polygons[i].northWest.lat` etc.
|
||||
public sealed class GeofencePolygonValidator : AbstractValidator<GeofencePolygon>
|
||||
{
|
||||
private const double MinLat = -90.0;
|
||||
private const double MaxLat = 90.0;
|
||||
private const double MinLon = -180.0;
|
||||
private const double MaxLon = 180.0;
|
||||
|
||||
public GeofencePolygonValidator()
|
||||
{
|
||||
// Both corners must be present. Without them no useful range/cross-field
|
||||
// check can run, so short-circuit via .Cascade(CascadeMode.Stop).
|
||||
RuleFor(p => p.NorthWest)
|
||||
.Cascade(CascadeMode.Stop)
|
||||
.NotNull().WithMessage("`northWest` corner is required.")
|
||||
.SetValidator(new GeoCornerValidator("northWest")!);
|
||||
|
||||
RuleFor(p => p.SouthEast)
|
||||
.Cascade(CascadeMode.Stop)
|
||||
.NotNull().WithMessage("`southEast` corner is required.")
|
||||
.SetValidator(new GeoCornerValidator("southEast")!);
|
||||
|
||||
// Cross-field invariant: NW must be genuinely north-of (lat greater)
|
||||
// AND west-of (lon smaller) SE. Only runs when both corners survived
|
||||
// the NotNull check above; FluentValidation skips the rule if either
|
||||
// is null (.When(...) guard below).
|
||||
RuleFor(p => p)
|
||||
.Must(HaveNorthWestActuallyNorthOfSouthEast)
|
||||
.When(p => p.NorthWest is not null && p.SouthEast is not null)
|
||||
.WithName("northWest")
|
||||
.WithMessage("`northWest.lat` must be greater than `southEast.lat` (NW is north-of SE).");
|
||||
|
||||
RuleFor(p => p)
|
||||
.Must(HaveNorthWestActuallyWestOfSouthEast)
|
||||
.When(p => p.NorthWest is not null && p.SouthEast is not null)
|
||||
.WithName("northWest")
|
||||
.WithMessage("`northWest.lon` must be less than `southEast.lon` (NW is west-of SE).");
|
||||
}
|
||||
|
||||
private static bool HaveNorthWestActuallyNorthOfSouthEast(GeofencePolygon polygon)
|
||||
=> polygon.NorthWest!.Lat > polygon.SouthEast!.Lat;
|
||||
|
||||
private static bool HaveNorthWestActuallyWestOfSouthEast(GeofencePolygon polygon)
|
||||
=> polygon.NorthWest!.Lon < polygon.SouthEast!.Lon;
|
||||
|
||||
// Inner per-corner validator. Kept private to this file because the
|
||||
// polygon corners are the only consumer; if a sibling endpoint needs
|
||||
// point-shape validation, promote and rename.
|
||||
private sealed class GeoCornerValidator : AbstractValidator<GeoPoint>
|
||||
{
|
||||
public GeoCornerValidator(string cornerLabel)
|
||||
{
|
||||
RuleFor(g => g.Lat)
|
||||
.InclusiveBetween(MinLat, MaxLat)
|
||||
.WithMessage($"`{cornerLabel}.lat` must be between {MinLat} and {MaxLat}.");
|
||||
|
||||
RuleFor(g => g.Lon)
|
||||
.InclusiveBetween(MinLon, MaxLon)
|
||||
.WithMessage($"`{cornerLabel}.lon` must be between {MinLon} and {MaxLon}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using FluentValidation;
|
||||
using SatelliteProvider.Api.DTOs;
|
||||
|
||||
namespace SatelliteProvider.Api.Validators;
|
||||
|
||||
// AZ-811: FluentValidation rules for the query-string surface of
|
||||
// GET /api/satellite/tiles/latlon. Wired through
|
||||
// ValidationEndpointFilter<GetTileByLatLonQuery> at endpoint registration
|
||||
// time (.WithValidation<GetTileByLatLonQuery>() in Program.cs).
|
||||
//
|
||||
// Each rule maps 1:1 to a query parameter; errors[] keys are camelCase per
|
||||
// GlobalValidatorConfig (matching the wire-format param names `lat`, `lon`,
|
||||
// `zoom`). Required-field detection is `NotNull()` on the nullable-bound
|
||||
// DTO (see GetTileByLatLonQuery for why properties are nullable). Each rule
|
||||
// uses CascadeMode.Stop so a missing param surfaces ONLY as
|
||||
// "`lat` is required" — not also "`lat` must be between -90 and 90" with a
|
||||
// null value. Unknown query parameters are caught upstream by
|
||||
// RejectUnknownQueryParamsEndpointFilter.
|
||||
public sealed class GetTileByLatLonQueryValidator : AbstractValidator<GetTileByLatLonQuery>
|
||||
{
|
||||
private const double MinLat = -90.0;
|
||||
private const double MaxLat = 90.0;
|
||||
private const double MinLon = -180.0;
|
||||
private const double MaxLon = 180.0;
|
||||
private const int MinZoom = 0;
|
||||
private const int MaxZoom = 22;
|
||||
|
||||
public GetTileByLatLonQueryValidator()
|
||||
{
|
||||
RuleFor(q => q.Lat)
|
||||
.Cascade(CascadeMode.Stop)
|
||||
.NotNull().WithMessage("`lat` is required.")
|
||||
.InclusiveBetween(MinLat, MaxLat).WithMessage($"`lat` must be between {MinLat} and {MaxLat}.");
|
||||
|
||||
RuleFor(q => q.Lon)
|
||||
.Cascade(CascadeMode.Stop)
|
||||
.NotNull().WithMessage("`lon` is required.")
|
||||
.InclusiveBetween(MinLon, MaxLon).WithMessage($"`lon` must be between {MinLon} and {MaxLon}.");
|
||||
|
||||
RuleFor(q => q.Zoom)
|
||||
.Cascade(CascadeMode.Stop)
|
||||
.NotNull().WithMessage("`zoom` is required.")
|
||||
.InclusiveBetween(MinZoom, MaxZoom).WithMessage($"`zoom` must be between {MinZoom} and {MaxZoom} (slippy-map range).");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace SatelliteProvider.Api.Validators;
|
||||
|
||||
// AZ-795 / AZ-796: process-wide FluentValidation configuration shared by the
|
||||
// API host and unit tests. Tests must call ApplyOnce() in their fixture setup
|
||||
// so the property-name casing they assert against matches what the running
|
||||
// API will produce — see `_docs/02_document/contracts/api/error-shape.md`
|
||||
// invariant Inv-4 (camelCase paths in `errors` map).
|
||||
public static class GlobalValidatorConfig
|
||||
{
|
||||
private static readonly object _gate = new();
|
||||
private static bool _applied;
|
||||
|
||||
public static void ApplyOnce()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_applied) return;
|
||||
|
||||
ValidatorOptions.Global.PropertyNameResolver = (type, member, expression) =>
|
||||
{
|
||||
var name = member?.Name;
|
||||
if (string.IsNullOrEmpty(name)) return null;
|
||||
return char.ToLowerInvariant(name[0]) + name[1..];
|
||||
};
|
||||
|
||||
_applied = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using FluentValidation;
|
||||
using SatelliteProvider.Common.DTO;
|
||||
|
||||
namespace SatelliteProvider.Api.Validators;
|
||||
|
||||
// AZ-796: FluentValidation rules for POST /api/satellite/tiles/inventory.
|
||||
// Wired through ValidationEndpointFilter<TileInventoryRequest> at endpoint
|
||||
// registration time (`WithValidation<TileInventoryRequest>()` in Program.cs).
|
||||
// Failures are converted to RFC 7807 ValidationProblemDetails per
|
||||
// `_docs/02_document/contracts/api/error-shape.md` v1.0.0.
|
||||
//
|
||||
// Required-field detection (rules 5+) is partially handled at the deserializer
|
||||
// level via `[JsonRequired]` on TileCoord.Z/X/Y plus
|
||||
// `JsonSerializerOptions.UnmappedMemberHandling.Disallow` (AZ-795). This
|
||||
// validator covers the non-deserializer-detectable rules: XOR populated,
|
||||
// per-array entry caps, and slippy-map range constraints.
|
||||
public sealed class InventoryRequestValidator : AbstractValidator<TileInventoryRequest>
|
||||
{
|
||||
public InventoryRequestValidator()
|
||||
{
|
||||
RuleFor(req => req).Custom((req, ctx) =>
|
||||
{
|
||||
var hasTiles = req.Tiles is { Count: > 0 };
|
||||
var hasHashes = req.LocationHashes is { Count: > 0 };
|
||||
if (hasTiles == hasHashes)
|
||||
{
|
||||
ctx.AddFailure(
|
||||
"$",
|
||||
"Populate exactly one of `tiles` or `locationHashes` (sending both, or neither, is not allowed).");
|
||||
}
|
||||
});
|
||||
|
||||
RuleFor(req => req.Tiles!.Count)
|
||||
.LessThanOrEqualTo(TileInventoryLimits.MaxEntriesPerRequest)
|
||||
.OverridePropertyName("tiles")
|
||||
.WithMessage($"`tiles` must contain at most {TileInventoryLimits.MaxEntriesPerRequest} entries.")
|
||||
.When(req => req.Tiles is not null);
|
||||
|
||||
RuleFor(req => req.LocationHashes!.Count)
|
||||
.LessThanOrEqualTo(TileInventoryLimits.MaxEntriesPerRequest)
|
||||
.OverridePropertyName("locationHashes")
|
||||
.WithMessage($"`locationHashes` must contain at most {TileInventoryLimits.MaxEntriesPerRequest} entries.")
|
||||
.When(req => req.LocationHashes is not null);
|
||||
|
||||
RuleForEach(req => req.Tiles)
|
||||
.SetValidator(new TileCoordValidator())
|
||||
.When(req => req.Tiles is not null);
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class TileCoordValidator : AbstractValidator<TileCoord>
|
||||
{
|
||||
private const int MaxZoom = 22;
|
||||
|
||||
public TileCoordValidator()
|
||||
{
|
||||
RuleFor(c => c.Z)
|
||||
.InclusiveBetween(0, MaxZoom)
|
||||
.WithMessage($"`z` must be between 0 and {MaxZoom} (slippy-map zoom range).");
|
||||
|
||||
RuleFor(c => c.X)
|
||||
.GreaterThanOrEqualTo(0)
|
||||
.WithMessage("`x` must be ≥ 0.")
|
||||
.Must((coord, x) => coord.Z >= 0 && coord.Z <= MaxZoom && x < (1L << coord.Z))
|
||||
.WithMessage(coord => $"`x` must be < 2^z = {(coord.Z >= 0 && coord.Z <= MaxZoom ? (1L << coord.Z).ToString() : "<invalid z>")} for z={coord.Z}.");
|
||||
|
||||
RuleFor(c => c.Y)
|
||||
.GreaterThanOrEqualTo(0)
|
||||
.WithMessage("`y` must be ≥ 0.")
|
||||
.Must((coord, y) => coord.Z >= 0 && coord.Z <= MaxZoom && y < (1L << coord.Z))
|
||||
.WithMessage(coord => $"`y` must be < 2^z = {(coord.Z >= 0 && coord.Z <= MaxZoom ? (1L << coord.Z).ToString() : "<invalid z>")} for z={coord.Z}.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using FluentValidation;
|
||||
using SatelliteProvider.Common.DTO;
|
||||
|
||||
namespace SatelliteProvider.Api.Validators;
|
||||
|
||||
// AZ-808: FluentValidation rules for POST /api/satellite/request.
|
||||
// Wired through ValidationEndpointFilter<RequestRegionRequest> at endpoint
|
||||
// registration time (.WithValidation<RequestRegionRequest>() in Program.cs).
|
||||
// Failures are converted to RFC 7807 ValidationProblemDetails per
|
||||
// _docs/02_document/contracts/api/error-shape.md v1.0.0.
|
||||
//
|
||||
// Required-field detection is handled at the deserializer level via
|
||||
// [JsonRequired] on RequestRegionRequest properties plus
|
||||
// JsonSerializerOptions.UnmappedMemberHandling.Disallow (AZ-795). This
|
||||
// validator covers the post-deserialization business rules: non-zero Id,
|
||||
// lat/lon/sizeMeters/zoomLevel range constraints.
|
||||
public sealed class RegionRequestValidator : AbstractValidator<RequestRegionRequest>
|
||||
{
|
||||
private const double MinLat = -90.0;
|
||||
private const double MaxLat = 90.0;
|
||||
private const double MinLon = -180.0;
|
||||
private const double MaxLon = 180.0;
|
||||
private const double MinSizeMeters = 100.0;
|
||||
private const double MaxSizeMeters = 10000.0;
|
||||
private const int MinZoom = 0;
|
||||
private const int MaxZoom = 22;
|
||||
|
||||
public RegionRequestValidator()
|
||||
{
|
||||
RuleFor(req => req.Id)
|
||||
.NotEmpty()
|
||||
.WithMessage("`id` must be a non-zero GUID (the caller's idempotency key).");
|
||||
|
||||
RuleFor(req => req.Lat)
|
||||
.InclusiveBetween(MinLat, MaxLat)
|
||||
.WithMessage($"`lat` must be between {MinLat} and {MaxLat}.");
|
||||
|
||||
RuleFor(req => req.Lon)
|
||||
.InclusiveBetween(MinLon, MaxLon)
|
||||
.WithMessage($"`lon` must be between {MinLon} and {MaxLon}.");
|
||||
|
||||
RuleFor(req => req.SizeMeters)
|
||||
.InclusiveBetween(MinSizeMeters, MaxSizeMeters)
|
||||
.WithMessage($"`sizeMeters` must be between {MinSizeMeters} and {MaxSizeMeters} meters.");
|
||||
|
||||
RuleFor(req => req.ZoomLevel)
|
||||
.InclusiveBetween(MinZoom, MaxZoom)
|
||||
.WithMessage($"`zoomLevel` must be between {MinZoom} and {MaxZoom} (slippy-map range).");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
namespace SatelliteProvider.Api.Validators;
|
||||
|
||||
// AZ-811: endpoint filter that rejects any query-string parameter outside an
|
||||
// allowed-set. ASP.NET model binding silently ignores unknown query params,
|
||||
// which means typos (e.g. `?latitude=` after AZ-812's rename to `lat`) bind
|
||||
// to the default value (0.0) and may produce a misleading 200 or a confusing
|
||||
// out-of-range 400 from the value-validator. This filter catches the typo at
|
||||
// the envelope level and returns a structured RFC 7807 ValidationProblemDetails
|
||||
// with errors[<paramName>] = "Unknown query parameter ...", matching the
|
||||
// shape produced by ValidationEndpointFilter<T> + GlobalExceptionHandler.
|
||||
//
|
||||
// Apply BEFORE ValidationEndpointFilter<T> so unknown-param errors precede
|
||||
// range checks against the bound default value.
|
||||
public sealed class RejectUnknownQueryParamsEndpointFilter : IEndpointFilter
|
||||
{
|
||||
private readonly HashSet<string> _allowedKeys;
|
||||
|
||||
public RejectUnknownQueryParamsEndpointFilter(IEnumerable<string> allowedKeys)
|
||||
{
|
||||
_allowedKeys = new HashSet<string>(allowedKeys, StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
|
||||
{
|
||||
var query = context.HttpContext.Request.Query;
|
||||
var unknown = query.Keys.Where(k => !_allowedKeys.Contains(k)).ToList();
|
||||
|
||||
if (unknown.Count > 0)
|
||||
{
|
||||
var errors = unknown.ToDictionary(
|
||||
k => k,
|
||||
k => new[]
|
||||
{
|
||||
$"Unknown query parameter `{k}`. Allowed: {string.Join(", ", _allowedKeys.Select(a => $"`{a}`"))}."
|
||||
});
|
||||
|
||||
return Results.ValidationProblem(errors);
|
||||
}
|
||||
|
||||
return await next(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using FluentValidation;
|
||||
using SatelliteProvider.Common.DTO;
|
||||
|
||||
namespace SatelliteProvider.Api.Validators;
|
||||
|
||||
// AZ-809: per-point validator invoked via RuleForEach on the parent
|
||||
// CreateRouteRequest. Each route waypoint must declare a valid WGS84
|
||||
// coordinate; the parent validator checks min/max count of the points
|
||||
// collection separately.
|
||||
//
|
||||
// Error path: errors keys land at `points[i].lat` / `points[i].lon` per
|
||||
// FluentValidation's default child-property naming + GlobalValidatorConfig
|
||||
// camelCase normalization (matches the wire format set by
|
||||
// [JsonPropertyName("lat"|"lon")] on RoutePoint).
|
||||
public sealed class RoutePointValidator : AbstractValidator<RoutePoint>
|
||||
{
|
||||
private const double MinLat = -90.0;
|
||||
private const double MaxLat = 90.0;
|
||||
private const double MinLon = -180.0;
|
||||
private const double MaxLon = 180.0;
|
||||
|
||||
public RoutePointValidator()
|
||||
{
|
||||
// `RoutePoint.Latitude` is the C# property name but the wire name is
|
||||
// `lat` via [JsonPropertyName]. OverridePropertyName chains AFTER the
|
||||
// first concrete rule (which provides the `TProperty` for the generic
|
||||
// extension) and aligns the FluentValidation error key with the wire
|
||||
// format — callers see `errors["points[i].lat"]` matching what they
|
||||
// posted rather than the camelCased C# name `latitude`.
|
||||
RuleFor(p => p.Latitude)
|
||||
.InclusiveBetween(MinLat, MaxLat)
|
||||
.WithMessage($"`lat` must be between {MinLat} and {MaxLat}.")
|
||||
.OverridePropertyName("lat");
|
||||
|
||||
RuleFor(p => p.Longitude)
|
||||
.InclusiveBetween(MinLon, MaxLon)
|
||||
.WithMessage($"`lon` must be between {MinLon} and {MaxLon}.")
|
||||
.OverridePropertyName("lon");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using FluentValidation;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SatelliteProvider.Common.Configs;
|
||||
using SatelliteProvider.Common.DTO;
|
||||
|
||||
namespace SatelliteProvider.Api.Validators;
|
||||
|
||||
// AZ-810: root validator for the UAV upload metadata envelope. Runs from
|
||||
// inside the custom `UavUploadValidationFilter` (the endpoint takes a
|
||||
// multipart form, so the standard `WithValidation<T>()` JSON-body filter
|
||||
// doesn't apply). Error keys come out as `errors.items[…]` from this
|
||||
// validator and are prefixed with `metadata.` by the filter, producing
|
||||
// `errors.metadata.items[…]` in the final ValidationProblemDetails per
|
||||
// `_docs/02_document/contracts/api/error-shape.md` v1.0.0.
|
||||
public sealed class UavTileBatchMetadataPayloadValidator : AbstractValidator<UavTileBatchMetadataPayload>
|
||||
{
|
||||
public UavTileBatchMetadataPayloadValidator(
|
||||
IOptions<UavQualityConfig> qualityConfig,
|
||||
TimeProvider? timeProvider = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(qualityConfig);
|
||||
var maxBatchSize = qualityConfig.Value.MaxBatchSize;
|
||||
|
||||
RuleFor(p => p.Items)
|
||||
.NotNull().WithMessage("`items` is required.")
|
||||
.NotEmpty().WithMessage("`items` must contain at least one entry.")
|
||||
.Must(items => items is null || items.Count <= maxBatchSize)
|
||||
.WithMessage($"`items` must contain at most {maxBatchSize} entries.");
|
||||
|
||||
RuleForEach(p => p.Items)
|
||||
.SetValidator(new UavTileMetadataValidator(qualityConfig, timeProvider));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using FluentValidation;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SatelliteProvider.Common.Configs;
|
||||
using SatelliteProvider.Common.DTO;
|
||||
|
||||
namespace SatelliteProvider.Api.Validators;
|
||||
|
||||
// AZ-810: per-item metadata validator for the UAV upload endpoint. Runs as
|
||||
// a `RuleForEach.SetValidator(...)` chain child of `UavTileBatchMetadataPayloadValidator`,
|
||||
// so error keys come out as `errors.metadata.items[i].latitude`, `…tileZoom`,
|
||||
// `…capturedAt`, etc. once the `UavUploadValidationFilter` prefixes the result.
|
||||
//
|
||||
// CapturedAt freshness (rule 11) is the same window that
|
||||
// `IUavTileQualityGate.Validate` enforces; running the same check at the API
|
||||
// boundary lets us short-circuit before any file bytes are inspected. The
|
||||
// gate remains as a defence-in-depth backstop for unit tests of the gate
|
||||
// itself and for the unlikely path of a caller invoking
|
||||
// `IUavTileUploadHandler` directly (bypassing the filter).
|
||||
public sealed class UavTileMetadataValidator : AbstractValidator<UavTileMetadata>
|
||||
{
|
||||
private const double MinLat = -90.0;
|
||||
private const double MaxLat = 90.0;
|
||||
private const double MinLon = -180.0;
|
||||
private const double MaxLon = 180.0;
|
||||
private const int MinZoom = 0;
|
||||
private const int MaxZoom = 22;
|
||||
|
||||
public UavTileMetadataValidator(IOptions<UavQualityConfig> qualityConfig, TimeProvider? timeProvider = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(qualityConfig);
|
||||
var cfg = qualityConfig.Value;
|
||||
var tp = timeProvider ?? TimeProvider.System;
|
||||
var maxAgeDays = cfg.MaxAgeDays;
|
||||
var futureSkewSeconds = cfg.CapturedAtFutureSkewSeconds;
|
||||
|
||||
RuleFor(m => m.Latitude)
|
||||
.InclusiveBetween(MinLat, MaxLat)
|
||||
.WithMessage($"`latitude` must be between {MinLat} and {MaxLat}.");
|
||||
|
||||
RuleFor(m => m.Longitude)
|
||||
.InclusiveBetween(MinLon, MaxLon)
|
||||
.WithMessage($"`longitude` must be between {MinLon} and {MaxLon}.");
|
||||
|
||||
RuleFor(m => m.TileZoom)
|
||||
.InclusiveBetween(MinZoom, MaxZoom)
|
||||
.WithMessage($"`tileZoom` must be between {MinZoom} and {MaxZoom} (slippy-map range).");
|
||||
|
||||
RuleFor(m => m.TileSizeMeters)
|
||||
.GreaterThan(0.0)
|
||||
.WithMessage("`tileSizeMeters` must be greater than 0.");
|
||||
|
||||
// Freshness window: capturedAt ∈ [now - MaxAgeDays, now + CapturedAtFutureSkewSeconds].
|
||||
// `Must` lambdas close over `tp` so the comparison fetches fresh
|
||||
// time per call (rule executes at validation time, not constructor
|
||||
// time). Equivalent to AZ-488 Rule 4 in UavTileQualityGate.
|
||||
RuleFor(m => m.CapturedAt)
|
||||
.Must(capturedAt => capturedAt.ToUniversalTime() <= tp.GetUtcNow().UtcDateTime.AddSeconds(futureSkewSeconds))
|
||||
.WithMessage($"`capturedAt` must be within {futureSkewSeconds}s of the current time (no future-dated tiles).")
|
||||
.Must(capturedAt => capturedAt.ToUniversalTime() >= tp.GetUtcNow().UtcDateTime.AddDays(-maxAgeDays))
|
||||
.WithMessage($"`capturedAt` must be within the last {maxAgeDays} days.");
|
||||
|
||||
// `FlightId` is intentionally not validated beyond JSON shape — AZ-503
|
||||
// anonymous-flight semantics require null/missing to be a valid case.
|
||||
// System.Text.Json already rejects malformed UUID strings at the
|
||||
// deserializer with `JsonException` → 400 via GlobalExceptionHandler.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System.Text.Json;
|
||||
using FluentValidation;
|
||||
using Microsoft.AspNetCore.Http.Json;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SatelliteProvider.Common.DTO;
|
||||
|
||||
namespace SatelliteProvider.Api.Validators;
|
||||
|
||||
// AZ-810: endpoint filter for `POST /api/satellite/upload`. The endpoint is
|
||||
// `multipart/form-data`, not a plain JSON body, so the standard
|
||||
// `WithValidation<T>()` filter (which expects an `[FromBody]` argument
|
||||
// already deserialized by the binder) cannot be used. This filter reads
|
||||
// the multipart `metadata` form field, deserializes it with the strict
|
||||
// global `JsonSerializerOptions` (which includes
|
||||
// `UnmappedMemberHandling.Disallow` from AZ-795), runs the FluentValidation
|
||||
// rules on `UavTileBatchMetadataPayload`, and adds the cross-field
|
||||
// alignment check (`metadata.items.Count == files.Count`).
|
||||
//
|
||||
// Failures are returned as RFC 7807 `ValidationProblemDetails` matching
|
||||
// `_docs/02_document/contracts/api/error-shape.md` v1.0.0; error-map keys
|
||||
// are prefixed with `metadata.` so paths like `items[0].latitude` from
|
||||
// the per-item validator surface to the caller as
|
||||
// `errors["metadata.items[0].latitude"]`.
|
||||
//
|
||||
// The downstream `IUavTileUploadHandler` retains its own envelope checks
|
||||
// as a defence-in-depth backstop (also covers callers invoking the
|
||||
// handler directly in unit tests). When the filter has already validated,
|
||||
// the handler's checks are no-ops by construction.
|
||||
public sealed class UavUploadValidationFilter : IEndpointFilter
|
||||
{
|
||||
private const string MetadataKeyPrefix = "metadata.";
|
||||
private const string MetadataField = "metadata";
|
||||
private const string FilesField = "files";
|
||||
|
||||
private readonly IValidator<UavTileBatchMetadataPayload> _validator;
|
||||
private readonly JsonSerializerOptions _jsonOptions;
|
||||
|
||||
public UavUploadValidationFilter(
|
||||
IValidator<UavTileBatchMetadataPayload> validator,
|
||||
IOptions<JsonOptions> jsonOptions)
|
||||
{
|
||||
_validator = validator ?? throw new ArgumentNullException(nameof(validator));
|
||||
ArgumentNullException.ThrowIfNull(jsonOptions);
|
||||
_jsonOptions = jsonOptions.Value.SerializerOptions;
|
||||
}
|
||||
|
||||
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
|
||||
{
|
||||
var request = context.HttpContext.Request;
|
||||
if (!request.HasFormContentType)
|
||||
{
|
||||
return Results.ValidationProblem(new Dictionary<string, string[]>
|
||||
{
|
||||
[MetadataField] = new[] { "Request must be `multipart/form-data`." },
|
||||
});
|
||||
}
|
||||
|
||||
var form = await request.ReadFormAsync(context.HttpContext.RequestAborted);
|
||||
var metadataField = form[MetadataField].ToString();
|
||||
var files = form.Files;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(metadataField))
|
||||
{
|
||||
return Results.ValidationProblem(new Dictionary<string, string[]>
|
||||
{
|
||||
[MetadataField] = new[] { "`metadata` form field is required." },
|
||||
});
|
||||
}
|
||||
|
||||
UavTileBatchMetadataPayload? payload;
|
||||
try
|
||||
{
|
||||
payload = JsonSerializer.Deserialize<UavTileBatchMetadataPayload>(metadataField, _jsonOptions);
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
// System.Text.Json with UnmappedMemberHandling.Disallow + [JsonRequired]
|
||||
// covers: unknown root/nested fields, missing required fields, type
|
||||
// mismatches. Surface uniformly as `errors.metadata`.
|
||||
return Results.ValidationProblem(new Dictionary<string, string[]>
|
||||
{
|
||||
[MetadataField] = new[] { $"`metadata` could not be parsed as JSON: {ex.Message}" },
|
||||
});
|
||||
}
|
||||
|
||||
if (payload is null)
|
||||
{
|
||||
return Results.ValidationProblem(new Dictionary<string, string[]>
|
||||
{
|
||||
[MetadataField] = new[] { "`metadata` must be a non-null JSON object." },
|
||||
});
|
||||
}
|
||||
|
||||
var result = await _validator.ValidateAsync(payload, context.HttpContext.RequestAborted);
|
||||
if (!result.IsValid)
|
||||
{
|
||||
var prefixed = new Dictionary<string, string[]>(StringComparer.Ordinal);
|
||||
foreach (var group in result.ToDictionary())
|
||||
{
|
||||
prefixed[MetadataKeyPrefix + group.Key] = group.Value;
|
||||
}
|
||||
return Results.ValidationProblem(prefixed);
|
||||
}
|
||||
|
||||
if (payload.Items.Count != files.Count)
|
||||
{
|
||||
return Results.ValidationProblem(new Dictionary<string, string[]>
|
||||
{
|
||||
[MetadataKeyPrefix + "items"] = new[]
|
||||
{
|
||||
$"`metadata.items` has {payload.Items.Count} entries but `files` has {files.Count}.",
|
||||
},
|
||||
[FilesField] = new[]
|
||||
{
|
||||
$"`files` has {files.Count} entries but `metadata.items` has {payload.Items.Count}.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return await next(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace SatelliteProvider.Api.Validators;
|
||||
|
||||
// AZ-795: shared validation infrastructure. A generic IEndpointFilter that
|
||||
// resolves IValidator<T> from DI for the first argument of type T in the
|
||||
// invoked endpoint and returns RFC 7807 ValidationProblemDetails (HTTP 400)
|
||||
// with a structured `errors` map when the validator rejects. When validation
|
||||
// passes, the filter forwards to the next stage unchanged.
|
||||
//
|
||||
// The filter is generic per request type; per-endpoint wire-up is done via
|
||||
// `RouteHandlerBuilder.WithValidation<T>()` (see ValidationEndpointFilterExtensions).
|
||||
// Per AZ-795 Outcome: callers must NOT need per-endpoint try/catch boilerplate;
|
||||
// the filter provides the uniform error contract documented in
|
||||
// `_docs/02_document/contracts/api/error-shape.md`.
|
||||
public sealed class ValidationEndpointFilter<T> : IEndpointFilter where T : class
|
||||
{
|
||||
public async ValueTask<object?> InvokeAsync(
|
||||
EndpointFilterInvocationContext context,
|
||||
EndpointFilterDelegate next)
|
||||
{
|
||||
var argument = context.Arguments.OfType<T>().FirstOrDefault();
|
||||
if (argument is null)
|
||||
{
|
||||
return await next(context);
|
||||
}
|
||||
|
||||
var validator = context.HttpContext.RequestServices.GetService<IValidator<T>>();
|
||||
if (validator is null)
|
||||
{
|
||||
return await next(context);
|
||||
}
|
||||
|
||||
var result = await validator.ValidateAsync(argument, context.HttpContext.RequestAborted);
|
||||
if (!result.IsValid)
|
||||
{
|
||||
return Results.ValidationProblem(result.ToDictionary());
|
||||
}
|
||||
|
||||
return await next(context);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace SatelliteProvider.Api.Validators;
|
||||
|
||||
// AZ-795: ergonomic extension method for opting an endpoint into
|
||||
// FluentValidation. Applied at MapPost/MapGet registration time:
|
||||
//
|
||||
// app.MapPost("/api/satellite/tiles/inventory", GetTilesInventory)
|
||||
// .WithValidation<TileInventoryRequest>();
|
||||
//
|
||||
// One line per endpoint; no per-handler try/catch boilerplate; uniform
|
||||
// RFC 7807 error shape — see `_docs/02_document/contracts/api/error-shape.md`.
|
||||
public static class ValidationEndpointFilterExtensions
|
||||
{
|
||||
public static RouteHandlerBuilder WithValidation<T>(this RouteHandlerBuilder builder)
|
||||
where T : class
|
||||
{
|
||||
builder.AddEndpointFilter<ValidationEndpointFilter<T>>();
|
||||
return builder;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,12 @@
|
||||
}
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Host=localhost;Port=5432;Database=satelliteprovider;Username=postgres;Password=postgres"
|
||||
"DefaultConnection": "Host=localhost;Port=5433;Database=satelliteprovider;Username=postgres;Password=postgres"
|
||||
},
|
||||
"Jwt": {
|
||||
"Secret": "DEV-ONLY-DO-NOT-USE-IN-PROD-replace-with-real-secret-via-JWT_SECRET-env-var",
|
||||
"Issuer": "DEV-ONLY-iss-admin-azaion-local",
|
||||
"Audience": "DEV-ONLY-aud-satellite-provider"
|
||||
},
|
||||
"MapConfig": {
|
||||
"Service": "GoogleMaps",
|
||||
|
||||
@@ -23,9 +23,27 @@
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Host=localhost;Database=satelliteprovider;Username=postgres;Password=postgres"
|
||||
},
|
||||
"Jwt": {
|
||||
"Secret": "",
|
||||
"Issuer": "",
|
||||
"Audience": ""
|
||||
},
|
||||
"UavQuality": {
|
||||
"MinBytes": 5120,
|
||||
"MaxBytes": 5242880,
|
||||
"MaxAgeDays": 7,
|
||||
"CapturedAtFutureSkewSeconds": 30,
|
||||
"MinLuminanceVariance": 10.0,
|
||||
"MaxBatchSize": 100,
|
||||
"LuminanceSampleSize": 32
|
||||
},
|
||||
"MapConfig": {
|
||||
"Service": "GoogleMaps",
|
||||
"ApiKey": ""
|
||||
"ApiKey": "",
|
||||
"TileSizePixels": 256,
|
||||
"AllowedZoomLevels": [ 15, 16, 17, 18, 19 ],
|
||||
"RetryBaseDelaySeconds": 1,
|
||||
"RetryMaxDelaySeconds": 30
|
||||
},
|
||||
"StorageConfig": {
|
||||
"TilesDirectory": "./tiles",
|
||||
@@ -37,7 +55,11 @@
|
||||
"DefaultZoomLevel": 20,
|
||||
"QueueCapacity": 1000,
|
||||
"DelayBetweenRequestsMs": 50,
|
||||
"SessionTokenReuseCount": 100
|
||||
"SessionTokenReuseCount": 100,
|
||||
"RegionProcessingTimeoutSeconds": 300,
|
||||
"RouteProcessingPollIntervalSeconds": 5,
|
||||
"MaxRoutePointSpacingMeters": 200.0,
|
||||
"LatLonTolerance": 0.0001
|
||||
},
|
||||
"CorsConfig": {
|
||||
"AllowedOrigins": []
|
||||
|
||||
@@ -1,7 +1,17 @@
|
||||
namespace SatelliteProvider.Common.Configs;
|
||||
namespace SatelliteProvider.Common.Configs;
|
||||
|
||||
public class MapConfig
|
||||
{
|
||||
public string Service { get; set; } = null!;
|
||||
public string ApiKey { get; set; } = null!;
|
||||
|
||||
// AZ-371 / C18 — Google Maps tile constants promoted from source literals.
|
||||
// AZ-377 / C24 — DefaultTileSizePixels is the canonical pixel size of a Google Maps tile;
|
||||
// sites that cannot inject IOptions<MapConfig> (e.g. DataAccess.TileRepository) reference it
|
||||
// directly so the value still has one source of truth.
|
||||
public const int DefaultTileSizePixels = 256;
|
||||
public int TileSizePixels { get; set; } = DefaultTileSizePixels;
|
||||
public int[] AllowedZoomLevels { get; set; } = new[] { 15, 16, 17, 18, 19 };
|
||||
public int RetryBaseDelaySeconds { get; set; } = 1;
|
||||
public int RetryMaxDelaySeconds { get; set; } = 30;
|
||||
}
|
||||
@@ -8,5 +8,11 @@ public class ProcessingConfig
|
||||
public int QueueCapacity { get; set; } = 100;
|
||||
public int DelayBetweenRequestsMs { get; set; } = 50;
|
||||
public int SessionTokenReuseCount { get; set; } = 100;
|
||||
|
||||
// AZ-371 / C18 — operational levers promoted from source literals.
|
||||
public int RegionProcessingTimeoutSeconds { get; set; } = 300;
|
||||
public int RouteProcessingPollIntervalSeconds { get; set; } = 5;
|
||||
public double MaxRoutePointSpacingMeters { get; set; } = 200.0;
|
||||
public double LatLonTolerance { get; set; } = 0.0001;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace SatelliteProvider.Common.Configs;
|
||||
|
||||
// AZ-488: tunable thresholds for the UAV tile-upload quality gate.
|
||||
// Defaults are documented in `_docs/02_document/contracts/api/uav-tile-upload.md` v1.0.0.
|
||||
public class UavQualityConfig
|
||||
{
|
||||
public int MinBytes { get; set; } = 5 * 1024;
|
||||
public int MaxBytes { get; set; } = 5 * 1024 * 1024;
|
||||
public int MaxAgeDays { get; set; } = 7;
|
||||
public int CapturedAtFutureSkewSeconds { get; set; } = 30;
|
||||
public double MinLuminanceVariance { get; set; } = 10.0;
|
||||
public int MaxBatchSize { get; set; } = 100;
|
||||
public int LuminanceSampleSize { get; set; } = 32;
|
||||
}
|
||||
@@ -4,18 +4,35 @@ namespace SatelliteProvider.Common.DTO;
|
||||
|
||||
public class CreateRouteRequest
|
||||
{
|
||||
// AZ-809: [JsonRequired] enforces presence at the deserializer; range and
|
||||
// shape checks live in `SatelliteProvider.Api/Validators/CreateRouteRequestValidator`.
|
||||
// Description and Geofences remain optional. The legacy in-service
|
||||
// `RouteValidator` is left in place as defense-in-depth for direct
|
||||
// service-layer callers (e.g. unit tests).
|
||||
[JsonRequired]
|
||||
public Guid Id { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public string? Description { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
public double RegionSizeMeters { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
public int ZoomLevel { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
public List<RoutePoint> Points { get; set; } = new();
|
||||
|
||||
[JsonPropertyName("geofences")]
|
||||
public Geofences? Geofences { get; set; }
|
||||
|
||||
public bool RequestMaps { get; set; } = false;
|
||||
public bool CreateTilesZip { get; set; } = false;
|
||||
[JsonRequired]
|
||||
public bool RequestMaps { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
public bool CreateTilesZip { get; set; }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace SatelliteProvider.Common.DTO;
|
||||
|
||||
public record DownloadTileResponse
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public int ZoomLevel { get; set; }
|
||||
public double Latitude { get; set; }
|
||||
public double Longitude { get; set; }
|
||||
public double TileSizeMeters { get; set; }
|
||||
public int TileSizePixels { get; set; }
|
||||
public string ImageType { get; set; } = string.Empty;
|
||||
public int? Version { get; set; }
|
||||
public string FilePath { get; set; } = string.Empty;
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
}
|
||||
@@ -6,9 +6,11 @@ public class GeoPoint
|
||||
{
|
||||
const double PRECISION_TOLERANCE = 0.00005;
|
||||
|
||||
[JsonRequired]
|
||||
[JsonPropertyName("lat")]
|
||||
public double Lat { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
[JsonPropertyName("lon")]
|
||||
public double Lon { get; set; }
|
||||
|
||||
|
||||
@@ -4,15 +4,18 @@ namespace SatelliteProvider.Common.DTO;
|
||||
|
||||
public class GeofencePolygon
|
||||
{
|
||||
[JsonRequired]
|
||||
[JsonPropertyName("northWest")]
|
||||
public GeoPoint? NorthWest { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
[JsonPropertyName("southEast")]
|
||||
public GeoPoint? SouthEast { get; set; }
|
||||
}
|
||||
|
||||
public class Geofences
|
||||
{
|
||||
[JsonRequired]
|
||||
[JsonPropertyName("polygons")]
|
||||
public List<GeofencePolygon> Polygons { get; set; } = new();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace SatelliteProvider.Common.DTO;
|
||||
|
||||
public record GetSatelliteTilesResponse
|
||||
{
|
||||
public List<SatelliteTile> Tiles { get; set; } = new();
|
||||
}
|
||||
+4
-3
@@ -1,9 +1,11 @@
|
||||
using SatelliteProvider.Common.Enums;
|
||||
|
||||
namespace SatelliteProvider.Common.DTO;
|
||||
|
||||
public class RegionStatus
|
||||
public class RegionStatusResponse
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Status { get; set; } = string.Empty;
|
||||
public RegionStatus Status { get; set; }
|
||||
public string? CsvFilePath { get; set; }
|
||||
public string? SummaryFilePath { get; set; }
|
||||
public int TilesDownloaded { get; set; }
|
||||
@@ -11,4 +13,3 @@ public class RegionStatus
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace SatelliteProvider.Common.DTO;
|
||||
|
||||
// AZ-812 (cycle 8): wire-format renamed Latitude/Longitude → Lat/Lon (OSM
|
||||
// convention) and added [JsonPropertyName("lat"/"lon")] so the wire is
|
||||
// unambiguous under JsonSerializerOptions.UnmappedMemberHandling.Disallow
|
||||
// (AZ-795 cycle 7).
|
||||
//
|
||||
// AZ-808 (cycle 8): switched [Required] → [JsonRequired] on every property.
|
||||
// [Required] is DataAnnotations and is NOT enforced by System.Text.Json — the
|
||||
// 2026-05-22 black-box probe confirmed it: omitting `id` returned HTTP 200
|
||||
// with id=Guid.Empty (silent coercion). [JsonRequired] is enforced by the
|
||||
// STJ deserializer and fails with BadHttpRequestException(JsonException),
|
||||
// which the GlobalExceptionHandler converts to RFC 7807 ValidationProblemDetails.
|
||||
// Removed the in-property defaults (= 18 for ZoomLevel, = false for StitchTiles)
|
||||
// because [JsonRequired] forces the caller to declare intent.
|
||||
public record RequestRegionRequest
|
||||
{
|
||||
[JsonRequired]
|
||||
public Guid Id { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
[JsonPropertyName("lat")]
|
||||
public double Lat { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
[JsonPropertyName("lon")]
|
||||
public double Lon { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
public double SizeMeters { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
public int ZoomLevel { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
public bool StitchTiles { get; set; }
|
||||
}
|
||||
@@ -4,9 +4,11 @@ namespace SatelliteProvider.Common.DTO;
|
||||
|
||||
public class RoutePoint
|
||||
{
|
||||
[JsonRequired]
|
||||
[JsonPropertyName("lat")]
|
||||
public double Latitude { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
[JsonPropertyName("lon")]
|
||||
public double Longitude { get; set; }
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
using SatelliteProvider.Common.Enums;
|
||||
|
||||
namespace SatelliteProvider.Common.DTO;
|
||||
|
||||
public class RoutePointDto
|
||||
{
|
||||
public double Latitude { get; set; }
|
||||
public double Longitude { get; set; }
|
||||
public string PointType { get; set; } = string.Empty;
|
||||
public RoutePointType PointType { get; set; }
|
||||
public int SequenceNumber { get; set; }
|
||||
public int SegmentIndex { get; set; }
|
||||
public double? DistanceFromPrevious { get; set; }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using SatelliteProvider.Common.Utils;
|
||||
using SatelliteProvider.Common.Utils;
|
||||
|
||||
namespace SatelliteProvider.Common.DTO;
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace SatelliteProvider.Common.DTO;
|
||||
|
||||
public record SatelliteTile
|
||||
{
|
||||
public string TileId { get; set; } = string.Empty;
|
||||
public byte[] ImageData { get; set; } = Array.Empty<byte>();
|
||||
public double Lat { get; set; }
|
||||
public double Lon { get; set; }
|
||||
public int ZoomLevel { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace SatelliteProvider.Common.DTO;
|
||||
|
||||
public record SaveResult
|
||||
{
|
||||
public bool Success { get; set; }
|
||||
public string? Exception { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace SatelliteProvider.Common.DTO;
|
||||
|
||||
// AZ-505: bulk-list / inventory request envelope. Either `Tiles` OR
|
||||
// `LocationHashes` is populated — never both, never neither. The handler
|
||||
// converts every `(z, x, y)` coord into a `location_hash` via UUIDv5 and
|
||||
// queries `tiles_leaflet_path` once. Response order matches request order.
|
||||
//
|
||||
// Max entries per request: see TileInventoryLimits.MaxEntriesPerRequest.
|
||||
public sealed class TileInventoryRequest
|
||||
{
|
||||
public IReadOnlyList<TileCoord>? Tiles { get; set; }
|
||||
public IReadOnlyList<Guid>? LocationHashes { get; set; }
|
||||
}
|
||||
|
||||
// AZ-505: Slippy-map tile coordinate triple. AZ-794 (cycle 7) renamed the
|
||||
// wire-format fields from `tileZoom/tileX/tileY` → `z/x/y` to align with the
|
||||
// OSM / slippy-map convention already used by `GET /tiles/{z}/{x}/{y}` and
|
||||
// to shave wire-size on inventory requests carrying thousands of entries.
|
||||
// The C# property names (`Z`, `X`, `Y`) intentionally mirror the wire names
|
||||
// 1:1 so consumers don't need to mentally translate at the deserialization
|
||||
// boundary. The DataAccess `TileEntity.TileZoom/TileX/TileY` columns are
|
||||
// unchanged — that's a database identity, not a wire format.
|
||||
public sealed class TileCoord
|
||||
{
|
||||
[JsonRequired]
|
||||
public int Z { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
public int X { get; set; }
|
||||
|
||||
[JsonRequired]
|
||||
public int Y { get; set; }
|
||||
}
|
||||
|
||||
// AZ-505: Inventory response. Entries are returned in the SAME ORDER as the
|
||||
// matching request input (per AC-1). When Request.Tiles was populated, each
|
||||
// entry's `Z`/`X`/`Y` echoes the request entry; when Request.LocationHashes
|
||||
// was populated, the coord triple fields are 0 (the caller already knows
|
||||
// the hash and can map it back themselves). AZ-794 (cycle 7) renamed the
|
||||
// coord triple to `z/x/y` to align wire format with the URL-path
|
||||
// convention.
|
||||
public sealed class TileInventoryResponse
|
||||
{
|
||||
public IReadOnlyList<TileInventoryEntry> Results { get; set; } = Array.Empty<TileInventoryEntry>();
|
||||
}
|
||||
|
||||
// AZ-505: One entry per request input. `Present` indicates whether a row
|
||||
// exists in the `tiles` table for the resolved `LocationHash`. When
|
||||
// `Present == false` only `LocationHash` (and the echoed coord triple, if the
|
||||
// request used coords) is populated — the rest are null.
|
||||
//
|
||||
// `EstimatedBytes` is intentionally absent in v1.0.0 — adding the per-row
|
||||
// `stat()` cost is deferred until production profiling justifies it (see
|
||||
// AZ-505 Outcome bullet 1 + Excluded list).
|
||||
//
|
||||
// AZ-794 (cycle 7): coord triple renamed `tileZoom/tileX/tileY` → `z/x/y`
|
||||
// (contract bumped to v2.0.0).
|
||||
public sealed class TileInventoryEntry
|
||||
{
|
||||
public int Z { get; set; }
|
||||
public int X { get; set; }
|
||||
public int Y { get; set; }
|
||||
public Guid LocationHash { get; set; }
|
||||
public bool Present { get; set; }
|
||||
|
||||
public Guid? Id { get; set; }
|
||||
public DateTime? CapturedAt { get; set; }
|
||||
public string? Source { get; set; }
|
||||
public Guid? FlightId { get; set; }
|
||||
public double? ResolutionMPerPx { get; set; }
|
||||
}
|
||||
|
||||
// AZ-505: per-task constants exposed for the request validator + tests.
|
||||
// Living under DTO so both the API handler and test assertions can reference
|
||||
// the same value without re-deriving it.
|
||||
public static class TileInventoryLimits
|
||||
{
|
||||
// 2x headroom over the AC-4 perf gate of 2500 tiles. Anything larger is
|
||||
// rejected with HTTP 400 by the API handler.
|
||||
public const int MaxEntriesPerRequest = 5000;
|
||||
}
|
||||
@@ -11,7 +11,6 @@ public class TileMetadata
|
||||
public double TileSizeMeters { get; set; }
|
||||
public int TileSizePixels { get; set; }
|
||||
public string ImageType { get; set; } = string.Empty;
|
||||
public string? MapsVersion { get; set; }
|
||||
public int? Version { get; set; }
|
||||
public string FilePath { get; set; } = string.Empty;
|
||||
public DateTime CreatedAt { get; set; }
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
namespace SatelliteProvider.Common.DTO;
|
||||
|
||||
// AZ-488 / `uav-tile-upload.md` v1.0.0 — per-item response shape. Status and
|
||||
// RejectReason strings are part of the frozen contract; any change requires a
|
||||
// contract minor-version bump.
|
||||
public record UavTileBatchUploadResponse
|
||||
{
|
||||
public List<UavTileUploadResultItem> Items { get; init; } = new();
|
||||
}
|
||||
|
||||
public record UavTileUploadResultItem
|
||||
{
|
||||
public int Index { get; init; }
|
||||
public string Status { get; init; } = string.Empty;
|
||||
public Guid? TileId { get; init; }
|
||||
public string? RejectReason { get; init; }
|
||||
public string? RejectDetails { get; init; }
|
||||
}
|
||||
|
||||
public static class UavTileUploadStatus
|
||||
{
|
||||
public const string Accepted = "accepted";
|
||||
public const string Rejected = "rejected";
|
||||
}
|
||||
|
||||
// AZ-488: closed enumeration of reject reasons exposed through the v1.0.0
|
||||
// contract. Adding a new code REQUIRES a minor contract bump per the
|
||||
// Versioning Rules in `_docs/02_document/contracts/api/uav-tile-upload.md`.
|
||||
public static class UavTileRejectReasons
|
||||
{
|
||||
public const string InvalidFormat = "INVALID_FORMAT";
|
||||
public const string SizeOutOfBand = "SIZE_OUT_OF_BAND";
|
||||
public const string WrongDimensions = "WRONG_DIMENSIONS";
|
||||
public const string CapturedAtFuture = "CAPTURED_AT_FUTURE";
|
||||
public const string CapturedAtTooOld = "CAPTURED_AT_TOO_OLD";
|
||||
public const string ImageTooUniform = "IMAGE_TOO_UNIFORM";
|
||||
public const string MetadataMissing = "METADATA_MISSING";
|
||||
public const string StorageFailure = "STORAGE_FAILURE";
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace SatelliteProvider.Common.DTO;
|
||||
|
||||
// AZ-488 / `uav-tile-upload.md` v1.0.0 — per-tile metadata supplied with each
|
||||
// batch item. `CapturedAt` is normalized to UTC by the upload handler before
|
||||
// reaching the persistence layer.
|
||||
//
|
||||
// AZ-503: `FlightId` is optional. When provided, two UAVs uploading the same
|
||||
// (z, x, y) cell from different flights coexist as distinct DB rows and write
|
||||
// to per-flight on-disk paths (./tiles/uav/{flight_id}/{z}/{x}/{y}.jpg). When
|
||||
// absent, the row is treated as flight-anonymous and the UPSERT collapses to
|
||||
// the AZ-484 "single row per (cell, source)" semantics via COALESCE-to-zero.
|
||||
//
|
||||
// AZ-810 (cycle 8) added [JsonRequired] to every non-optional axis so the
|
||||
// deserializer rejects partial payloads with HTTP 400 + ValidationProblemDetails
|
||||
// via GlobalExceptionHandler BEFORE the FluentValidation + IUavTileQualityGate
|
||||
// layers run. FlightId stays optional per AZ-503 anonymous-flight semantics.
|
||||
public record UavTileMetadata
|
||||
{
|
||||
[JsonRequired]
|
||||
public double Latitude { get; init; }
|
||||
[JsonRequired]
|
||||
public double Longitude { get; init; }
|
||||
[JsonRequired]
|
||||
public int TileZoom { get; init; }
|
||||
[JsonRequired]
|
||||
public double TileSizeMeters { get; init; }
|
||||
[JsonRequired]
|
||||
public DateTime CapturedAt { get; init; }
|
||||
public Guid? FlightId { get; init; }
|
||||
}
|
||||
|
||||
public record UavTileBatchMetadataPayload
|
||||
{
|
||||
[JsonRequired]
|
||||
public List<UavTileMetadata> Items { get; init; } = new();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace SatelliteProvider.Common.Enums;
|
||||
|
||||
public enum RegionStatus
|
||||
{
|
||||
Queued,
|
||||
Processing,
|
||||
Completed,
|
||||
Failed,
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace SatelliteProvider.Common.Enums;
|
||||
|
||||
public enum RoutePointType
|
||||
{
|
||||
Start,
|
||||
End,
|
||||
Action,
|
||||
Intermediate,
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace SatelliteProvider.Common.Enums;
|
||||
|
||||
public enum TileSource
|
||||
{
|
||||
GoogleMaps,
|
||||
Uav,
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
namespace SatelliteProvider.Common.Enums;
|
||||
|
||||
// AZ-484: contract v1.0.0 stores TileSource as a snake_case string
|
||||
// ('google_maps', 'uav'). Dapper's TypeHandler<T> for enum types is bypassed
|
||||
// during deserialization (Dapper issue #259), so we cannot rely on a Dapper
|
||||
// handler to round-trip enum<->wire string. Instead, TileEntity stores the
|
||||
// wire value as a plain string and producers/consumers convert through this
|
||||
// helper at the boundary, preserving type safety in business code while
|
||||
// avoiding the Dapper enum read bug.
|
||||
public static class TileSourceConverter
|
||||
{
|
||||
public const string GoogleMapsWireValue = "google_maps";
|
||||
public const string UavWireValue = "uav";
|
||||
|
||||
public static string ToWireValue(TileSource value) => value switch
|
||||
{
|
||||
TileSource.GoogleMaps => GoogleMapsWireValue,
|
||||
TileSource.Uav => UavWireValue,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown TileSource"),
|
||||
};
|
||||
|
||||
public static TileSource FromWireValue(string wireValue)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(wireValue);
|
||||
|
||||
return wireValue.ToLowerInvariant() switch
|
||||
{
|
||||
GoogleMapsWireValue => TileSource.GoogleMaps,
|
||||
UavWireValue => TileSource.Uav,
|
||||
_ => throw new ArgumentException($"'{wireValue}' is not a defined member of enum TileSource", nameof(wireValue)),
|
||||
};
|
||||
}
|
||||
|
||||
public static bool IsValidWireValue(string? wireValue) =>
|
||||
wireValue is GoogleMapsWireValue or UavWireValue;
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using SixLabors.ImageSharp.Processing;
|
||||
|
||||
namespace SatelliteProvider.Common.Imaging;
|
||||
|
||||
// AZ-367 / C14: shared tile-grid stitcher.
|
||||
// Both region and route map generation previously implemented the same placement
|
||||
// loop (min/max of TileX/TileY, allocate Image<Rgb24>, foreach tile load + DrawImage
|
||||
// at (x-minX, y-minY) * tileSizePixels). The overlays (region center cross / route
|
||||
// geofence rectangles + route point crosses) differ and stay at the call sites.
|
||||
public sealed class TileGridStitcher
|
||||
{
|
||||
public async Task<StitchResult> StitchAsync(
|
||||
IEnumerable<TilePlacement> tiles,
|
||||
int tileSizePixels,
|
||||
bool deduplicateByTileCoords,
|
||||
bool swallowTileLoadErrors,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(tiles);
|
||||
if (tileSizePixels <= 0)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(tileSizePixels), tileSizePixels, "Tile size must be positive.");
|
||||
}
|
||||
|
||||
var sourceList = tiles.ToList();
|
||||
if (sourceList.Count == 0)
|
||||
{
|
||||
throw new InvalidOperationException("No tiles to stitch.");
|
||||
}
|
||||
|
||||
var orderedTiles = deduplicateByTileCoords
|
||||
? sourceList
|
||||
.GroupBy(t => (t.TileX, t.TileY))
|
||||
.Select(g => g.First())
|
||||
.OrderBy(t => t.TileY)
|
||||
.ThenBy(t => t.TileX)
|
||||
.ToList()
|
||||
: sourceList;
|
||||
|
||||
var minX = orderedTiles.Min(t => t.TileX);
|
||||
var maxX = orderedTiles.Max(t => t.TileX);
|
||||
var minY = orderedTiles.Min(t => t.TileY);
|
||||
var maxY = orderedTiles.Max(t => t.TileY);
|
||||
|
||||
var gridWidth = maxX - minX + 1;
|
||||
var gridHeight = maxY - minY + 1;
|
||||
var imageWidth = gridWidth * tileSizePixels;
|
||||
var imageHeight = gridHeight * tileSizePixels;
|
||||
|
||||
var stitchedImage = new Image<Rgb24>(imageWidth, imageHeight);
|
||||
var placed = new List<TilePlacement>(orderedTiles.Count);
|
||||
var missing = new List<MissingTile>();
|
||||
|
||||
try
|
||||
{
|
||||
foreach (var tile in orderedTiles)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
if (!File.Exists(tile.FilePath))
|
||||
{
|
||||
missing.Add(new MissingTile(tile, MissingTileReason.FileNotFound, Error: null));
|
||||
continue;
|
||||
}
|
||||
|
||||
Image<Rgb24>? tileImage = null;
|
||||
try
|
||||
{
|
||||
tileImage = await Image.LoadAsync<Rgb24>(tile.FilePath, cancellationToken);
|
||||
var destX = (tile.TileX - minX) * tileSizePixels;
|
||||
var destY = (tile.TileY - minY) * tileSizePixels;
|
||||
stitchedImage.Mutate(ctx => ctx.DrawImage(tileImage, new Point(destX, destY), 1f));
|
||||
placed.Add(tile);
|
||||
}
|
||||
catch (Exception ex) when (swallowTileLoadErrors && ex is not OperationCanceledException)
|
||||
{
|
||||
missing.Add(new MissingTile(tile, MissingTileReason.LoadFailed, ex));
|
||||
}
|
||||
finally
|
||||
{
|
||||
tileImage?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
stitchedImage.Dispose();
|
||||
throw;
|
||||
}
|
||||
|
||||
return new StitchResult(
|
||||
Image: stitchedImage,
|
||||
MinX: minX,
|
||||
MinY: minY,
|
||||
MaxX: maxX,
|
||||
MaxY: maxY,
|
||||
TileSizePixels: tileSizePixels,
|
||||
ImageWidth: imageWidth,
|
||||
ImageHeight: imageHeight,
|
||||
PlacedTiles: placed,
|
||||
MissingTiles: missing);
|
||||
}
|
||||
|
||||
public void DrawCross(Image<Rgb24> image, Point center, Rgb24 color, int armLength, int thickness = 10)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
if (armLength < 0 || thickness < 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var halfThickness = thickness / 2;
|
||||
var width = image.Width;
|
||||
var height = image.Height;
|
||||
|
||||
for (int dx = -armLength; dx <= armLength; dx++)
|
||||
{
|
||||
for (int t = -halfThickness; t <= halfThickness; t++)
|
||||
{
|
||||
int x = center.X + dx;
|
||||
int y = center.Y + t;
|
||||
if (x >= 0 && x < width && y >= 0 && y < height)
|
||||
{
|
||||
image[x, y] = color;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int dy = -armLength; dy <= armLength; dy++)
|
||||
{
|
||||
for (int t = -halfThickness; t <= halfThickness; t++)
|
||||
{
|
||||
int x = center.X + t;
|
||||
int y = center.Y + dy;
|
||||
if (x >= 0 && x < width && y >= 0 && y < height)
|
||||
{
|
||||
image[x, y] = color;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void DrawRectangleBorder(Image<Rgb24> image, Rectangle rect, Rgb24 color, int thickness = 5)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
if (thickness < 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var x1 = rect.X;
|
||||
var y1 = rect.Y;
|
||||
var x2 = rect.X + rect.Width - 1;
|
||||
var y2 = rect.Y + rect.Height - 1;
|
||||
var width = image.Width;
|
||||
var height = image.Height;
|
||||
|
||||
for (int t = 0; t < thickness; t++)
|
||||
{
|
||||
for (int x = x1; x <= x2; x++)
|
||||
{
|
||||
int topY = y1 + t;
|
||||
int bottomY = y2 - t;
|
||||
if (x >= 0 && x < width && topY >= 0 && topY < height)
|
||||
{
|
||||
image[x, topY] = color;
|
||||
}
|
||||
if (x >= 0 && x < width && bottomY >= 0 && bottomY < height)
|
||||
{
|
||||
image[x, bottomY] = color;
|
||||
}
|
||||
}
|
||||
|
||||
for (int y = y1; y <= y2; y++)
|
||||
{
|
||||
int leftX = x1 + t;
|
||||
int rightX = x2 - t;
|
||||
if (leftX >= 0 && leftX < width && y >= 0 && y < height)
|
||||
{
|
||||
image[leftX, y] = color;
|
||||
}
|
||||
if (rightX >= 0 && rightX < width && y >= 0 && y < height)
|
||||
{
|
||||
image[rightX, y] = color;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record TilePlacement(int TileX, int TileY, string FilePath);
|
||||
|
||||
public sealed record StitchResult(
|
||||
Image<Rgb24> Image,
|
||||
int MinX,
|
||||
int MinY,
|
||||
int MaxX,
|
||||
int MaxY,
|
||||
int TileSizePixels,
|
||||
int ImageWidth,
|
||||
int ImageHeight,
|
||||
IReadOnlyList<TilePlacement> PlacedTiles,
|
||||
IReadOnlyList<MissingTile> MissingTiles);
|
||||
|
||||
public sealed record MissingTile(TilePlacement Tile, MissingTileReason Reason, Exception? Error);
|
||||
|
||||
public enum MissingTileReason
|
||||
{
|
||||
FileNotFound,
|
||||
LoadFailed
|
||||
}
|
||||
@@ -4,8 +4,8 @@ namespace SatelliteProvider.Common.Interfaces;
|
||||
|
||||
public interface IRegionService
|
||||
{
|
||||
Task<RegionStatus> RequestRegionAsync(Guid id, double latitude, double longitude, double sizeMeters, int zoomLevel, bool stitchTiles = false);
|
||||
Task<RegionStatus?> GetRegionStatusAsync(Guid id);
|
||||
Task<RegionStatusResponse> RequestRegionAsync(Guid id, double latitude, double longitude, double sizeMeters, int zoomLevel, bool stitchTiles = false);
|
||||
Task<RegionStatusResponse?> GetRegionStatusAsync(Guid id);
|
||||
Task ProcessRegionAsync(Guid id, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,5 +9,11 @@ public interface ITileService
|
||||
Task<IEnumerable<TileMetadata>> GetTilesByRegionAsync(double latitude, double longitude, double sizeMeters, int zoomLevel);
|
||||
Task<TileBytes> GetOrDownloadTileAsync(int z, int x, int y, CancellationToken cancellationToken = default);
|
||||
Task<TileMetadata> DownloadAndStoreSingleTileAsync(double latitude, double longitude, int zoomLevel, CancellationToken cancellationToken = default);
|
||||
// AZ-505: bulk-list / inventory endpoint. Maps every request entry to its
|
||||
// location_hash, queries the repository in one round-trip, and returns one
|
||||
// response entry per request entry — in the same order. Callers are
|
||||
// expected to validate the request shape (`Tiles` XOR `LocationHashes`,
|
||||
// entry count cap) BEFORE invoking this method.
|
||||
Task<TileInventoryResponse> GetInventoryAsync(TileInventoryRequest request, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.11" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
using SatelliteProvider.Common.DTO;
|
||||
using SatelliteProvider.Common.DTO;
|
||||
|
||||
namespace SatelliteProvider.Common.Utils;
|
||||
|
||||
public static class GeoUtils
|
||||
{
|
||||
private const double EARTH_RADIUS = 6378137;
|
||||
public const double EarthRadiusMeters = 6378137d;
|
||||
public const double EarthEquatorialCircumferenceMeters = 40075016.686d;
|
||||
public const double MetersPerDegreeLatitude = 111000d;
|
||||
|
||||
public static (int x, int y) WorldToTilePos(GeoPoint point, int zoom)
|
||||
{
|
||||
@@ -29,7 +31,7 @@ public static class GeoUtils
|
||||
Math.Cos(lat1Rad) * Math.Cos(lat2Rad) *
|
||||
Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
|
||||
var c = 2 * Math.Asin(Math.Sqrt(a));
|
||||
var distance = EARTH_RADIUS * c;
|
||||
var distance = EarthRadiusMeters * c;
|
||||
|
||||
var y = Math.Sin(dLon) * Math.Cos(lat2Rad);
|
||||
var x = Math.Cos(lat1Rad) * Math.Sin(lat2Rad) -
|
||||
@@ -46,7 +48,7 @@ public static class GeoUtils
|
||||
|
||||
public static GeoPoint GoDirection(this GeoPoint startPoint, Direction direction)
|
||||
{
|
||||
var angularDistance = direction.Distance / EARTH_RADIUS;
|
||||
var angularDistance = direction.Distance / EarthRadiusMeters;
|
||||
var azimuthRadians = ToRadians(direction.Azimuth);
|
||||
var startLatRad = ToRadians(startPoint.Lat);
|
||||
var startLonRad = ToRadians(startPoint.Lon);
|
||||
@@ -73,11 +75,11 @@ public static class GeoUtils
|
||||
{
|
||||
var latRad = centerGeoPoint.Lat * Math.PI / 180.0;
|
||||
|
||||
var latDiff = (radiusM / EARTH_RADIUS) * (180.0 / Math.PI);
|
||||
var latDiff = (radiusM / EarthRadiusMeters) * (180.0 / Math.PI);
|
||||
var minLat = Math.Max(centerGeoPoint.Lat - latDiff, -90.0);
|
||||
var maxLat = Math.Min(centerGeoPoint.Lat + latDiff, 90.0);
|
||||
|
||||
var lonDiff = (radiusM / (EARTH_RADIUS * Math.Cos(latRad))) * (180.0 / Math.PI);
|
||||
var lonDiff = (radiusM / (EarthRadiusMeters * Math.Cos(latRad))) * (180.0 / Math.PI);
|
||||
var minLon = Math.Max(centerGeoPoint.Lon - lonDiff, -180.0);
|
||||
var maxLon = Math.Min(centerGeoPoint.Lon + lonDiff, 180.0);
|
||||
|
||||
@@ -125,9 +127,4 @@ public static class GeoUtils
|
||||
var centerLon = (northWest.Lon + southEast.Lon) / 2.0;
|
||||
return new GeoPoint(centerLat, centerLon);
|
||||
}
|
||||
|
||||
public static double CalculatePolygonDiagonalDistance(GeoPoint northWest, GeoPoint southEast)
|
||||
{
|
||||
return CalculateDistance(northWest, southEast);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace SatelliteProvider.Common.Utils;
|
||||
|
||||
// AZ-368 / C15: shared CSV writer for tile rows.
|
||||
// Both region and route pipelines previously emitted the same CSV (header
|
||||
// "latitude,longitude,file_path", same OrderByDescending(Latitude).ThenBy(Longitude)
|
||||
// ordering, same F6 numeric format). Two near-identical writers are now one.
|
||||
//
|
||||
// The class is instance-based (no static, per coderule.mdc — file I/O has side
|
||||
// effects). It carries no dependencies, so callers can `new TileCsvWriter()`
|
||||
// at use sites without DI bloat.
|
||||
public sealed class TileCsvWriter
|
||||
{
|
||||
public const string Header = "latitude,longitude,file_path";
|
||||
|
||||
public async Task WriteAsync(string filePath, IEnumerable<TileCsvRow> rows, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(filePath);
|
||||
ArgumentNullException.ThrowIfNull(rows);
|
||||
|
||||
var ordered = rows.OrderByDescending(r => r.Latitude).ThenBy(r => r.Longitude).ToList();
|
||||
|
||||
await using var writer = new StreamWriter(filePath);
|
||||
await writer.WriteLineAsync(Header.AsMemory(), cancellationToken);
|
||||
|
||||
foreach (var row in ordered)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var line = $"{row.Latitude:F6},{row.Longitude:F6},{row.FilePath}";
|
||||
await writer.WriteLineAsync(line.AsMemory(), cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record TileCsvRow(double Latitude, double Longitude, string FilePath);
|
||||
@@ -0,0 +1,94 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Globalization;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace SatelliteProvider.Common.Utils;
|
||||
|
||||
// AZ-503: pure-C# RFC 9562 (formerly RFC 4122 §4.3) UUIDv5 implementation.
|
||||
//
|
||||
// .NET 10 ships Guid.CreateVersion7 but NOT a version-5 builder, so we implement
|
||||
// the SHA-1-based algorithm here. Onboard `gps-denied-onboard/components/c6_tile_cache/_uuid.py`
|
||||
// MUST use the same TileNamespace constant and the same algorithm (Python's stdlib
|
||||
// uuid.uuid5 is identical by construction) so both sides of the wire compute
|
||||
// byte-identical IDs for the same (z, x, y, source, flight_id) inputs.
|
||||
//
|
||||
// Cross-repo namespace coordination: TileNamespace below is THE pinned value.
|
||||
// Any change here must be paired with the same change on the onboard side; the
|
||||
// AZ-503 task spec requires this and AC-1 (Python reference vectors) gates it.
|
||||
public static class Uuidv5
|
||||
{
|
||||
// Pinned cross-repo namespace for tile identity. Must match
|
||||
// gps-denied-onboard `c6_tile_cache/_uuid.py:TILE_NAMESPACE`.
|
||||
// Chosen as a fresh random UUID (no semantic meaning beyond being a stable
|
||||
// 128-bit constant shared between the two repos).
|
||||
public static readonly Guid TileNamespace = new("5b8d0c2e-7f1a-4d3b-9c5e-1f3a8e7d2b6c");
|
||||
|
||||
// AZ-505 consolidation: the canonical formula for a tile cell's
|
||||
// location_hash. Both TileRepository.GetByTileCoordinatesAsync and
|
||||
// TileService.GetInventoryAsync compute it; centralising here means the
|
||||
// cross-repo invariant (must byte-match gps-denied-onboard
|
||||
// `c6_tile_cache/_uuid.py:location_hash`) only has one source-of-truth in
|
||||
// this codebase. Format string is `"{z}/{x}/{y}"` under invariant culture —
|
||||
// matches the Python side's f-string output.
|
||||
public static Guid LocationHashForTile(int tileZoom, int tileX, int tileY)
|
||||
{
|
||||
var name = string.Create(CultureInfo.InvariantCulture, $"{tileZoom}/{tileX}/{tileY}");
|
||||
return Create(TileNamespace, name);
|
||||
}
|
||||
|
||||
public static Guid Create(Guid namespaceId, string name)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(name);
|
||||
|
||||
// Namespace UUIDs are concatenated as 16 bytes in network (big-endian)
|
||||
// order. .NET's Guid.ToByteArray() returns mixed-endian (RFC 4122
|
||||
// "Microsoft" layout), so we cannot use it directly — we must rebuild
|
||||
// the byte array in big-endian order, matching what Python's
|
||||
// uuid.UUID.bytes produces.
|
||||
Span<byte> namespaceBytes = stackalloc byte[16];
|
||||
WriteGuidBigEndian(namespaceId, namespaceBytes);
|
||||
|
||||
var nameBytes = Encoding.UTF8.GetBytes(name);
|
||||
|
||||
Span<byte> hash = stackalloc byte[20];
|
||||
var buffer = new byte[16 + nameBytes.Length];
|
||||
namespaceBytes.CopyTo(buffer);
|
||||
Buffer.BlockCopy(nameBytes, 0, buffer, 16, nameBytes.Length);
|
||||
if (!SHA1.TryHashData(buffer, hash, out _))
|
||||
{
|
||||
throw new InvalidOperationException("SHA-1 hash computation failed.");
|
||||
}
|
||||
|
||||
// Take first 16 bytes, set version to 5 (upper nibble of byte 6) and
|
||||
// variant to RFC 4122 (upper two bits of byte 8 set to `10`).
|
||||
Span<byte> uuidBytes = stackalloc byte[16];
|
||||
hash[..16].CopyTo(uuidBytes);
|
||||
uuidBytes[6] = (byte)((uuidBytes[6] & 0x0F) | 0x50);
|
||||
uuidBytes[8] = (byte)((uuidBytes[8] & 0x3F) | 0x80);
|
||||
|
||||
return ReadGuidBigEndian(uuidBytes);
|
||||
}
|
||||
|
||||
private static void WriteGuidBigEndian(Guid value, Span<byte> destination)
|
||||
{
|
||||
Span<byte> mixed = stackalloc byte[16];
|
||||
value.TryWriteBytes(mixed);
|
||||
// Convert from Microsoft mixed-endian (first 3 fields little-endian) to
|
||||
// network (big-endian) order.
|
||||
BinaryPrimitives.WriteUInt32BigEndian(destination[..4], BinaryPrimitives.ReadUInt32LittleEndian(mixed[..4]));
|
||||
BinaryPrimitives.WriteUInt16BigEndian(destination.Slice(4, 2), BinaryPrimitives.ReadUInt16LittleEndian(mixed.Slice(4, 2)));
|
||||
BinaryPrimitives.WriteUInt16BigEndian(destination.Slice(6, 2), BinaryPrimitives.ReadUInt16LittleEndian(mixed.Slice(6, 2)));
|
||||
mixed.Slice(8, 8).CopyTo(destination.Slice(8, 8));
|
||||
}
|
||||
|
||||
private static Guid ReadGuidBigEndian(ReadOnlySpan<byte> bigEndian)
|
||||
{
|
||||
Span<byte> mixed = stackalloc byte[16];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(mixed[..4], BinaryPrimitives.ReadUInt32BigEndian(bigEndian[..4]));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(mixed.Slice(4, 2), BinaryPrimitives.ReadUInt16BigEndian(bigEndian.Slice(4, 2)));
|
||||
BinaryPrimitives.WriteUInt16LittleEndian(mixed.Slice(6, 2), BinaryPrimitives.ReadUInt16BigEndian(bigEndian.Slice(6, 2)));
|
||||
bigEndian.Slice(8, 8).CopyTo(mixed.Slice(8, 8));
|
||||
return new Guid(mixed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
-- AZ-484: introduce per-source tile rows.
|
||||
-- Adds `source` and `captured_at` columns, backfills existing rows to
|
||||
-- (source='google_maps', captured_at=created_at), drops the 4-column unique index
|
||||
-- created by migration 012 (idx_tiles_unique_location), and replaces it with a
|
||||
-- 5-column unique index that includes `source`. The whole migration runs inside a
|
||||
-- single transaction so a failure mid-flight cannot leave the table without its
|
||||
-- unique index or with partially backfilled rows (per coderule.mdc and AZ-484
|
||||
-- Risk 1 mitigation).
|
||||
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE tiles ADD COLUMN IF NOT EXISTS source VARCHAR(32);
|
||||
ALTER TABLE tiles ADD COLUMN IF NOT EXISTS captured_at TIMESTAMP;
|
||||
|
||||
UPDATE tiles
|
||||
SET source = 'google_maps'
|
||||
WHERE source IS NULL;
|
||||
|
||||
UPDATE tiles
|
||||
SET captured_at = created_at
|
||||
WHERE captured_at IS NULL;
|
||||
|
||||
ALTER TABLE tiles ALTER COLUMN source SET NOT NULL;
|
||||
ALTER TABLE tiles ALTER COLUMN captured_at SET NOT NULL;
|
||||
|
||||
DROP INDEX IF EXISTS idx_tiles_unique_location;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_tiles_unique_location_source
|
||||
ON tiles (latitude, longitude, tile_zoom, tile_size_meters, source);
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,104 @@
|
||||
-- AZ-503-foundation: deterministic tile identity (UUIDv5) + multi-flight evidence preservation.
|
||||
--
|
||||
-- Adds four columns to `tiles`:
|
||||
-- - flight_id (uuid NULL) — per-UAV-flight identifier. NULL for google_maps and
|
||||
-- legacy UAV rows; populated for AZ-503+ UAV uploads.
|
||||
-- - location_hash (uuid NOT NULL) — UUIDv5(TILE_NAMESPACE, "{tile_zoom}/{tile_x}/{tile_y}").
|
||||
-- Drives leaflet hot-path lookups and future voting layer.
|
||||
-- - content_sha256 (bytea NULL) — SHA-256 of the JPEG body at insert time. NULL for legacy
|
||||
-- rows (pre-AZ-503), NOT NULL for new rows enforced at the
|
||||
-- application layer (TileEntity / repositories). Kept NULL-able
|
||||
-- at the column level because the migration cannot read tile
|
||||
-- files from disk safely (path may have moved, file may be
|
||||
-- gone). Application invariant: SHA-256 only meaningful when
|
||||
-- not NULL.
|
||||
-- - legacy_id (uuid NULL) — preserves the pre-AZ-503 random id of each row for one
|
||||
-- deprecation cycle (per AZ-503 Risk 1). Dropped in a
|
||||
-- follow-up migration once external references to legacy
|
||||
-- ids are confirmed flushed.
|
||||
--
|
||||
-- Switches the UPSERT conflict key from (latitude, longitude, tile_zoom, tile_size_meters, source)
|
||||
-- to an integer-only key with per-flight separation:
|
||||
-- (tile_zoom, tile_x, tile_y, tile_size_meters, source, COALESCE(flight_id, '00000000-...'::uuid))
|
||||
-- so two UAV flights uploading the same (z, x, y) cell coexist as distinct rows.
|
||||
--
|
||||
-- TILE_NAMESPACE is pinned cross-repo at 5b8d0c2e-7f1a-4d3b-9c5e-1f3a8e7d2b6c (matches
|
||||
-- SatelliteProvider.Common.Utils.Uuidv5.TileNamespace and gps-denied-onboard
|
||||
-- c6_tile_cache/_uuid.py). DO NOT change without updating both sides.
|
||||
--
|
||||
-- Whole migration runs inside one transaction; partial failure leaves the table without the
|
||||
-- new columns rather than half-migrated (per AZ-484 precedent for tile-table migrations).
|
||||
|
||||
BEGIN;
|
||||
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||
|
||||
-- Helper: pure-SQL UUIDv5 (SHA-1-based, RFC 9562 §5.5). Used ONLY for the
|
||||
-- location_hash backfill below. Application writes compute the same UUIDv5
|
||||
-- via SatelliteProvider.Common.Utils.Uuidv5.Create (verified byte-identical
|
||||
-- against Python uuid.uuid5 in AZ-503 AC-1).
|
||||
CREATE OR REPLACE FUNCTION pg_temp.uuidv5(namespace_uuid uuid, name text) RETURNS uuid AS $$
|
||||
DECLARE
|
||||
ns_bytes bytea;
|
||||
hash bytea;
|
||||
b6 int;
|
||||
b8 int;
|
||||
BEGIN
|
||||
-- Namespace UUID as 16 big-endian bytes.
|
||||
ns_bytes := decode(replace(namespace_uuid::text, '-', ''), 'hex');
|
||||
hash := substring(digest(ns_bytes || convert_to(name, 'UTF8'), 'sha1') from 1 for 16);
|
||||
-- Set version = 5 (upper nibble of byte 6).
|
||||
b6 := (get_byte(hash, 6) & 15) | 80;
|
||||
hash := set_byte(hash, 6, b6);
|
||||
-- Set RFC 4122 variant (upper 2 bits of byte 8 = 10).
|
||||
b8 := (get_byte(hash, 8) & 63) | 128;
|
||||
hash := set_byte(hash, 8, b8);
|
||||
RETURN encode(hash, 'hex')::uuid;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql IMMUTABLE;
|
||||
|
||||
ALTER TABLE tiles ADD COLUMN IF NOT EXISTS flight_id uuid;
|
||||
ALTER TABLE tiles ADD COLUMN IF NOT EXISTS location_hash uuid;
|
||||
ALTER TABLE tiles ADD COLUMN IF NOT EXISTS content_sha256 bytea;
|
||||
ALTER TABLE tiles ADD COLUMN IF NOT EXISTS legacy_id uuid;
|
||||
|
||||
-- Preserve the pre-AZ-503 random id under legacy_id for the deprecation window.
|
||||
UPDATE tiles
|
||||
SET legacy_id = id
|
||||
WHERE legacy_id IS NULL;
|
||||
|
||||
-- Backfill location_hash for every existing row. Deterministic; same algorithm
|
||||
-- the application uses for new writes.
|
||||
UPDATE tiles
|
||||
SET location_hash = pg_temp.uuidv5(
|
||||
'5b8d0c2e-7f1a-4d3b-9c5e-1f3a8e7d2b6c'::uuid,
|
||||
tile_zoom::text || '/' || tile_x::text || '/' || tile_y::text)
|
||||
WHERE location_hash IS NULL;
|
||||
|
||||
-- location_hash is now populated for every row; promote to NOT NULL.
|
||||
ALTER TABLE tiles ALTER COLUMN location_hash SET NOT NULL;
|
||||
|
||||
-- content_sha256 is intentionally left nullable for legacy rows (the migration cannot
|
||||
-- safely re-read tile files: paths may have rotated, files may be absent). The application
|
||||
-- layer enforces NOT NULL for all writes starting at AZ-503; legacy NULLs are treated as
|
||||
-- "unverified content" and surfaced as such if/when integrity checks are added downstream.
|
||||
|
||||
-- Drop AZ-484's lat/lon-keyed unique index and replace with the integer + flight_id key.
|
||||
DROP INDEX IF EXISTS idx_tiles_unique_location_source;
|
||||
DROP INDEX IF EXISTS idx_tiles_unique_location;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_tiles_unique_identity
|
||||
ON tiles (
|
||||
tile_zoom,
|
||||
tile_x,
|
||||
tile_y,
|
||||
tile_size_meters,
|
||||
source,
|
||||
COALESCE(flight_id, '00000000-0000-0000-0000-000000000000'::uuid)
|
||||
);
|
||||
|
||||
-- Lookup index on location_hash for application reads (kept lightweight here;
|
||||
-- the larger covering index `tiles_leaflet_path` is owned by AZ-505).
|
||||
CREATE INDEX IF NOT EXISTS idx_tiles_location_hash ON tiles (location_hash);
|
||||
|
||||
COMMIT;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user