107 Commits

Author SHA1 Message Date
Oleksandr Bezdieniezhnykh 62d6b8310a [AZ-808] [AZ-809] [AZ-810] [AZ-811] [AZ-812] Cycle 8 retro + close
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Cycle 8 retrospective (cycle-end mode): 5 tickets shipped, 17 SP, 4
batches across 1 cycle theme (strict input validation for the 4
AZ-795 child endpoints + AZ-812 region API field rename).

Artifacts:
- _docs/06_metrics/retro_2026-05-23_cycle8.md
- _docs/06_metrics/structure_2026-05-23_cycle8.md (gap-filled; last
  structural snapshot was cycle 5)

Key cycle-8 findings (now in _docs/LESSONS.md ring buffer):
- Step-14 security-audit Medium findings under the small-fix
  threshold should be resolved in-cycle, not deferred (F-AZ809-1
  closed in commit 8fca6e0, ~30 min from discovery to fix).
- Retro recommendations ship end-to-end when they name concrete
  tickets/files + size as a coherent cycle theme (cycle 7 Action 3
  -> cycle 8 strict-validation slate, first end-to-end traceable
  cross-cycle improvement action in project history).
- Contract wire-format updates (new required field / rename) need a
  ripgrep probe across all consumer paths (perf script, probe
  scripts, README, deploy docs, OpenAPI examples) — partial syncs
  surface at Step 15 perf gate (PT-06 missed AZ-809 requestMaps +
  createTilesZip, fixed in commit 32bc5c1).

Carry-overs to cycle 9: track PT-07 cache-pollution false positive
(harness, not regression), reduce 3 cycles in a row of misleading
"PT-07 fails on warm/cold ratio" entries in the perf report.

Marks Step 17 completed; cycle 8 closed. Next /autodev invocation
starts cycle 9 from Step 0.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 17:17:03 +03:00
Oleksandr Bezdieniezhnykh 32bc5c1e48 [AZ-808] [AZ-809] [AZ-810] [AZ-811] [AZ-812] Cycle 8 perf run
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
8/8 scenarios PASS within threshold. Cycle-8 strict-validation
overhead is below percentile resolution on every measured
endpoint.

PT-06 (route creation) required one in-cycle perf-script fix:
add requestMaps=false + createTilesZip=false to the body to
satisfy AZ-809's no-defaulting rule. The script had already
been updated for AZ-812's wire rename during cycle 8 but missed
AZ-809's newly required fields. Production code is correct; only
the perf probe was stale.

Report: _docs/06_metrics/perf_2026-05-23_cycle8.md. Trend vs
cycle 7 is flat within noise band on every scenario.

Known harness quirks (pre-existing, not cycle-8 regressions)
surfaced and documented for cleanup:
- PT-07 cross-run cache pollution (hard-coded base coords)
- PT-01 "cold" misnomer (tile cached on disk since cycle 5)
- PT-03 cached-by-PT-02 side effect (cycle-7 note carried forward)

Auto-chains to Step 16 (Deploy).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 16:10:12 +03:00
Oleksandr Bezdieniezhnykh 8fca6e0209 [AZ-809] F-AZ809-1: cap geofences.polygons at 50 (security audit)
Closes the cycle-8 Medium DoS finding. Without the cap, an
authenticated caller could submit millions of bbox polygons in a
single 500 MiB request (Kestrel global limit) and saturate the
FluentValidation allocator on the validator hot path; each polygon
is ~90 bytes of JSON, so the body limit is not a useful gate.

Realistic use is 1-10 polygons per route — 50 leaves 5x headroom
while bounding the worst-case allocation.

Layers:
- CreateRouteRequestValidator: MaxPolygons = 50 + Must(...) chained
  before RuleForEach so the count error fires at "geofences.polygons"
  (not the leaf path).
- Unit: Validate_GeofencePolygonsTooMany_FailsCountRule.
- Integration: GeofencePolygonsTooMany_Returns400 (51 valid bbox
  polygons -> HTTP 400 + errors["geofences.polygons"]).
- Contract: route-creation.md -> v1.0.1 patch (tightening an
  existing range). New Inv-10, new geofence-polygons-too-many
  test case, changelog row.
- Test spec: BT-29 sub-case 9b + AZ-809 AC-1b row in the
  traceability matrix.
- Security report: F-AZ809-1 marked RESOLVED in cycle 8; verdict
  remains PASS_WITH_WARNINGS (Lows + carry-overs unchanged).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 15:29:10 +03:00
Oleksandr Bezdieniezhnykh ac40a8b352 [AZ-808] [AZ-809] [AZ-810] [AZ-811] [AZ-812] Cycle 8 security audit
PASS_WITH_WARNINGS. Zero Critical / High.

New cycle-8 findings:
- F-AZ809-1 (Medium / A04 Insecure Design): unbounded
  geofences.polygons enables an authenticated DoS on
  POST /api/satellite/route. Cap candidate: 50 or 500.
- F-AZ810-1 (Low / A09): JsonException.Message echoed in
  UavUploadValidationFilter (new instance of cycle-7 F-AZ795-1
  pattern in a second code path).
- F-AZ810-2 (Low / Informational): UavTileMetadata.CapturedAt
  typed DateTime not DateTimeOffset; freshness window drifts in
  non-UTC dev environments. Zero impact in UTC-deployed prod.

Carry-overs (cycle 7): F-AZ795-1, F-AZ795-2, D-AZ795-1 still
open. Cycle 4 D2-cy4 still open (test-runtime Medium).

Cycle-8 architectural wins recorded: per-endpoint validation
reached 100% coverage; three approved validation paths
formalised; OSM wire-format normalisation under strict mode
(AZ-812); UAV-handler defence-in-depth retained.

Highest-priority cycle-9 follow-up: F-AZ809-1 polygon cap.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 15:17:31 +03:00
Oleksandr Bezdieniezhnykh 6207ab7c27 [AZ-808] [AZ-809] [AZ-810] [AZ-811] [AZ-812] Cycle 8 docs sync
Phase 13 of autodev existing-code flow — document skill in task
mode. Targeted updates to system-level docs that the per-batch
implementation commits did not already cover. Per-module docs
(api_program.md, common_dtos.md, system-flows.md F1/F2/F4) and
the 4 new contract docs (region-request.md, route-creation.md,
tile-latlon.md, uav-tile-upload.md v1.2.0) were already updated
during Step 10 batch commits and were verified-clean here.

architecture.md
- Bump contracts inventory line to mention uav-tile-upload.md v1.2.0
  (was v1.1.0) and add the four cycle-8 contracts (region-request,
  route-creation, tile-latlon, error-shape) so the contract index
  in architecture.md is no longer stale relative to the implemented
  endpoints.
- Add new architectural principle "Strict wire-format validation
  at the API edge (AZ-795 epic, completed across cycles 7-8)" to
  the Architectural Principles list. Describes the two-layer
  enforcement (deserializer + FluentValidation), the three approved
  per-endpoint paths (WithValidation<T> for JSON bodies,
  UavUploadValidationFilter for multipart, RejectUnknownQueryParams
  EndpointFilter + WithValidation<TQuery> for query strings), and
  the no-handler-without-validation rule.

ripple_log_cycle8.md
- New cycle-8 ripple log following the cycle-7 template. Documents
  every directly-changed source file, the importer scan results,
  doc refresh decisions, and the no-ripple component list.
- Records the AZ-795 epic posture: cycle 8 closes the per-endpoint
  rollout. Every public-facing JSON, multipart, and query-param
  endpoint now goes through one of the three approved paths. The
  exempt endpoints (GET region/{id}, GET route/{id}, GET tiles/mgrs
  stub, GET tiles/{z}/{x}/{y}) are listed with justification.

State
- Advance autodev to Step 14 (Security Audit), sub_step phase 0
  awaiting-choice.

No production code change; no test code change.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 14:32:57 +03:00
Oleksandr Bezdieniezhnykh ec0eb909a1 [AZ-808] [AZ-809] [AZ-810] [AZ-811] [AZ-812] Cycle 8 test-spec sync
Phase 12 of autodev existing-code flow — cycle-update mode of the
test-spec skill. Append cycle-8 coverage to the documentation suite
without rewriting any pre-cycle-8 content.

blackbox-tests.md
- Add 4 new BT entries (BT-28..BT-31) — one per cycle-8 endpoint:
  - BT-28: Region request endpoint strict validation + OSM rename
    (AZ-808 + AZ-812; 11 sub-cases through the new `RegionRequest
    Validator` + the AZ-795 deserializer infra; sub-case `pos` proves
    the new `lat`/`lon` names accepted, sub-case `9` proves the old
    `latitude`/`longitude` rejected by `UnmappedMemberHandling.Disallow`).
  - BT-29: Create route endpoint nested + cross-field validation
    (AZ-809; 15 sub-cases covering nested per-point validators,
    geofence cross-field invariants, and the `createTilesZip` /
    `requestMaps` cross-field rule; advisory ACs 9 + 10 explicitly
    NOT tested per spec).
  - BT-30: UAV upload metadata multipart validation (AZ-810; 14
    sub-cases across the three-layer composition: deserializer,
    FluentValidation, envelope cross-field; documents the unique
    `errors["metadata"]` vs `errors["metadata.items[i].field"]` key
    convention for multipart endpoints).
  - BT-31: GET tiles/latlon query-param validation + unknown-param
    rejection (AZ-811; 8 sub-cases; sub-cases 4b + 4c prove the
    novel `UnknownQueryParameterEndpointFilter` rejects both
    legacy and hostile unknown query keys).

traceability-matrix.md
- Append 41 AC rows (AZ-808 AC-1..AC-8, AZ-809 AC-1..AC-10,
  AZ-810 AC-1..AC-9, AZ-811 AC-1..AC-9, AZ-812 AC-1..AC-6).
- Update Coverage Summary: cycle-8 row added; Total moves from
  126 tests / 75 ACs to 167 tests / 116 ACs.
- Add "Coverage shape notes (Cycle 8 ...)" section explaining the
  multipart enforcement shape (AZ-810), the new query-param filter
  (AZ-811), the AZ-808 + AZ-812 same-cycle coordination, and the
  AZ-810 AC-9 process annotation (false-PASS by source tracing →
  bound to green full-suite re-run after the test-data coord-clamp
  fix in commit b763da3).
- AZ-809 AC-9 + AC-10 marked as `◐ advisory (not tested)` —
  naming-consistency concerns surfaced for parent-suite team
  decision.

State
- Advance autodev to Step 13 (Update Docs), sub_step phase 0
  awaiting-invocation.

No production code change; no contract change; no test code change.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 14:28:17 +03:00
Oleksandr Bezdieniezhnykh b763da3f24 [AZ-810] Clamp UAV test-fixture coordinates to OSM-valid range
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
The AZ-810 metadata validator rejects lat outside [-90, 90] and lon
outside [-180, 180]. Two NextTestCoordinate() helpers seeded their
counter from `(Ticks/TicksPerSecond) % 1_000_000` and returned
`60 + n*0.0005`, producing lat well above 90° for almost any seed
(e.g. n=200000 -> lat=160). Pre-AZ-810 there was no validator and no
DB constraint, so the out-of-range values were silently accepted; the
new validator (correctly) rejected them at HTTP 400.

Clamp both helpers to non-overlapping OSM-valid ranges:
  - UavUploadTests.cs:           lat in [50, 70),  lon in [10, 40)
  - UavUploadValidationTests.cs: lat in [-70, -50), lon in [-40, -10)

Non-overlap (not the prior +5_000_000 counter offset) is what now
guarantees AZ-488 and AZ-810 suites don't collide on the per-source
UNIQUE index when both run against the same DB.

No production code change; AZ-810 validator behaviour is unchanged.

Also:
- Correct AC-9 in batch_04_cycle8_report.md: the original claim
  ("verified by tracing source") was a false-PASS; the autodev
  Step 11 test run surfaced the gap. Now confirmed by full-suite
  green (scripts/run-tests.sh --full).
- Add ring-buffer lesson on AC-verification standards for input-
  validation changes: tracing fixture variables to their generators
  is insufficient; only a green integration-test run is sound
  evidence for a "no-regression" AC.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 14:20:45 +03:00
Oleksandr Bezdieniezhnykh bbe87835a9 [AZ-808] [AZ-809] [AZ-810] [AZ-811] [AZ-812] Cycle 8 close
Closes cycle 8 (Strict input validation across every public API
endpoint). After 4 batches, every JSON-body, multipart-envelope, and
query-parameter endpoint rejects unknown fields, missing required
axes, type mismatches, and business-rule violations BEFORE the
handler runs, all surfacing RFC 7807 ValidationProblemDetails per
error-shape.md v1.0.0.

Artifacts:

- cumulative_review_batches_01-04_cycle8_report.md
  PASS_WITH_WARNINGS. Cross-batch consistency check across all 5
  cycle-8 tasks: 0 Critical / 0 High / 0 Medium / 4 Low (all
  surfaced as per-batch findings; no NEW cumulative-only
  categories). 5 follow-up PBI candidates surfaced (test-helper
  consolidation, validator filter decision matrix in docs,
  RoutePointDto wire-shape unification, service-layer RouteValidator
  retirement decision).

- implementation_completeness_cycle8_report.md
  PASS. Every cycle-8 task promise is implemented as production
  behaviour. Production code verified for scaffold / placeholder /
  NotImplemented markers: none found in any cycle-8 validator. All
  five pipelines (region POST, lat/lon GET, route POST, upload
  POST, inventory POST) WIRED.

- implementation_report_strict_validation_cycle8.md
  Final cycle implementation report. 41 / 41 ACs covered across
  5 tasks (AZ-812, AZ-808, AZ-811, AZ-809, AZ-810). 63 new unit
  test methods + 52 new integration test methods + 4 new curl probe
  scripts + 3 new contract docs (region-request, tile-latlon,
  route-creation) + 1 contract version bump (uav-tile-upload
  v1.1.0 -> v1.2.0). Handoff to autodev Step 11 (Run Tests)
  documented.

Autodev state transitions Step 10 (Implement) -> Step 11 (Run Tests).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 13:32:31 +03:00
Oleksandr Bezdieniezhnykh 490902c80a [AZ-810] Strict validation for POST /api/satellite/upload metadata
Adds the per-endpoint child of AZ-795 ("Strict Input Validation Epic")
for the UAV upload multipart endpoint. Three new validators land under
SatelliteProvider.Api/Validators/:

- UavTileBatchMetadataPayloadValidator: items NotNull + NotEmpty +
  count <= MaxBatchSize + RuleForEach dispatching to the per-item
  validator.
- UavTileMetadataValidator: lat / lon / tileZoom range, tileSizeMeters
  > 0, capturedAt within [now - MaxAgeDays, now + future-skew]; uses an
  injectable TimeProvider so unit tests can drive a fixed clock.
- UavUploadValidationFilter: IEndpointFilter that reads the multipart
  `metadata` form field, deserializes it with the strict global
  JsonSerializerOptions (so UnmappedMemberHandling.Disallow +
  [JsonRequired] from AZ-795 are honored), runs the FluentValidation
  chain, and enforces the cross-field `items.Count == files.Count`
  envelope rule. FluentValidation errors are prefixed with `metadata.`
  so wire keys look like `errors["metadata.items[0].latitude"]`.

[JsonRequired] is added to every non-optional axis on
UavTileMetadata and UavTileBatchMetadataPayload; FlightId stays
nullable per AZ-503 anonymous-flight semantics.

Coverage: 13 unit tests + 16 integration tests + 1 curl probe script
exercise the happy path and every failure mode. All 9 ACs covered;
no regression in AZ-488 UavUploadTests payloads (traced against the
new rules).

Documentation: uav-tile-upload.md bumped v1.1.0 -> v1.2.0 with the
new validation rules section + 400-shape examples + changelog entry.
api_program.md updated to describe the three new validators + filter
+ the AddTransient<UavUploadValidationFilter>() DI registration.

Reports: batch_04_cycle8_report.md + reviews/batch_04_cycle8_review.md
record the PASS_WITH_WARNINGS verdict (2 Low DRY-in-tests findings:
FixedTimeProvider duplication crossed the cycle-2 "promote to shared"
threshold; PostBatch helper duplicated between two integration
suites). Both deferred to follow-up PBIs.

Task spec archived: _docs/02_tasks/todo/AZ-810... -> done/.
Jira: AZ-810 transitioned In Progress -> In Testing.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 13:32:19 +03:00
Oleksandr Bezdieniezhnykh 5e056b2334 [AZ-809] Strict validation for POST /api/satellite/route
Third concrete child of AZ-795 (cycle 8 batch 3). FluentValidation +
[JsonRequired] + UnmappedMemberHandling.Disallow combine to reject every
malformed payload at the API boundary with RFC 7807 ValidationProblemDetails.

Validators (SatelliteProvider.Api/Validators/, all new)
- CreateRouteRequestValidator: id non-empty, name/description length,
  regionSizeMeters/zoomLevel ranges, points count [2, 500], cross-field
  createTilesZip => requestMaps. Chains RoutePointValidator (per-point)
  and GeofencePolygonValidator (per-polygon, guarded by When(Geofences != null)).
  OverridePropertyName("geofences.polygons") on the geofences chain so
  FluentValidation's default leaf-only key policy doesn't drop the parent
  path on deep expressions like req.Geofences!.Polygons.
- RoutePointValidator: lat/lon ranges; OverridePropertyName("lat"/"lon")
  chained AFTER InclusiveBetween (the extension is defined on
  IRuleBuilderOptions<T, TProperty>, so the generic type is only
  inferable after the first concrete rule) so error keys match the
  wire format (`points[i].lat`) rather than the C# property name
  (`points[i].latitude`).
- GeofencePolygonValidator: per-corner range checks via private nested
  GeoCornerValidator; cross-field NW.Lat > SE.Lat and NW.Lon < SE.Lon
  invariants emit at errors["geofences.polygons[i].northWest"].

DTOs (SatelliteProvider.Common/DTO/, [JsonRequired] additions only)
- CreateRouteRequest: id, name, regionSizeMeters, zoomLevel, points,
  requestMaps, createTilesZip
- RoutePoint: Latitude, Longitude
- GeofencePolygon: NorthWest, SouthEast; Geofences: Polygons
- GeoPoint: Lat, Lon

Tests
- Unit: 26 methods total — 16 in CreateRouteRequestValidatorTests, 6 in
  GeofencePolygonValidatorTests, 4 in RoutePointValidatorTests. Each
  RuleFor/RuleForEach chain has at least one positive + one negative case.
- Integration: CreateRouteValidationTests.cs — 16 methods (happy + 15
  failure modes) wired into smoke + full suites. Covers empty body,
  missing/zero id, empty name, out-of-range regionSizeMeters/zoomLevel,
  points count < 2, per-point lat/lon out-of-range, geofence invariants,
  missing requestMaps, cross-field createTilesZip, unknown root field,
  nested type mismatch.
- Manual probe: scripts/probe_route_validation.sh curl-exercises every
  failure mode end-to-end + happy path.

Docs
- New contract _docs/02_document/contracts/api/route-creation.md v1.0.0
  with nested DTO chain, invariants, per-field test cases table, and
  advisories on the legacy service-layer RouteValidator + the
  input/output RoutePoint vs RoutePointDto naming asymmetry.
- system-flows.md F4 sequence diagram extended with the validation-filter
  branch; preconditions + error scenarios reference the new contract.
- modules/api_program.md: CreateRoute handler section added; Api/Validators
  bumped to AZ-808/AZ-809/AZ-811.
- modules/common_dtos.md: DTO descriptions updated with [JsonRequired]
  annotations and constraint summaries.
- tests/blackbox-tests.md BT-06/BT-N03/BT-N04/BT-N05 align with the new
  wire format and named error keys.
- tests/security-tests.md SEC-04 references GlobalExceptionHandler's
  JsonException branch + AZ-353 correlationId.
- _docs/03_implementation/batch_03_cycle8_report.md + reviews/batch_03_cycle8_review.md
  (PASS_WITH_NOTES — F1 Low: OverridePropertyName documented inline,
  F2 + F3 Info: pre-existing advisories for follow-up).

Smoke green (mode=smoke, exit 0). AZ-809 transitioned to In Testing on Jira.
Task file moved to _docs/02_tasks/done/.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 17:49:48 +03:00
Oleksandr Bezdieniezhnykh 34ee1e0b83 [AZ-808] [AZ-811] Strict validation on region POST + lat/lon GET
AZ-808: FluentValidation for POST /api/satellite/request
- RegionRequestValidator: id non-empty, lat/lon/sizeMeters/zoomLevel ranges
- RequestRegionRequest: [JsonRequired] on every property, no implicit defaults
- Wired via .WithValidation<RequestRegionRequest>() in MapPost chain
- Unit + integration tests + curl probe script
- New contract: contracts/api/region-request.md v1.0.0

AZ-811: FluentValidation + envelope filter for GET /api/satellite/tiles/latlon
- GetTileByLatLonQuery: nullable record (double?/int?) so the minimal-API
  binder never short-circuits with BadHttpRequestException before filters
- GetTileByLatLonQueryValidator: Cascade(Stop) + NotNull + InclusiveBetween
  per param; missing surfaces as `\`<name>\` is required.`
- RejectUnknownQueryParamsEndpointFilter: reusable IEndpointFilter that
  rejects any query key outside the allowed set with errors[<key>] map;
  catches legacy `?Latitude=` typos and hostile probes (`?debug=1&admin=1`)
- Handler: [AsParameters] GetTileByLatLonQuery + .Value deref post-validator
- Unit (validator + filter) + integration tests + curl probe script
- New contract: contracts/api/tile-latlon.md v1.0.0

Shared hygiene
- Promote AssertErrorsContainsMention from per-test-file private helpers to
  ProblemDetailsAssertions (closes batch-1 Low-severity DRY warning)
- Sync Swagger param descriptions, README, blackbox/security/perf scripts,
  uuidv5 doc with the new lat/lon/zoom query-param names

Docs
- system-flows.md F1/F2 reference the new contracts + validation layers
- modules/api_program.md adds Api/Validators + Api/DTOs sections
- _autodev_state.md: batch 2 of 4 complete; next batch = AZ-809

All smoke tests green (mode=smoke, exit 0). AZ-808 + AZ-811 transitioned
to In Testing on Jira.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 16:29:41 +03:00
Oleksandr Bezdieniezhnykh fcd494f67e [AZ-812] Region API: rename Latitude/Longitude → Lat/Lon (OSM convention)
Mirror of AZ-794 (inventory z/x/y rename). RequestRegionRequest.cs renames C#
props Latitude→Lat / Longitude→Lon and adds [JsonPropertyName("lat"/"lon")] so
the wire format is unambiguous under the AZ-795 strict-parsing stack
(UnmappedMemberHandling.Disallow → legacy {"latitude":..,"longitude":..} now
returns HTTP 400 instead of silently coercing).

Updates all in-repo consumers: API handler (Program.cs), integration tests
(Models.cs, RegionTests.cs, IdempotentPostTests.cs, SecurityTests.cs), the
performance harness (run-performance-tests.sh PT-03/04/05/07), and module
docs (common_dtos.md, api_program.md; system-flows.md F2 already used
lat/lon). New RegionFieldRenameTests.cs covers AC-4 both directions (new
format → 200, legacy format → 400). Smoke green; no regressions.

region-request.md contract doc not bumped here — AZ-808 publishes v1.0.0
directly with the post-rename names per AZ-812 coordination clause.

Batch 01 of cycle 8. PASS_WITH_WARNINGS (one Low DRY finding for follow-up
test-helper consolidation; details in
_docs/03_implementation/reviews/batch_01_cycle8_review.md).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 15:54:53 +03:00
Oleksandr Bezdieniezhnykh 0810a89ef1 Cycle 8 Step 10 start: autodev state -> Implement in_progress
Marks transition from Step 9 (New Task, closed in 06d160d) to
Step 10 (Implement) for cycle 8. Batch 1 begins next (AZ-812
DTO rename, per the ordering decision recorded in the cycle-8
deps-table section).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 13:01:04 +03:00
Oleksandr Bezdieniezhnykh 06d160daf0 [AZ-808] [AZ-809] [AZ-810] [AZ-811] [AZ-812] Cycle 8 Step 9 queued
Step 9 (New Task) closure for cycle 8. Queues 5 task specs under the
AZ-795 strict-validation umbrella + OSM-naming harmonization:

- AZ-808 region-request validator (POST /api/satellite/request)   3 pts
- AZ-809 route-creation validator (POST /api/satellite/route)     5 pts
- AZ-810 UAV upload metadata validator (POST /api/satellite/upload) 5 pts
- AZ-811 lat/lon GET validator (GET /api/satellite/tiles/latlon)  2 pts
- AZ-812 Region DTO rename latitude/longitude -> lat/lon          3 pts

Total 18 SP. Origin: cross-repo request from gps-denied-onboard
agent (2026-05-22) after AZ-777 Phase 2 black-box probe of the
Region API surfaced silent-coercion behavior + the lone OSM-deviating
coord naming convention left in the producer's public surface.

Ordering recorded (per /autodev Step 10 dirty-tree decision):
AZ-812 ships first so AZ-808 validator + contract doc + integration
tests are written against the final lat/lon names. AZ-809/AZ-810/AZ-811
are independent of AZ-812 (their DTOs already use OSM short form).

Deps table updated: cycle-8b (AZ-812) folded into cycle-8 ordering as
step 1; AZ-808 dependency upgraded SOFT -> HARD on AZ-812.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 13:00:34 +03:00
Oleksandr Bezdieniezhnykh 8c13cd4f30 Update autodev state to reflect task progress: status changed to 'in_progress' and sub_step phase updated to 1 with new name 'gather-feature-description'.
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
2026-05-22 11:44:27 +03:00
Oleksandr Bezdieniezhnykh a49f6c941b [AZ-794] [AZ-795] [AZ-796] Cycle 7 Step 17: retrospective + close cycle
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Cycle 7 retrospective (cycle-end mode) — three-task pure-quality
cycle (AZ-794 rename + AZ-795 epic shared infra + AZ-796 inventory
validator). PASS gate end-to-end; first cycle to ship a contract
MAJOR bump; second consecutive cycle with zero new process
leftovers; first cycle to run the full 5-phase security audit
since cycle 5.

Top 3 improvement actions for cycle 8:
1. Formalise the implement-skill <-> downstream-skill artifact
   contract — cycle 7 shipped without an implementation report
   and the doc / test-spec / retrospective skills successfully
   fell back to task-spec + commit-body reading, but the
   fallback is implicit and should be codified.
2. Sanitize JsonException.Message + BadHttpRequestException.Message
   before surfacing them in ValidationProblemDetails.detail —
   F-AZ795-1 / F-AZ795-2 in the cycle-7 security audit.
3. AZ-795 child-task sweep across the remaining public endpoints
   (request / route / upload / latlon) using AZ-796 as the
   reference pattern; 2-3 SP per endpoint, spread across cycles
   8-10.

LESSONS.md ring buffer updated with 3 cycle-7 entries (process /
testing / architecture); 3 oldest cycle-2 entries dropped to
maintain the 15-entry buffer.

State pointer advanced to cycle 8 step 9 (New Task) — Re-Entry
After Completion per autodev existing-code flow.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 11:24:52 +03:00
Oleksandr Bezdieniezhnykh 30d99e09ad [AZ-794] [AZ-795] [AZ-796] Cycle 7 Step 16 deploy report
Cycle 7 is a pure-quality cycle: no migrations, no new endpoints,
no new env vars, unchanged container image base. The full shipping
payload is a contract MAJOR bump (tile-inventory.md 1.0.0 -> 2.0.0,
breaking) plus a new strict-validation surface across the inventory
endpoint.

Deploy report covers:
- 3 cycle-7 commits (task adoption, implementation, sync) + this
  one + the pending close commit.
- Zero migrations; tiles schema unchanged from cycle 6.
- Postgres host-port move 5432 -> 5433 (dev-only sibling-conflict
  avoidance; staging/prod unaffected).
- Two NuGet additions (FluentValidation 12.0.0 +
  .DependencyInjectionExtensions 12.0.0), both CVE-clean.
- 5 verification gates: tests PASS, test-spec sync PASS, docs
  PASS, security PASS_WITH_WARNINGS (3 Low), perf PASS (9/9 incl.
  PT-09 v2 smoke).
- 4 NEW cycle-7 recommended follow-ups (D-AZ795-1 FV bump;
  F-AZ795-1/2 message sanitisation; implementation-report
  exit-gate contract; AZ-795 child-task sweep for remaining
  public endpoints).
- Zero new process leftovers; cycle 5/6 carry-overs unchanged.

Step 16.5 (Release) skipped per the cycle-2-to-6 convention; the
operator runbook in this deploy report serves as the release
record. User-confirmed via Choose A/B/C at the Step 16.5 gate.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 11:24:39 +03:00
Oleksandr Bezdieniezhnykh bc04ba7f99 [AZ-794] [AZ-795] [AZ-796] Cycle 7 Steps 12-15 sync (test-spec / docs / security / perf)
Step 12 (Test-Spec Sync): adds BT-27 for the AZ-796 9-rule
validation surface and 12 cycle-7 AC rows + Coverage Summary
update to traceability-matrix.md.

Step 13 (Update Docs): module-layout + module docs for the new
SatelliteProvider.Api/Validators namespace + GlobalExceptionHandler
+ updated TileInventory DTO; tests_unit + tests_integration
document the new InventoryRequestValidatorTests (16 unit tests
covering all 9 rules) + TileInventoryValidationTests (16
integration tests) + ProblemDetailsAssertions support;
glossary entries for Validation Problem Details / FluentValidation
/ Unmapped Member Handling; system-flows F8 (Tile Inventory Bulk
Lookup) expanded with deserializer + validator gates and a 13-row
Validation Surface table; data_parameters § Tile Inventory
documents the v2 input schema + constraints; ripple_log_cycle7
captures the doc-side ripple decisions.

Step 14 (Security Audit): 5-phase audit ran; verdict
PASS_WITH_WARNINGS (3 Low findings — D-AZ795-1 FluentValidation
12.0.0 -> 12.1.1 recommended bump, F-AZ795-1 JsonException.Message
leak in 400 detail, F-AZ795-2 BadHttpRequestException.Message leak).
No Critical / High; auth runs before validation (confirmed in
Program.cs); two NuGet additions (FluentValidation 12.0.0 +
.DependencyInjectionExtensions 12.0.0) both CVE-clean. Per-phase
reports plus consolidated security_report_cycle7.md.

Step 15 (Performance Test): docker compose stack used for perf
run, scripts/run-performance-tests.sh exited 0 with 8/8 scenarios
PASS (second consecutive clean exit-0); added PT-09 cycle-7 smoke
probe (v2 z/x/y schema, 2500-tile all-miss batch) measuring
min=27ms median=44ms p95=73ms max=86ms (13.7x under AZ-505 AC-4
1000ms budget). PT-07/08 improvements traced to the cycle-6 TLS
handshake-overhead identification, not application-side change.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 11:24:27 +03:00
Oleksandr Bezdieniezhnykh 865dfdb3b9 [AZ-794] [AZ-795] [AZ-796] Strict input validation + z/x/y rename
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
AZ-794: rename inventory wire fields tileZoom/tileX/tileY -> z/x/y
to match the slippy-map URL convention. Contract bumped to v2.0.0.

AZ-795: shared validation infrastructure -- FluentValidation +
ValidationEndpointFilter + GlobalValidatorConfig (camelCase paths).
GlobalExceptionHandler now converts JsonException (UnmappedMember +
JsonRequired) into RFC 7807 ValidationProblemDetails. JSON layer
hardened with UnmappedMemberHandling.Disallow + camelCase naming
policy. New error-shape.md contract.

AZ-796: InventoryRequestValidator covers 9 rules (XOR tiles vs
locationHashes, cap 1000, z 0..22, x/y in slippy bounds, hash
length/charset). 16 unit tests + 16 integration tests + a manual
curl probe script.

Adjacent fixes uncovered by the new strict layer:
- IdempotentPostTests RoutePoint payload corrected to lat/lon
  (the DTO has used JsonPropertyName for ages; previously silently
  ignored under PascalCase fallback).
- TileInventoryTests slippy x/y reduced to fit z=18 bounds.
- docker-compose.yml host port for Postgres moved 5432 -> 5433 to
  avoid sibling-project conflict; appsettings.Development + README
  + AGENTS + architecture + containerization docs aligned.

New coderule (suite + repo): API consumer-facing OpenAPI
descriptions must not contain task IDs, contract filenames, or
version-bump history -- internal change tracking belongs in
commits/contract docs/changelogs. Existing offending descriptions
in Program.cs cleaned up.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 10:02:02 +03:00
Oleksandr Bezdieniezhnykh dceaddc436 [AZ-794] [AZ-795] [AZ-796] Adopt cycle 7 tasks (API quality follow-up)
Adopt three Jira tickets originally filed by gps-denied-onboard
AZ-777 Phase 1 Jetson probing into satellite-provider cycle 7.

- AZ-794: rename inventory body fields tileZoom/tileX/tileY → z/x/y
  (OSM convention; aligns body shape with URL slippy-map convention).
- AZ-795: epic + shared infra ship for strict input validation across
  all public endpoints (FluentValidation + global ProblemDetails
  filter + JsonSerializerOptions.UnmappedMemberHandling.Disallow).
- AZ-796: first concrete per-endpoint child of AZ-795 — strict
  validation for POST /api/satellite/tiles/inventory; reference
  implementation pattern for sibling per-endpoint tasks.

Re-labels the cross-repo follow-up section in _dependencies_table.md
as Step 9 cycle 7, sets cycle 7 ordering (shared infra → rename →
inventory validator), and bumps the autodev state cursor to Step 10
(Implement) for cycle 7.

Source: gps-denied-onboard AZ-777 Phase 1 Jetson probe (2026-05-22).
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-22 08:53:51 +03:00
Oleksandr Bezdieniezhnykh 7d3ba1c3fd Enhance .cursor documentation and workflows
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Updated the README.md to reflect new skill commands and improved descriptions for various workflows, including the addition of new skills like /test-spec, /code-review, and /release. Enhanced clarity on session boundaries and flow resolutions in the auto-chaining process.

Removed the implementer agent file as it is no longer needed. Updated coderule and meta-rule documents to enforce stricter testing and implementation standards, ensuring real results are produced rather than simulated ones.

Revised the autodev flow documentation to include a new release step and clarified the retrospective process. Adjusted the testing rules to specify coverage thresholds for critical paths.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-21 13:52:34 +03:00
Oleksandr Bezdieniezhnykh 19c0371fd6 [no-ticket] Sync .cursor with suite root
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Bring this repo's .cursor/ in line with the suite monorepo root .cursor/
so rules, skills, and autodev artifacts stay consistent across
submodules and sibling repos.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-17 13:11:02 +03:00
Oleksandr Bezdieniezhnykh af661359c7 [AZ-505] Cycle 6 Step 17: retrospective + close cycle
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Single-task cycle delivering AZ-505 (3 SP); 1 batch, PASS verdict
after a single auto-fix round (ComputeLocationHash duplication
consolidated into Uuidv5.LocationHashForTile). Step 14 Security
Audit skipped; Step 15 Performance Test PASS (8/8, exit 0) and
closes the cycle-3 perf-harness leftover that carried across
cycles 3-5.

Top 3 lessons appended to LESSONS.md ring buffer:
- Kestrel Http1AndHttp2 requires TLS for ALPN; spec-time decision
- Dapper-bypassing test paths own the Npgsql type contract
- Test fixtures naming specific schema artifacts need migration awareness

Cycle 7 opens at Step 9 (New Task).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 23:07:19 +03:00
Oleksandr Bezdieniezhnykh ba3bdb1918 [AZ-505] Cycle 6 Steps 15-16 perf + deploy report
Step 15 (Performance Test): 8/8 PT scenarios PASS in a single
default-parameter run (exit 0). Adapts scripts/run-performance-tests.sh
for the new TLS+ALPN dev listener via CURL_OPTS=(--cacert ./certs/api.crt).
Report at _docs/06_metrics/perf_2026-05-12_cycle6.md. The clean exit-0
satisfies the cycle-3 perf-harness leftover deletion criterion that
carried across cycles 3-5; leftover file deleted.

Step 16 (Deploy): _docs/03_implementation/deploy_cycle6.md captures the
shipping payload (inventory endpoint, HTTP/2 TLS+ALPN, tiles_leaflet_path
covering index, migration 015), the dev-cert plumbing for local-docker +
integration-tests parity, the production-TLS topology note (terminate at
ingress; never promote the dev cert), and the operator runbook for
promoting cycle-6 past dev.

NU1902 / CA2227 / ASPDEPR002 / Serilog-10.x re-listed as carry-overs
unchanged; admin-team iss/aud confirmation unchanged.

State advanced to Step 17 (Retrospective).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 23:02:00 +03:00
Oleksandr Bezdieniezhnykh 5d84d2839e [AZ-505] Test-spec sync + task-mode doc updates for cycle 6
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Step 12 (Test-Spec Sync, cycle-update mode):
- blackbox-tests.md: append BT-23..BT-26 for AZ-505's new
  observable behaviors (inventory order/shape; leaflet
  most-recent via location_hash; HTTP/2 multiplex over TLS+ALPN;
  request validation).
- performance-tests.md: append PT-09 (inventory p95 ≤ 1000ms /
  2500 tiles); records cycle-6 measured p95=66ms; documents
  promotion path to scripts/run-performance-tests.sh if budget
  ever tightens.
- traceability-matrix.md: resolve the 5 AZ-503 deferrals
  (AC-5/6/9/10/12) by pointing at AZ-505 test names + add 7
  AZ-505 AC rows (AC-1..AC-7) + bump totals (90 -> 94 tests,
  56/56 -> 63/63 in-scope) + add cycle-6 coverage shape notes
  (budget relaxation rationale, voting-filter deferral note,
  TLS+ALPN pivot, NFR propagation).

Step 13 (Update Docs, task mode):
- common_dtos.md: add 5 new TileInventory DTOs.
- common_interfaces.md: add ITileService.GetInventoryAsync.
- services_tile_service.md: document TileService.GetInventoryAsync
  steps + the XOR-validation-in-handler note.
- dataaccess_migrator.md: bump migration count 14 -> 15;
  describe migration 015 (AZ-505 leaflet covering index, lock
  window, INCLUDE-list trade-off).
- system-flows.md: add F7 (Leaflet Tile Serving, AZ-310 +
  AZ-505 location_hash rewire + TLS+ALPN) and F8 (Tile
  Inventory Bulk Lookup) with sequence diagrams, validation
  surface, and AC-4 perf evidence. Update Flow Inventory +
  Dependencies tables accordingly.
- glossary.md: add "Tile Inventory" entry pointing at the
  v1.0.0 contract.
- ripple_log_cycle6.md: new file — exhaustive reverse-dependency
  analysis confirms zero stale downstream module docs.

Advance autodev state from step 11 -> 14 (skipping 12+13 as
completed in this commit; auto-chain through Step 14 = Security
Audit optional gate).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 22:29:22 +03:00
Oleksandr Bezdieniezhnykh c74a2339aa [AZ-505] AC-5 fix: enable TLS for HTTP/2 via ALPN
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Kestrel with HttpProtocols.Http1AndHttp2 on a plaintext listener
silently downgrades to HTTP/1.1-only (logs "HTTP/2 is not enabled
... TLS is not enabled"), so AC-5's multiplexed-GET test failed
with HTTP_1_1_REQUIRED. ALPN cannot run over plaintext, so the
fix switches the dev listener to TLS on https://+:8080:

- scripts/run-tests.sh generates a self-signed dev cert idempotently
  (./certs/api.pfx + api.crt) via openssl in an alpine container;
  certs/ is gitignored.
- docker-compose.yml binds Kestrel to ASPNETCORE_URLS=https://+:8080
  with Kestrel__Certificates__Default__Path bound to the .pfx.
- docker-compose.tests.yml mounts api.crt into the integration-tests
  container's CA store and runs update-ca-certificates so HttpClient
  trusts the cert transparently; default API_URL is now https://api:8080.
- Drop the obsolete Http2UnencryptedSupport AppContext switch from
  Http2MultiplexingTests; ALPN over TLS handles negotiation.

Test-data fixes caught on the post-TLS rerun (independent of the TLS
switch but surfaced together):

- Http2MultiplexingTests: switch slippy coords from (154321, 95812)
  -- which Google Maps returns 404 for -- to (158485, 91707), the
  slippy projection of (47.461747, 37.647063) already exercised by
  JwtIntegrationTests.
- TileInventoryTests + LeafletPathIndexOnlyTests: SpecifyKind to
  Unspecified at the binding site for raw Npgsql seed paths writing
  into tiles.captured_at / created_at / updated_at (TIMESTAMP without
  tz). Npgsql v6+ refuses Kind=Utc into plain timestamp columns;
  production goes through Dapper and never hits this code path.
- MigrationTests Az503NewUniqueIndexCoversIntegerKeyAndFlightId:
  accept either idx_tiles_location_hash (migration 014) or its
  AZ-505 successor tiles_leaflet_path (migration 015) -- both have
  location_hash as the leading column, which is the AC-9 intent.

Docs updated to reflect the TLS+ALPN path: tile-inventory.md
Non-Goals, modules/api_program.md, module-layout.md, the AZ-505
task spec's Risk 3, and the cycle 6 implementation + completeness
reports. The full integration test suite passes (mode=full, exit 0).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 22:19:26 +03:00
Oleksandr Bezdieniezhnykh da40534b49 chore: advance autodev state to Step 11 (Run Tests) after AZ-505 batch 1
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 21:17:23 +03:00
Oleksandr Bezdieniezhnykh 909f69cb3a [AZ-505] Tile inventory endpoint + HTTP/2 + Leaflet covering index
Production code:
- POST /api/satellite/tiles/inventory (XOR body, 5000-cap,
  most-recent-per-location_hash select, present/absent shaping).
- Kestrel HttpProtocols.Http1AndHttp2 on every listener (AC-5).
- Migration 015 creates tiles_leaflet_path covering index over
  (location_hash, captured_at DESC, updated_at DESC, id DESC)
  INCLUDE (file_path, source); drops superseded idx_tiles_location_hash.
- TileRepository.GetByTileCoordinatesAsync rewired to filter by
  location_hash (Index Only Scan via tiles_leaflet_path).
- TileRepository.GetTilesByLocationHashesAsync added with Npgsql-
  direct ANY($1::uuid[]) binding (Dapper IEnumerable expansion is
  incompatible with the array form).
- Uuidv5.LocationHashForTile centralises the UUIDv5(TileNamespace,
  "{z}/{x}/{y}") formula — single source of truth for the cross-repo
  invariant (gps-denied-onboard parity).

Contracts:
- New: contracts/api/tile-inventory.md v1.0.0.
- Bumped: contracts/data-access/tile-storage.md to v2.0.0 (joint
  ownership by AZ-503-foundation + AZ-505: schema + covering index +
  GetByTileCoordinatesAsync rewrite).

Tests:
- TileInventoryTests covers AC-1, AC-2 (DB-level), AC-4, AC-6.
- Http2MultiplexingTests covers AC-5 (20 concurrent multiplexed GETs
  over h2c via SocketsHttpHandler + AppContext Http2Unencrypted switch).
- LeafletPathIndexOnlyTests covers AC-3 (EXPLAIN (ANALYZE, BUFFERS)
  asserts Index Only Scan over tiles_leaflet_path with heap_blocks=0).

Docs:
- architecture.md, system-flows.md, data_model.md, module-layout.md,
  glossary.md, modules/api_program.md, modules/dataaccess_tile_repository.md,
  components/02_data_access/description.md all updated to reference the
  v2.0.0 tile-storage contract + new tile-inventory contract + AC-7.

Reports:
- batch_01_cycle6_report.md, batch_01_cycle6_review.md,
  implementation_completeness_cycle6_report.md (PASS),
  implementation_report_tile_inventory_cycle6.md.

Task spec moved todo/ -> done/.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 21:16:37 +03:00
Oleksandr Bezdieniezhnykh 3c7cd4e56b chore: update autodev state to Step 10 (Implement) and refine task details for AZ-505
- Advanced the autodev state to Step 10, reflecting the implementation phase.
- Updated task name for AZ-505 to "Implement" and adjusted its status to "not_started."
- Enhanced the dependencies table with detailed context for AZ-505, clarifying its relationship with AZ-503 and its role in cycle 6.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 20:17:57 +03:00
Oleksandr Bezdieniezhnykh aa1a1bf19f chore: open cycle 6 — state advanced to Step 9 (New Task)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 18:08:17 +03:00
Oleksandr Bezdieniezhnykh ea278afb37 [AZ-503] [AZ-504] Cycle 5 Step 17: retrospective + close cycle
retro_2026-05-12_cycle5.md captures the cycle-end retrospective:
- Implementation: 2 tasks (AZ-504 + AZ-503-foundation), 4 SP total,
  100% first-attempt pass rate, 1 mid-implement scope-split
  (AZ-503 → AZ-503-foundation + AZ-505, blocked-linked).
- Quality: 50/50 PASS/PASS_WITH_WARNINGS, 0 new Medium+, 1 new Low
  (defensive contentSha256 soft-NULL guard).
- Security: PASS_WITH_WARNINGS, 0 new Critical/High/Medium, 2 new
  Low informational (F1 flightId provenance, F2 pgcrypto runbook
  gap).
- Performance: PASS_WITH_INFRA_WARNINGS — first measurable PT-08
  ever (Run #1 199ms, Run #2 117ms vs 2000ms threshold); PT-01/02
  failed on recurring local Docker/colima DNS cold-start, not an
  app regression.
- Structural: +1 ProjectReference edge (IntegrationTests → Common),
  +1 minor contract bump (uav-tile-upload 1.0.0 → 1.1.0), +1 DB
  migration (014_AddTileIdentityColumns.sql), 0 NuGet bumps,
  0 csproj additions, DAG still acyclic at 9 projects.

structure_2026-05-12_cycle5.md captures the structural snapshot.

LESSONS.md updated with 3 cycle-5 entries (oldest dropped to
preserve the 15-entry ring buffer):
- [architecture] Cross-repo cryptographic invariants must live as
  code constants in both repos with reference-vector tests.
- [tooling] When perf-mode "one re-run" fires twice with the same
  DNS root cause, escalate from re-run to harness fix.
- [process] Spec contradicts live code by >=2 prerequisites →
  prefer split into foundation + follow-up (A/B/C option C).

Top 3 follow-up actions (cycle 6 candidates):
- Action 1 (1 SP): DNS pre-warm in scripts/run-performance-tests.sh
  → closes the cycle-3 perf-harness leftover.
- Action 2 (5 SP): AZ-505 — inventory endpoint + HTTP/2 + Leaflet
  covering index (blocked-linked on AZ-503-foundation, this cycle).
- Action 3 (1 SP): pgcrypto pre-install runbook step (F2-cy5 doc
  fix).

Cycle 5 closed. Autodev state advanced for cycle 6 by the next
/autodev invocation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 18:07:57 +03:00
Oleksandr Bezdieniezhnykh 0e05fc519a [AZ-503] [AZ-504] Cycle 5 Step 16 deploy report
deploy_cycle5.md captures everything operators need to promote
cycle 5 beyond dev:

- Code shipped: AZ-503-foundation (deterministic UUIDv5 tile
  identity, integer-only flight-aware UPSERT, per-flight on-disk
  paths) + AZ-504 (perf script grep-pipefail fix).
- NEW database migration 014_AddTileIdentityColumns.sql adds
  flight_id, location_hash, content_sha256, legacy_id; enables
  pgcrypto; swaps the AZ-484 float index for the new
  idx_tiles_unique_identity integer index. Idempotent under
  DbUp's journal.
- NEW contract version uav-tile-upload.md 1.0.0 → 1.1.0 (adds
  optional flightId; derived tileId in response).
- NEW per-flight on-disk path layout for UAV tiles (additive;
  legacy paths preserved).
- No env-var changes. Container image base unchanged from cycle 4.
- Verification gates passed: PASS (Step 11), PASS (Steps 12+13),
  PASS_WITH_WARNINGS (Step 14), PASS_WITH_INFRA_WARNINGS (Step 15).
- Cycle-3 perf-harness leftover stays OPEN with two clean follow-up
  paths recorded (DNS pre-warm in script, OR move perf gate to CI).
- Operator runbook includes pgcrypto pre-install check for managed
  Postgres providers.

Autodev state advanced to Step 17 (Retrospective).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 18:01:49 +03:00
Oleksandr Bezdieniezhnykh 61612044fb [AZ-503] [AZ-504] Cycle 5 Steps 11-15 sync
Wrap up cycle 5 verification + documentation:
- Steps 10/11 wrap-up reports (implementation_completeness +
  implementation_report) for the AZ-503-foundation + AZ-504 batch.
- Step 12 test-spec sync: AZ-503-foundation/AZ-504 ACs appended;
  AZ-505 deferred ACs recorded.
- Step 13 update-docs: architecture, data-model, glossary, module-
  layout, uav-tile-upload contract (v1.1.0), DataAccess + Services
  + Tests module docs synced; new common_uuidv5.md module doc.
- Step 14 security audit: PASS_WITH_WARNINGS; 0 new Critical/High;
  2 new Low informational (F1 flightId provenance, F2 pgcrypto
  deploy gap).
- Step 15 performance test: PASS_WITH_INFRA_WARNINGS; PT-08
  passed twice (AZ-504 fix verified); PT-01/02 failed due to
  recurring local Docker/colima DNS cold-start (not an app
  regression). Cycle-3 perf-harness leftover stays OPEN with
  replay #5 documented.
- Autodev state moved to Step 16 (Deploy).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 18:01:27 +03:00
Oleksandr Bezdieniezhnykh c646aa93e2 [AZ-503] Tile identity → UUIDv5 + integer UPSERT (foundation)
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Foundation half of original AZ-503 (split during /autodev step 10 batch 2
on user choice; deferred work moved to AZ-505 with a Blocks link).

Adds deterministic tile identity (UUIDv5 over (z, x, y, source, flight_id))
shared cross-repo with gps-denied-onboard via the pinned TileNamespace
5b8d0c2e-7f1a-4d3b-9c5e-1f3a8e7d2b6c, switches the tiles UPSERT key from
floats to integers with per-flight separation, plumbs FlightId through
UavTileMetadata + handler, and writes UAV evidence to per-flight
on-disk directories so two flights at the same (z, x, y) coexist.

- Common: pure-C# RFC 9562 Uuidv5 (no third-party dep) + FlightId DTO
  field; 10 Python-reference unit vectors verify byte parity.
- DataAccess: migration 014 adds flight_id (uuid NULL), location_hash
  (uuid NOT NULL, backfilled via session-scoped pg_temp.uuidv5),
  content_sha256 (bytea NULL), legacy_id (uuid NULL = preserves
  pre-AZ-503 random id one cycle); drops idx_tiles_unique_location_source
  (AZ-484) and adds idx_tiles_unique_identity keyed on
  (tile_zoom, tile_x, tile_y, tile_size_meters, source,
   COALESCE(flight_id, '00000000-...'::uuid)) + idx_tiles_location_hash.
- TileRepository: ColumnList + UPSERT updated; id never updated on
  conflict (preserves AC-2 idempotence). UpdateAsync extended.
- Services: TileService and UavTileUploadHandler compute deterministic
  Id + LocationHash + ContentSha256 before insert; UAV file path
  becomes ./tiles/uav/{flight_id or 'none'}/{z}/{x}/{y}.jpg.
- Tests: Uuidv5Tests (10 reference vectors), UavTileFilePathTests
  (per-flight + anonymous paths), UavTileUploadHandlerTests (AC-2,
  AC-3, AC-7, AC-11 unit-level), UavUploadTests (AC-3 + AC-4
  integration: multi-flight DB coexistence with shared location_hash
  + distinct file_path; float-different lat/lon collapse to 1 row),
  MigrationTests (column shape, idx_tiles_unique_identity supersedes
  AZ-484 index, deterministic backfill).
- IntegrationTests project references Common to reuse Uuidv5 in raw
  SQL seeds.
- AZ-488 MultiSourceCoexistence seed fixed to populate location_hash
  (otherwise migration 014's NOT NULL constraint fails).

ACs covered: AC-1, AC-2, AC-3, AC-4, AC-7, AC-8, AC-11.
ACs deferred to AZ-505: AC-5, AC-6, AC-9, AC-10, AC-12.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 17:07:35 +03:00
Oleksandr Bezdieniezhnykh f6197499a4 chore: update autodev state after AZ-504 batch 1
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 16:33:08 +03:00
Oleksandr Bezdieniezhnykh ab437a15df [AZ-504] Fix grep | wc -l pipefail crash in PT-08 batch counting
scripts/run-performance-tests.sh:416-417 used `grep -o ... | wc -l`
to count `"status":"accepted"` and `"status":"rejected"` markers in
the PT-08 batch response. On the happy path (rejected=0) grep -o
exits 1, and under `set -o pipefail` + `set -e` (line 16) the
pipeline killed the script before reaching any of PT-08's reporting
code — reproducing twice in the cycle-3 perf-harness leftover
(replay #2 + #3 post-AZ-500).

Fix: neutralise grep's no-match exit locally with `|| true` on the
grep stage of each pipeline. `grep -o | wc -l` is kept (not swapped
for `grep -c`) because the PT-08 response is compact JSON — all
items live on one line, so `grep -c` would always return 1 and lose
occurrence-count semantics. An 8-line comment explains why grep
cannot fail for I/O at this code path (file is curl-written, HTTP
200 gated).

AC-1 + AC-2 verified in-place against a standalone harness under
`set -e -o pipefail` (compact-JSON, mixed-status, edge-empty
cases). AC-3 + AC-4 are Step 15 (Performance Test) obligations by
spec design — the leftover deletion (AC-4) is "in the same commit"
as the green full perf run.

Batch report: _docs/03_implementation/batch_01_cycle5_report.md.
Code review: _docs/03_implementation/reviews/batch_01_cycle5_review.md
— PASS, no findings.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 16:32:36 +03:00
Oleksandr Bezdieniezhnykh 8e509b550c [AZ-503] [AZ-504] cycle 5 new-task: tile identity + perf-script-fix
- AZ-503 (3 SP, epic AZ-483) — Tile identity → UUIDv5 deterministic id;
  integer-only UPSERT with COALESCE(flight_id) per-flight separation;
  content_sha256 column; POST /api/satellite/tiles/inventory bulk-list
  endpoint; HTTP/2 at Kestrel edge. Cross-workspace handoff from
  gps-denied-onboard (AZ-304 / AZ-316 counterpart). Supersedes the
  AZ-484 UPSERT-conflict-key portion.

- AZ-504 (1 SP, epic AZ-483) — Fix scripts/run-performance-tests.sh
  lines 416-417: grep -o | wc -l + set -o pipefail kills PT-08 when
  rejected=0. Closes the replay obligation for the cycle-3 perf-harness
  leftover (leftover deletion gated on green full perf run, AC-4).

Updates _dependencies_table.md with cycle 5 entries and records
replay attempt #4 against the perf-cycle3 leftover (PBI opened —
leftover still stays until AZ-504 lands and full perf run is green).

State advanced to Step 10 (Implement).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 16:27:40 +03:00
Oleksandr Bezdieniezhnykh e31f59211d [AZ-500] Cycle 4 Step 17: retrospective + close cycle
Adds retro_2026-05-12_cycle4.md, structure_2026-05-12_cycle4.md, and
the deploy_cycle4.md report that was dropped from the Steps 12-15
sync commit. Appends 3 new lessons to LESSONS.md (12/15 ring buffer)
on transitive major-version bumps, exposed pre-existing bugs, and
single-task-cycle metric framing. State advances to cycle 5 / step 9
(awaiting next New Task invocation).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 06:14:43 +03:00
Oleksandr Bezdieniezhnykh af4219fce6 [AZ-500] Cycle 4 Steps 12-15 sync (test-spec / docs / security / perf)
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Step 12 (Test-Spec Sync) - cycle-update mode
  - traceability-matrix: 8 AZ-500 AC rows + .NET 10 runtime
    restriction supersession + Cycle-4 coverage shape note
    (no new tests; ACs verified by re-running existing 78-test
    suite + build pipeline + manifest grep)

Step 13 (Update Docs) - task mode
  - FINAL_report, 00_discovery, architecture, module-layout,
    api_program, tests_unit: .NET 8 -> .NET 10 / C# 12 -> 14 /
    Swashbuckle 6.6.2 -> 10.1.7 + Microsoft.OpenApi 2.x
    refactor note in api_program; Serilog.AspNetCore 8.0.3
    fallback documented inline per AZ-500 Risk #4
  - deployment/{containerization, ci_cd_pipeline}: Docker
    aspnet/sdk:8.0 -> :10.0
  - ripple_log_cycle4: empty import-graph ripple recorded
    (Program.cs is entry point; ParameterDescriptionFilter only
    consumed by Program.cs; csproj/global.json/Dockerfile have
    no import edges)

Step 14 (Security Audit) - resume mode
  - dependency_scan_cycle4: AZ-500 19-package delta scanned;
    cycle-3 D1+D3 (CVE-2026-26130) closed by major-version
    bump; cycle-3 D2 (Test.Sdk 17.8.0 NuGet.Frameworks flag)
    carried over - explicitly out of AZ-500 scope
  - security_report_cycle4: PASS_WITH_WARNINGS (only carry-over
    Medium open; AZ-500 introduced 0 new Critical/High); cycle-3
    static_analysis/owasp_review/infrastructure_review carried
    forward unchanged (AZ-500 made no source-level edits to
    those surfaces)

Step 15 (Performance Test) - perf mode, full default-param run
  - perf_2026-05-12_cycle4: 7 Pass + 1 Unverified (PT-08 hit
    pre-existing scripts/run-performance-tests.sh:417 grep-
    pipefail bug, NOT a .NET 10 regression)
  - PT-07 warm p95 = 301ms (7.7x improvement vs cycle-3 short
    variant - .NET 10 pipeline + N=20 dilution); cold p95 =
    2782ms (-14%); PT-06 90ms (-49%)
  - AZ-500 NFR (Performance) MET for 7/8 scenarios
  - Cycle-3 perf-harness leftover updated with replay #3
    results; STAYS OPEN per AZ-500 Constraint (deletes only on
    fully clean run)

Recommended follow-up PBIs (out of cycle-4 scope, surfaced for
the backlog):
  - 1 SP fix scripts/run-performance-tests.sh:416-417 grep-
    pipefail (replace grep -o ... | wc -l with grep -c ... ||
    true) - unblocks PT-08 + closes the cycle-3 perf leftover
  - 3 SP migrate WithOpenApi(...) callsites to ASP.NET Core 10
    minimal-API metadata extensions (clears 8 ASPDEPR002
    warnings; recorded in batch_01_cycle4_review.md)
  - 1 SP Microsoft.OpenApi 2.x nullable cleanup (CS8604 in
    ParameterDescriptionFilter.cs:25)
  - 1 SP bump Microsoft.NET.Test.Sdk 17.8.0 -> 17.13.0+
    (closes cycle-3 D2 NuGet.Frameworks transitive flag)

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 06:05:29 +03:00
Oleksandr Bezdieniezhnykh de609cffa1 [AZ-500] Cycle 4 implement-skill wrap-up reports
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Adds the cycle-4 product implementation completeness gate report
(verdict: PASS) and the final implementation report for the .NET 10
migration. Records the Step 16 handoff to Step 11 (test-run skill)
to avoid duplicating the full-suite run already executed during
AC-6 verification (271/271 unit + full integration suite green).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 05:32:27 +03:00
Oleksandr Bezdieniezhnykh 813136326f [AZ-500] .NET 8 -> .NET 10 migration
Coordinated cross-cutting bump: 9 csproj TFMs net8.0 -> net10.0;
global.json sdk.version 8.0.0 -> 10.0.0; all Dockerfiles + scripts/
+ .woodpecker on mcr.microsoft.com/dotnet/{sdk,aspnet,runtime}:10.0;
all Microsoft.AspNetCore.* (8.0.25) and Microsoft.Extensions.* (9.0.10)
packages -> 10.0.7. Serilog.AspNetCore retained at 8.0.3 (10.0.0
requires Serilog.Sinks.File >= 7.0.0; out of AZ-500 scope per "no
unrelated package bumps") -- documented in AGENTS.md. Swashbuckle
9.x bumped to 10.1.7 to track Microsoft.OpenApi 2.x; Program.cs +
ParameterDescriptionFilter.cs refactored for the 2.x namespace
(Microsoft.OpenApi), OpenApiSecuritySchemeReference, JsonSchemaType
enum, and IOpenApiSchema dictionary properties. Fixed implicit AC-5
prereq: scripts/run-performance-tests.sh PERF_DLL path bin/Release/
net8.0 -> net10.0. Docs sync: architecture.md + AGENTS.md.

ACs verified: AC-1..AC-4 + AC-7 + AC-8 by grep + build; AC-6 by
./scripts/run-tests.sh --full (271/271 unit tests + full integration
suite green); AC-5 short bootstrap-smoke (PERF_REPEAT_COUNT=2
PERF_UAV_BATCH_SIZE=2) succeeded at the bootstrap step (no exit 3),
PT-01..PT-07 PASS. PT-08 surfaced a pre-existing grep-pipefail bug
in run-performance-tests.sh:417 -- not an SDK problem; recorded as
follow-up in the perf-cycle3 leftover. Code review verdict:
PASS_WITH_WARNINGS (2 Medium deferred per scope discipline:
WithOpenApi ASPDEPR002 deprecation x8, CS8604 nullable in
ParameterDescriptionFilter.cs; both targeted at follow-up PBIs).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 05:28:01 +03:00
Oleksandr Bezdieniezhnykh c0f004d2c9 [AZ-500] Cycle 4 Step 9: new-task .NET 10 migration
Closes Step 9 (New Task) of cycle 4. AZ-500 spec defines the
.NET 8 -> .NET 10 migration (TFM bump on 9 csprojs, global.json
SDK pin to 10.0.0, both Dockerfiles + run-tests.sh + woodpecker
to mcr.microsoft.com/dotnet/*:10.0, Microsoft.AspNetCore.* and
Microsoft.Extensions.* to the 10.x line, Serilog.AspNetCore to
10.x or documented 8.0.3 fallback, plus arch.md + AGENTS.md doc
sync). Closes the cycle-3 perf-harness leftover via AC-5
(bootstrap smoke after migration).

Also logs the cycle-4 perf-leftover replay attempt that
discovered the host-SDK / project-SDK mismatch and rolls the
state file from cycle 3 -> cycle 4 (Step 9 done -> Step 10
ready).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 04:35:52 +03:00
Oleksandr Bezdieniezhnykh ca0ca9f2a4 [AZ-491] [AZ-492] [AZ-493] [AZ-494] [AZ-495] [AZ-496] Cycle 3 Step 17: retrospective + close cycle
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Cycle-3 retrospective:
  - 6 tasks (AZ-491..AZ-496), 5 batches, 18 SP delivered.
  - 100% code review pass rate (5/5 PASS_WITH_WARNINGS, 0 FAIL).
  - 0 Critical/High/Medium review findings; 7 distinct Low.
  - Security audit PASS_WITH_WARNINGS: 0 new Medium, 3 Low (all
    test-only or operator-CLI), 2 Informational, 1 False Positive.
  - Net Architecture delta: **-3** (F-AUTH-2 + D1 + D3 RESOLVED;
    only new findings are Low test-side surfaces). First
    net-negative cycle on record.
  - 5 of 6 tasks completed first attempt (no post-review fix
    commits). Cycle-2's 2 prior-retro actions all translated to
    closed work (AZ-491 from Action 1, AZ-492 from Action 2,
    AZ-493 from Action 3).

Top 3 cycle-4 improvement actions surfaced:
  1. Execute the perf harness to capture PT-07/PT-08 baseline.
  2. Bump TestSupport JWT pins 7.0.3 → 7.1.2+ (D4 NU1902 cleanup).
  3. Add `workspace:` tag to cross-repo ACs in task-spec writing
     and render them separately in the traceability matrix.

3 new ring-buffer lessons appended to _docs/LESSONS.md:
  - [process] Option-B forcing functions for cross-team blockers.
  - [process] ACs prescribing a measurement should also prescribe
    the collection path.
  - [process] Cross-repo-write ACs need workspace tags.

Structural snapshot at structure_2026-05-12_cycle3.md records the
new SatelliteProvider.TestSupport project (+2 ProjectReference edges
into it; no production-layer dependents) and the AZ-496 package
bumps (8.0.21 → 8.0.25).

Cycle 3 COMPLETE. State advanced to Step 9 (New Task) for cycle 4
per existing-code flow Re-Entry After Completion.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 03:46:41 +03:00
Oleksandr Bezdieniezhnykh 65cdfae970 [AZ-491] [AZ-492] [AZ-493] [AZ-494] [AZ-495] [AZ-496] Cycle 3 Step 15 skip + Step 16 deploy report
Step 15 (Performance Test): SKIPPED. User skipped the optional gate
question. Per meta-rule.mdc, performance tests require explicit
approval; a skipped question is not approval. Recorded as leftover at
_docs/_process_leftovers/2026-05-12_perf-cycle3-harness-execution.md
for replay at next /autodev invocation.

Step 16 (Deploy): COMPLETED. Produced deploy_cycle3.md mirroring the
cycle-2 shape. Covers:
  - 9 cycle-3 commits + zero DB migration
  - Config changes (JWT_ISSUER/JWT_AUDIENCE env vars w/ fail-fast,
    8.0.25 package bumps, new TestSupport project)
  - Pre-deploy gate recap (Steps 11-15)
  - Cycle-3 operational risks R1-R4 (admin-team iss/aud confirm,
    cross-repo doc deferral, cycle-2 R1/R3 carry-overs, test-runner
    log line)
  - Rollback plan, post-deploy verification (incl. wrong-iss / wrong-
    aud smoke probes), CI/CD push policy
  - Resolved this cycle: F-AUTH-2, D1, D3, PT-07/PT-08 leftover
  - Follow-up backlog: D4 NU1902 bump, F-DBR-2 third guard, F-PERF-1
    token-history hardening, image-fixture consolidation, AC-7 cross-
    repo write, no-revocation-list residual

Next: Step 17 (Retrospective, cycle-end mode).
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 03:42:10 +03:00
Oleksandr Bezdieniezhnykh 314d1dec39 [AZ-491] [AZ-492] [AZ-493] [AZ-494] [AZ-496] Cycle 3 Step 14: security audit refresh
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
All 5 phases refreshed against cycle-3 delta:

Phase 1 (Dependency Scan):
  - D1 RESOLVED (AZ-496): Microsoft.AspNetCore.OpenApi 8.0.21 → 8.0.25
  - D3 RESOLVED (AZ-496): JwtBearer 8.0.21 → 8.0.25
  - D4 NEW (Low, test-only): System.IdentityModel.Tokens.Jwt 7.0.3 +
    Microsoft.IdentityModel.Tokens 7.0.3 pinned in TestSupport carry
    CVE-2024-21319 (JWE DoS). Bump to ≥ 7.1.2 tracked as future PBI.

Phase 2 (Static Analysis):
  - F-AUTH-3 (Info): test runner Program.cs logs iss/aud at startup;
    production API does NOT (verified by grep).
  - F-AUTH-4 (Info): DEV-ONLY iss/aud placeholders in
    appsettings.Development.json + .env.example — by design per
    Option B for AZ-494.
  - F-DBR-1: TRUNCATE string interpolation in
    IntegrationTestDatabaseReset.cs — false positive (hard-coded
    table list).
  - F-DBR-2 (Low): TRUNCATE guard is operator-bypassable. Two-guard
    model is conservative-by-default and unit-tested.
  - F-PERF-1 (Low): perf-bootstrap --mint-only writes a 4-hour
    GPS-permission token to stdout. Operator-trusted machine assumed.

Phase 3 (OWASP Top 10):
  - A03 carries D1/D3 RESOLVED + D4 NEW.
  - A07 flips F-AUTH-2 to RESOLVED (AZ-494); residual revocation-list
    Low recorded.
  - A05 status unchanged (F-DBR-1 false positive).
  - A08 picks up F-DBR-2.

Phase 4 (Infrastructure):
  - JWT_ISSUER / JWT_AUDIENCE flow .env → compose → Kestrel config,
    same pattern as JWT_SECRET.
  - INTEGRATION_TEST_DB_RESET + ASPNETCORE_ENVIRONMENT=Testing wired
    for AZ-493 reset gate.
  - SatelliteProvider.TestSupport is IsPackable=false — never ships
    in a production container image.
  - New operational gate added to deploy runbook: grep for DEV-ONLY-
    in the rendered deploy environment must return zero hits.

Phase 5 (Security Report):
  - Verdict: PASS_WITH_WARNINGS (cycle 3 does not escalate).
  - 0 Critical, 0 High, 0 new Medium.
  - Cycle-2 F-AUTH-2 (Medium) RESOLVED; cycle-1 D1 + cycle-2 D3
    RESOLVED.

Autodev state advanced to Step 14 completed. Next: Step 15
(Performance Test, optional gate).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 03:13:04 +03:00
Oleksandr Bezdieniezhnykh e42bf62152 [AZ-491] [AZ-492] [AZ-493] [AZ-494] [AZ-495] [AZ-496] Cycle 3 Steps 11-13: test-spec sync + ripple log
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Step 11 (Run Tests) is recorded as PASS based on the implement skill's
internal Step 16 gate (./scripts/run-tests.sh --full, all-green) per
test-run/SKILL.md § Functional Mode — same runner, immediately
preceding invocation, no value in a second run.

Step 12 (Test-Spec Sync, cycle-update mode):
  - traceability-matrix.md: rows added for AZ-491 AC-1..AC-6,
    AZ-493 AC-1..AC-6, AZ-495 (doc convention), AZ-496 AC-1..AC-N
    (dependency bump); AZ-494 AC-1/AC-2 rows now cross-reference
    new SEC-12 / SEC-13 blackbox IDs.
  - security-tests.md: SEC-12 (wrong iss returns 401) and SEC-13
    (wrong aud returns 401) appended for AZ-494.
  - environment.md: Environment Variables table extended with
    GOOGLE_MAPS_API_KEY, JWT_SECRET, JWT_ISSUER, JWT_AUDIENCE,
    INTEGRATION_TEST_DB_RESET. Closes a cycle-2 oversight where
    JWT_SECRET was never recorded.

Step 13 (Update Docs, task mode):
  - tests_unit.md: consolidated the duplicate
    AuthenticationServiceCollectionExtensionsTests entry that
    spanned AZ-487 + AZ-494 into one coherent block.
  - ripple_log_cycle3.md created: per-task source files +
    every doc that was touched (architecture, module-layout,
    api_program, tests_unit, tests_integration, traceability,
    performance-tests, security-tests, environment, security_report,
    owasp_review, deploy_cycle2, retro_2026-05-11_cycle2). Notes
    which docs were intentionally NOT touched and the open
    cross-repo doc ripple (AC-7).

Autodev state advanced to Step 13 completed. Next: Step 14 Security
Audit (optional gate).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 02:57:45 +03:00
Oleksandr Bezdieniezhnykh 495605f51b [AZ-494] [AZ-492] Cycle 3 Step 16: full test suite green; close batches
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Final cumulative review for batches 04-05 (PASS_WITH_WARNINGS, 4 Low
findings, all non-blocking). Combined with the prior 01-03 cumulative,
this closes the per-cycle batch coverage with two PASS_WITH_WARNINGS
verdicts.

scripts/run-tests.sh --full green: format check + 13 cycle-3 unit
tests (including the 4 new AZ-494 fail-fast cases for missing /
empty iss / aud) + the full integration suite (including the 2 new
WrongIssuer / WrongAudience 401 assertions).

Fixed a stale "leave blank to fall back" comment in .env.example
that contradicted the "REQUIRED" line right above it; the integration
runner reads env vars directly with no appsettings fallback so blank
values now fail-fast.

Advanced _docs/_autodev_state.md to mark Step 10 (Implement) status:
completed.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 02:35:10 +03:00
Oleksandr Bezdieniezhnykh f979e18811 [AZ-494] Enable JWT iss/aud validation with fail-fast startup
Option B per user decision: production ships with empty Jwt.Issuer /
Jwt.Audience in appsettings.json so the API process refuses to start
unless JWT_ISSUER + JWT_AUDIENCE env vars are supplied. Development
ships with grep-friendly DEV-ONLY- placeholders so local + docker
flows keep working unchanged.

AuthenticationServiceCollectionExtensions flips ValidateIssuer +
ValidateAudience to true and wires ValidIssuer / ValidAudience via a
new ResolveRequiredOrThrow helper that all three required values
(secret, iss, aud) now share. JwtTokenFactory.Create + CreateExpired
gain optional iss / aud parameters (default null) so existing call
sites compile unchanged. JwtTestHelpers adds MintAuthenticated /
MintExpired wrappers that resolve iss + aud from env, plus
ResolveIssuerOrThrow / ResolveAudienceOrThrow. PerfBootstrap.MintToken
+ Program.cs JWT bootstrap migrated to the new surface so the perf
harness and the integration runner both validate against the same
contract.

Adds 4 fail-fast unit tests (missing/empty issuer + audience), 2
negative integration scenarios (WrongIssuer_Returns401,
WrongAudience_Returns401), and re-tags every existing integration
mint site via MintAuthenticated.

Compose, .env.example, run-tests.sh, run-performance-tests.sh all
load + export JWT_ISSUER + JWT_AUDIENCE alongside JWT_SECRET.

Resolves F-AUTH-2 (security_report.md + owasp_review.md). AC-7
(cross-repo suite/_docs/10_auth.md write) deferred — outside this
workspace; tracked in deploy_cycle2.md R3 follow-up.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 02:28:48 +03:00
Oleksandr Bezdieniezhnykh 080441db5d [AZ-492] Cycle 3 batch 4: perf harness PT-07 + PT-08 + JWT-attach
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Drains all three deferred perf-harness items in one batch:
- PT-01..PT-06 now carry Authorization: Bearer minted via the canonical
  SatelliteProvider.TestSupport.JwtTokenFactory (AZ-491) — no third copy
  of JWT logic in the shell.
- PT-07 implemented as cold + warm dual-pass distribution (N=20 each),
  reports p50/p95 for both passes and fails if warm p95 >= cold p95.
- PT-08 implemented as 20-batch upload distribution with batch p95 gated
  at the AZ-488 2000 ms target; per-item gate cost reported as derived
  proxy (batch_p95 / batch_size).

New SatelliteProvider.IntegrationTests/PerfBootstrap.cs adds two CLI
short-circuit subcommands (--mint-only and --gen-uav-fixture <path>)
invoked by the shell so the perf script never inlines the JWT or
JPEG-fixture logic. The dispatch sits at the top of Program.cs Main
and runs before any HTTP / DB / readiness setup.

performance-tests.md PT-07 + PT-08 flip from Deferred to Implemented.
traceability-matrix.md PT-07 + PT-08 rows move from recorded to covered
(PT-08 partial due to per-item proxy — flagged Low in batch-4 review).
_docs/_process_leftovers/2026-05-11_perf-pt07-harness.md deleted; the
leftovers directory is now empty.

Closes cycle-2 retro Action 2; LESSONS.md [process] rule about Deferred
NFRs remains in force as a guardrail.

Also includes the previously-uncommitted cumulative review report for
cycle-3 batches 01-03 (generated at the end of batch 3 but not staged).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 01:52:25 +03:00
Oleksandr Bezdieniezhnykh 745f4840e6 [AZ-493] Cycle 3 batch 3: integration test DB-reset hook
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
AZ-493 (2 SP): replace the cycle-2 wallclock-seeded _coordinateCounter
workaround with a proper Postgres state-reset hook that runs at
integration test runner startup, eliminating the per-source-unique-index
collision risk that the persistent docker-compose Postgres volume
introduced post-AZ-484.

The reset is split into two surfaces:

* SatelliteProvider.TestSupport.IntegrationTestResetGuard - pure
  static class, I/O-free, unit-tested. Two independent guards: (a)
  ASPNETCORE_ENVIRONMENT must equal "Testing", (b) DB_CONNECTION_STRING
  Host must be in the allowed-host list (postgres, localhost, 127.0.0.1).
  Failure of either guard surfaces a structured operator-friendly
  InvalidOperationException.
* SatelliteProvider.IntegrationTests.IntegrationTestDatabaseReset -
  instance class owning the Npgsql side effects. Calls the guard then
  runs TRUNCATE TABLE route_regions, route_points, routes, regions,
  tiles RESTART IDENTITY CASCADE inside a single Npgsql transaction.

Spec-vs-reality: the task spec prescribed "DB name contains _test" as
Guard 2; the actual compose file uses Database=satelliteprovider and
DB rename is gated on user confirmation per coderule.mdc. Substituted
a Host allowlist as the equivalent guard (intent identical: reject
remote / production hosts). Recorded as Low/Spec-Gap in the review.

Program.cs adds --keep-state CLI flag and INTEGRATION_KEEP_STATE env
var (1/true) opt-outs so a developer can inspect leftover state when
debugging. Startup banner shows which path executed.
docker-compose.tests.yml gets ASPNETCORE_ENVIRONMENT=Testing +
passthrough for INTEGRATION_KEEP_STATE. scripts/run-tests.sh wires the
--keep-state flag through to compose.

UavUploadTests._coordinateCounter wallclock seed is retained as
defense-in-depth (per the task spec's implementer choice). The reset
is the primary isolation path; the seed is the belt-and-suspenders
fallback for --keep-state runs.

8 new unit tests in SatelliteProvider.Tests/TestSupport/
IntegrationTestResetGuardTests.cs cover Production/Staging/missing-env
throw, allowed-host case-insensitivity, disallowed-host rejection
with representative prod hostnames, and the AllowedHosts contract.

tests_integration.md gains a Reliability section that documents the
hook, the two guards, the truncate order, and the three opt-out forms.
module-layout.md TestSupport entry extended with the new pure guard
and the explicit "Npgsql stays in IntegrationTests" boundary.

Test-suite gate (AC-6) deferred to Step 16 Final Test Run per implement
skill convention. Per-batch review verdict: PASS_WITH_WARNINGS with 1
Low (spec-vs-reality on Guard 2, non-blocking).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 01:38:42 +03:00
Oleksandr Bezdieniezhnykh c396740644 [AZ-491] Cycle 3 batch 2: consolidate JWT test-mint helpers into TestSupport
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
AZ-491 (3 SP): eliminate the cycle-2 duplicate of JWT-minting logic
that existed in both SatelliteProvider.Tests/TestUtilities/
JwtTokenFactory.cs (unit-side) and SatelliteProvider.IntegrationTests/
JwtTestHelpers.cs (integration-side), where the same Expires <
NotBefore bug needed parallel fixes in commits f64d0d7 + 11b7074.

Option A chosen: new SatelliteProvider.TestSupport class library
(no test framework) holds the canonical JwtTokenFactory.Create /
CreateExpired / TamperSignature. Both Tests and IntegrationTests
consume it via ProjectReference; production projects (Api, Common,
DataAccess, Services.*) cannot depend on it. The notBefore-shift
workaround is preserved with an inline regression-prevention comment
back-referencing the cycle-2 fix commits.

SatelliteProvider.IntegrationTests/JwtTestHelpers.cs is stripped to
runner-only concerns: ResolveSecretOrThrow, AttachDefaultAuthorization,
and the DefaultSubject = "integration-tests" constant. Call sites in
Program.cs, JwtIntegrationTests.cs, and UavUploadTests.cs (10 sites)
switched to JwtTokenFactory.* with JwtTestHelpers.DefaultSubject
explicitly passed for the runner subject - behavior parity preserved.

Dockerfile for IntegrationTests gets the new TestSupport csproj
in its pre-restore COPY layer. Api Dockerfile unchanged (TestSupport
is NOT a production dependency).

A new code-review SKILL.md Phase 6 checklist row flags near-identical
helper logic across test projects as a Medium / Maintainability
finding with explicit cycle-2 retro back-reference, so this whole
pattern stops at one occurrence.

module-layout.md adds a TestSupport Shared/Cross-Cutting entry
documenting the production-isolation invariant. tests_unit.md +
tests_integration.md updated to describe the consolidated layout.
sln updated.

Test-suite gate (AC-2 + AC-3) deferred to Step 16 Final Test Run
per implement-skill convention. Per-batch review verdict:
PASS_WITH_WARNINGS with 1 Low (pre-existing 7.0.3 version pin
preserved verbatim from cycle-2 IntegrationTests csproj for parity;
not blocking; deferred bump).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 01:32:24 +03:00
Oleksandr Bezdieniezhnykh 9cfd80babe [AZ-495] [AZ-496] Cycle 3 batch 1: doc convention + AspNetCore 8.0.25
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
AZ-495 (1 SP): formalize the modules-only documentation convention for
the WebApi component. _docs/02_document/module-layout.md now carries an
explicit Documentation Layout section anchoring WebApi docs at
modules/api_program.md; the components/06_web_api/ folder is
intentionally absent. .cursor/skills/new-task/SKILL.md Step 4 directs
future agents at the correct path. Cycle-1 + cycle-2 F1 findings in the
two batch-review files are marked RESOLVED with back-reference to
AZ-495. Cycle-2 retrospective decision-item list F1 updated.

AZ-496 (2 SP): bump Microsoft.AspNetCore.OpenApi and JwtBearer in
SatelliteProvider.Api.csproj from 8.0.21 to 8.0.25, closing CVE-
2026-26130 (SignalR DoS - not reachable in this app, but the runtime
patch is the recommended hardening per cycle-1 D1 + cycle-2 D3).
SatelliteProvider.Tests.csproj has no direct JwtBearer reference - it
consumes JwtBearer transitively via ProjectReference to Api, so no
edit needed there. Dockerfiles use floating mcr.microsoft.com/
dotnet/aspnet:8.0 / sdk:8.0 / runtime:8.0 tags which auto-resolve to
>= 8.0.25 on rebuild. Security artifacts (dependency_scan.md,
security_report.md) and current-state docs (module-layout.md,
architecture.md, modules/api_program.md, modules/tests_unit.md)
updated to reflect 8.0.25.

Batch report + code review report (verdict PASS_WITH_WARNINGS with 2
Low findings, neither blocking) written under _docs/03_implementation.

Test suite gate deferred to Step 16 (Final Test Run) per implement
skill convention. Patch-level bump within .NET 8 LTS; regression risk
very low.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 01:24:48 +03:00
Oleksandr Bezdieniezhnykh 76076cbd90 [AZ-491] [AZ-492] [AZ-493] [AZ-494] [AZ-495] [AZ-496] Cycle 3 Step 9: 6 task specs
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Drains the cycle-2 retrospective top-3 improvement actions plus three
carried-forward security and process items, into 6 individually-
trackable PBIs:

- AZ-491 (3 SP) consolidate JWT test-mint helpers (Retro Action 1)
- AZ-492 (3 SP) perf harness PT-07 + PT-08 + JWT-attach (Retro Act. 2)
- AZ-493 (2 SP) integration test DB-reset hook (Retro Action 3)
- AZ-494 (2 SP) JWT iss/aud validation (cycle-2 F-AUTH-2 Medium)
- AZ-495 (1 SP) doc-folder convention for WebApi (cycle 1+2 F1 carry)
- AZ-496 (2 SP) bump AspNetCore 8.0.21 -> 8.0.25 (cycle 1+2 D1+D3)

All 6 at-or-below the user-rule 5 SP cap. AZ-494 gated on admin-team
confirming iss/aud values. Cycle 3 total: 13 SP.

Autodev pointer advances to Step 10 Implement.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 01:15:21 +03:00
Oleksandr Bezdieniezhnykh b69cf5640e [AZ-487] [AZ-488] retro: cycle 2 report + structural snapshot
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Cycle-2 retrospective covering AZ-487 + AZ-488. Captures six patterns
(duplicate JWT helpers diverged then both broke; pre-existing
test bugs unmasked by downstream test pressure; cycle 1 perf-NFR
action stopped adding scenarios but did not drain backlog; doc-path
F1 carried over twice with no decision; integration test DB
isolation = wallclock workaround; 8 SP friction observable even
with user override). Top-3 improvement actions: consolidate JWT
mint helpers, promote PT-07/PT-08/JWT-attach to real PBI, real
integration DB-reset hook.

LESSONS.md ring buffer now holds 6 entries (testing x3, process x2,
estimation x1).

Structural snapshot: 6 components / 12 PR edges unchanged; contract
coverage 14% -> 29%; new external NuGet edges (JwtBearer 8.0.21 +
ImageSharp 3.1.11) tied to cycle-2 security findings.

Autodev pointer advances to cycle 3 / Step 9 New Task.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 00:43:27 +03:00
Oleksandr Bezdieniezhnykh e9f4e84adb [AZ-487] [AZ-488] docs: cycle 2 deploy report
Per-cycle deploy report covering AZ-487 (JWT baseline) + AZ-488 (UAV
tile batch upload). Lists all 12 cycle-2 commits already pushed to
origin/dev, recaps Steps 11-15 gate outcomes, flags three
operator-gated risks (R1 consumer Bearer-token coordination, R2
JWT_SECRET prod-distinct verification, R3 GPS-permission claim
provisioning), documents rollback (image flip; zero schema change),
and lists deferred follow-ups (PT-07/PT-08 harness + run-perf script
JWT-attach, F1 doc-folder choice).

Advances autodev pointer to Step 17 (Retrospective).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 00:37:32 +03:00
Oleksandr Bezdieniezhnykh cbbb26bd28 [AZ-487] [AZ-488] chore: cycle 2 Step 15 skip + record JWT-attach script rot
Step 15 (Performance Test) — skipped per gate (option B). Recording two
deferred items in the existing perf leftover:

* PT-07 + PT-08 remain Deferred. Both NFRs depend on the same
  baseline-capture harness that has not landed; the integration-test
  fixtures needed for PT-08 already exist (UavUploadTests +
  UavTileImageFactory), so PT-08 attaches to the same harness as PT-07
  when implemented.
* scripts/run-performance-tests.sh PT-01..PT-06 currently return 401
  against the post-AZ-487 build because they attach no Bearer token.
  Script must mint an HS256 token from JWT_SECRET at script start
  before any curl call. Tracked in the leftover so PT-01..PT-06 are
  runnable again the same cycle PT-07/PT-08 are activated.

No code change in this commit — leftover + state advance only.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 00:35:18 +03:00
Oleksandr Bezdieniezhnykh 5214a4a647 [AZ-487] [AZ-488] security: cycle 2 delta audit (PASS_WITH_WARNINGS)
Step 14 (Security Audit) for cycle 2 — delta scan against the cycle-1
baseline. Verdict remains PASS_WITH_WARNINGS; no Critical/High.

Scope: JWT auth boundary (AZ-487) and UAV multipart upload + ImageSharp
decode of attacker-controlled bytes (AZ-488). Both new packages
(JwtBearer 8.0.21, ImageSharp 3.1.11 in Services.TileDownloader)
checked.

Cycle-2 delta:
* 0 Critical / 0 High
* 2 Medium: F-AUTH-2 (iss/aud not validated — by design until admin
  team publishes values, AZ-487 § Constraints), F-UAV-1 (ImageSharp
  decode now runs on attacker-controlled bytes — mitigations
  sufficient; pin to GHSA subscribe-and-bump policy).
* 4 Low: F-AUTH-1 (DEV-ONLY secret in appsettings.Development.json —
  accepted), F-AUTH-3 (rate-limit gap extends to 401 floods — folds
  into cycle-1 I3), F-UAV-2 (JsonDocument.Parse on signature-validated
  claims — bounded by Kestrel header cap), D3 (JwtBearer shares D1
  patch line).
* 1 Informational: F-UAV-3 (reject reasons disclose gate structure —
  accepted UX trade-off; documented in contract).

OWASP refresh: A01 / A07 move from N/A (with caveat) to
PASS_WITH_WARNINGS (per-tenant authz absent; iss/aud + revocation
gaps tracked).

Pre-deploy operational gate added: deploy pipeline must verify
JWT_SECRET != DEV-ONLY placeholder before promoting api.

Artifacts: dependency_scan.md, static_analysis.md, owasp_review.md,
infrastructure_review.md, security_report.md — all appended with a
"Cycle 2 Delta" section preserving cycle-1 finding IDs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 00:13:58 +03:00
Oleksandr Bezdieniezhnykh e3cd388577 [AZ-487] [AZ-488] docs: cycle 2 doc sync (task mode)
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Step 13 (Update Docs) for cycle 2. Most cross-cutting docs were
already updated during Step 10 (architecture.md, glossary.md,
components/03_tile_downloader, modules/api_program.md, data_model.md,
contracts/api/uav-tile-upload.md). This commit completes the remaining
module-level + module-layout updates and writes the cycle-2 ripple log.

* modules/common_configs.md: + UavQualityConfig section and
  appsettings-section row (UavQuality).
* modules/common_dtos.md: + UavTileMetadata, UavTileBatchMetadataPayload,
  UavTileBatchUploadResponse, UavTileUploadResultItem, UavTileUploadStatus,
  UavTileRejectReasons (closed enumeration v1.0.0).
* module-layout.md: refresh Common (+ UavQualityConfig + UAV DTOs),
  TileDownloader (+ UavTileQualityGate, UavTileUploadHandler, +
  SixLabors.ImageSharp 3.1.11 PackageReference), and WebApi (+
  Authentication/*, DTOs/UavTileBatchUploadRequest, + JwtBearer 8.0.21
  PackageReference). Updates the "Last Updated" stamp to cycle 2.
* modules/tests_unit.md: replace the obsolete "only a dummy test"
  description; add cycle-2 AZ-487 / AZ-488 test classes
  (AuthenticationServiceCollectionExtensionsTests, JwtTokenFactoryTests,
  UavTileQualityGateTests, UavTileUploadHandlerTests, UavTileFilePathTests,
  PermissionsRequirementTests) + new ProjectReference / package
  references.
* modules/tests_integration.md: + JwtIntegrationTests, UavUploadTests
  (incl. wall-clock-seeded coordinate counter rationale from the Step 11
  fix), and the StubAndErrorContractTests update for the removed 501
  stub.
* ripple_log_cycle2.md (new): cycle-2 reverse-dependency scan results
  showing every importer of the new symbols resolves inside the three
  already-updated components (WebApi, TileDownloader, Common). No
  unexpected ripple, no heuristic fallback needed.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 00:04:05 +03:00
Oleksandr Bezdieniezhnykh 98cdcd17c1 [AZ-487] [AZ-488] docs: cycle 2 test-spec sync
Append cycle 2 entries to test-spec artifacts (cycle-update mode):

* security-tests.md: SEC-05..SEC-09 (AZ-487 JWT 401/403/parity)
  + SEC-10..SEC-11 (AZ-488 permission + reject-detail leak hygiene).
* blackbox-tests.md: BT-13..BT-17 (UAV happy / mixed / multi-source
  coexistence / same-source UPSERT / rule-ordering) + BT-18 (existing
  endpoints parity with Bearer token).
* resource-limit-tests.md: RL-05..RL-07 (MaxBatchSize, per-item MaxBytes,
  Kestrel/Form envelope cap).
* performance-tests.md: untouched (PT-08 already landed with AZ-488 as
  Deferred — see _docs/_process_leftovers/2026-05-11_perf-pt07-harness).
* traceability-matrix.md: append AC rows for AZ-487 AC-1..AC-8 and
  AZ-488 AC-1..AC-10 + AC-7a..AC-7e; annotate "No authentication"
  restriction as superseded by AZ-487+AZ-488; add NFR rows (perf,
  security, reliability, compatibility) for both tasks; refresh totals
  (78 tests; 47/47 ACs; 8/8 restrictions).

Coverage shape: AZ-487 AC-7 (Swagger Authorize) and the perf NFRs are
recorded but not actively measured this commit (manual UI smoke +
deferred PT-08 harness, respectively).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 00:00:14 +03:00
Oleksandr Bezdieniezhnykh dc3dabe7bd [AZ-488] fix: seed UavUploadTests coordinate counter from wall-clock
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Postgres data volume persists across docker-compose runs. The previous
`int _coordinateCounter = 0` reset on every test-runner process start
so the SECOND `--full` run collided with rows seeded by the first
`--smoke` run (the AC-3 MultiSourceCoexistence test does a raw INSERT
for the pre-seed step, not an UPSERT, and the unique constraint fires).

Seed the counter from a wall-clock value (~Unix epoch seconds mod 1M)
so each runner process picks a distinct coordinate band. Eliminates
inter-run collisions without coupling the test to docker volume reset.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 23:53:44 +03:00
Oleksandr Bezdieniezhnykh 1802d32107 [AZ-488] UAV tile batch upload + 5-rule quality gate
Replaces the 501 stub at POST /api/satellite/upload with a multipart
batch endpoint that ingests UAV-captured tiles, runs each item through
a 5-rule quality gate, and persists accepted tiles via the AZ-484
multi-source storage path with source='uav'.

Quality gate (in fixed order, first failure wins): JPEG format
(content-type + magic), size band 5 KiB-5 MiB, exact 256x256
dimensions, captured-at age (no future >30 s skew, no older than
7 days), luminance variance on 32x32 downsample. Closed reject-reason
enumeration in v1.0.0 contract.

Authorization: custom PermissionsRequirement / PermissionsAuthorization
Handler that reads the JWT `permissions` claim (tolerates both
repeated-string and JSON-array shapes). Endpoint protected by
RequiresGpsPermission policy; 401 without token, 403 without GPS perm.

Persistence: file-first to ./tiles/uav/{z}/{x}/{y}.jpg, then
ITileRepository.InsertAsync UPSERT (per-source UPSERT contract from
AZ-484). Per-item failures reported in response without aborting the
batch. Kestrel MaxRequestBodySize and FormOptions limits set to
MaxBatchSize x MaxBytes (default 100 x 5 MiB = 500 MiB).

New frozen contract: _docs/02_document/contracts/api/uav-tile-upload.md
v1.0.0. PT-08 NFR added to performance-tests.md as Deferred (harness
work tracked in PT-07 leftover, per AZ-488 § Risk 4).

Tests: 11 quality-gate unit tests, 5 handler unit tests, 3 file-path
unit tests, 12 permission-handler unit tests, 7 integration tests
(AC-1..AC-6, AC-8). All 253 unit tests + smoke integration suite
green.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 23:50:49 +03:00
Oleksandr Bezdieniezhnykh 11b7074485 [AZ-487] fix: integration-test JWT factory handles negative lifetime
Same fix as f64d0d7 applied to the integration tests' own copy of the
JWT mint helper. MintExpiredToken passes a negative lifetime which made
Expires < NotBefore and the JwtSecurityToken constructor rejected the
token before it could exercise lifetime-validation. Shift NotBefore
behind Expires for non-positive lifetimes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 23:47:26 +03:00
Oleksandr Bezdieniezhnykh f64d0d760a [AZ-487] fix: JWT factory + tests now pass on net8.0
- JwtTokenFactory.Create: negative `lifetime` produced Expires < NotBefore
  which `JwtSecurityToken` rejects at construction time. Shift NotBefore
  behind Expires whenever the requested lifetime is non-positive so the
  expired-token fixture round-trips and lifetime validation can fire.
- JwtTokenFactoryTests: validate against a handler with
  `MapInboundClaims = false` so assertions read the factory's own claim
  names ("sub", "email", "permissions") rather than the .NET-default
  remapped ClaimTypes.* aliases.

These were latent — masked by the CS0104 build break fixed in 753be43.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 23:45:12 +03:00
Oleksandr Bezdieniezhnykh 753be43d11 [AZ-487] fix: resolve CS0104 ambiguity in AuthN tests
`AuthenticationServiceCollectionExtensions` is also a built-in
.NET type under `Microsoft.Extensions.DependencyInjection`. With
both namespaces imported the unqualified references in this test
file failed with CS0104, breaking the entire test project build.
Resolved via a `using` alias so the call sites stay short while
the build stays unambiguous.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 23:41:31 +03:00
Oleksandr Bezdieniezhnykh 96cd3c4495 [AZ-487] JWT validation baseline (HS256, all endpoints)
ci/woodpecker/push/01-test Pipeline failed
ci/woodpecker/push/02-build-push unknown status
Adds Microsoft.AspNetCore.Authentication.JwtBearer 8.0.21 and the
SatelliteProvider.Api.Authentication.AddSatelliteJwt extension that
validates HS256 tokens against a shared JWT_SECRET (>=32 bytes, fail
fast at startup). Every minimal-API endpoint now carries
.RequireAuthorization(); the middleware chain is UseExceptionHandler ->
UseHttpsRedirection -> UseCors -> UseAuthentication -> UseAuthorization
-> endpoints. Swagger UI gets a Bearer security definition so the
Authorize button works.

Test infrastructure: JwtTokenFactory (unit) and JwtTestHelpers
(integration) mint deterministic tokens against the same secret; the
integration test runner attaches a default Bearer token to its shared
HttpClient so existing tests continue to exercise protected endpoints.
JwtIntegrationTests adds AC-1..AC-4 and AC-7 (Swagger advertises
Bearer) end-to-end; AuthenticationServiceCollectionExtensionsTests
covers AC-5 (missing/empty/short secret fail-fast) plus env-var
precedence; JwtTokenFactoryTests covers AC-6 (claims pass through
the JwtSecurityTokenHandler.ValidateToken path JwtBearer uses).

docker-compose and scripts/run-tests.sh now propagate JWT_SECRET to
the api and integration-tests containers, with a >=32-byte guard.
.env.example documents the required keys; .env stays gitignored.

Code review verdict: PASS_WITH_WARNINGS (2 Low findings surfaced
in _docs/03_implementation/reviews/batch_01_cycle2_review.md).

Cross-component coordination: gps-denied-onboard and the mission
planner UI must attach Bearer tokens before this lands in dev.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 23:06:23 +03:00
Oleksandr Bezdieniezhnykh 8e15e53782 chore: cycle 2 step 9 task plan artifacts + step 10 state
Carries forward new-task research + solution drafts under
_docs/02_task_plans/uav-batch-upload/ that were not included in
the Step 9 task-spec commit (42a3cc7). Also marks the autodev
state as Step 10 in_progress for cycle 2 implementation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 22:54:36 +03:00
Oleksandr Bezdieniezhnykh 42a3cc7467 [AZ-487] [AZ-488] Cycle 2 Step 9: JWT baseline + UAV upload task specs
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Created two PBIs for cycle 2 under epic AZ-483 (multi-source tile
storage + UAV upload). Splits the originally-planned single AZ-485
into 2 cohesive tasks because the combined scope was ~10 SP and
JWT auth is independently shippable:

- AZ-487 (2 SP) JWT validation baseline. Adds HS256 JwtBearer
  middleware against JWT_SECRET env var per the suite-level auth
  contract (suite/_docs/10_auth.md). Applies .RequireAuthorization()
  on all existing endpoints. Skips iss/aud validation (suite doc
  does not specify). No /users/me endpoints. Hard prerequisite for
  AZ-488.

- AZ-488 (8 SP, over-cap user-accepted) UAV tile upload endpoint
  with batch + 5-rule quality gate. Replaces the 501 stub. Multipart
  batch DTO, 5 quality rules (format, size band, dimensions,
  captured_at age 7d, blank/uniform variance heuristic). UAV files
  land at ./tiles/uav/{z}/{x}/{y}.jpg; google_maps grandfathered
  at bare ./tiles/{z}/{x}/{y}.jpg. Per-source UPSERT via the
  AZ-484 ITileRepository.InsertAsync. Sync 200 with per-item
  results. Requires GPS permission claim. Produces frozen contract
  uav-tile-upload.md v1.0.0.

Both Jira tickets created and linked. Dependencies table updated.
Autodev state advanced to cycle 2 Step 10 (Implement).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 21:04:49 +03:00
Oleksandr Bezdieniezhnykh 18609656f9 [AZ-484] Cycle 1 Step 17 Retrospective: report + structural snapshot
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Closes the AZ-484 cycle:
- retro_2026-05-11.md: 5 patterns identified (code-review-PASS does
  not imply runtime PASS; spec-authorship under-specifies wire
  format / test sites; NFR test-spec entries decoupled from runner
  scripts; pre-existing module doc staleness; pre-existing security
  Mediums now visible). Top-3 actions ranked by impact, with target
  rule/skill files and owners.
- structure_2026-05-11.md: baseline structural snapshot for future
  retro deltas (6 components, 12 ProjectReference edges, 0 cycles
  in import graph, 0 net architecture violations, 1 frozen
  contract, ~14% contract coverage).
- LESSONS.md: header rewritten to describe the two-layer format
  (deep lessons + 15-entry ring buffer); appended 3 new ring-buffer
  entries (testing/process/estimation) sourced from this retro.
- _autodev_state.md: cycle 2 starting at Step 9 New Task.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 10:08:47 +03:00
Oleksandr Bezdieniezhnykh 51b572108a [AZ-484] Cycle 1 Steps 12-16: docs, security, perf, deploy report
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Captures the post-implementation autodev gates for AZ-484 multi-source
tile storage:

- Step 12 (Test-Spec Sync): added 7 AC rows (AZ-484 AC-1..AC-7) and a
  PT-07 NFR row to traceability-matrix.md; added PT-07 scenario to
  performance-tests.md.
- Step 13 (Update Docs): refreshed data_model.md (tiles columns +
  indexes + selection rule + UPSERT contract + migrations 012/013),
  module-layout.md (Common/Enums section with L-001 guidance,
  DataAccess imports-from now lists 6 sites), 6 module / component
  docs to reflect the new repo signatures, source/captured_at fields,
  and Dapper enum bypass workaround. ripple_log_cycle1.md records
  zero out-of-scope ripple.
- Step 14 (Security Audit): PASS_WITH_WARNINGS - 0 Critical, 0 High,
  5 Medium, 5 Low. AZ-484 itself added zero new findings. Hardening
  items (Postgres default creds, .env in build context, GMaps key
  rotation, ASP.NET Core 8.0.21 -> 8.0.25, rate limiter) recorded
  for separate tickets.
- Step 15 (Performance Test): all PT-01..PT-07 scenarios Unverified
  (non-blocking); PT-07 baseline-comparison harness deferred to a
  leftover for next cycle.
- Step 16 (Deploy): cycle deploy report covering migration safety,
  rollback path, post-deploy verification, security caveats.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 10:03:05 +03:00
Oleksandr Bezdieniezhnykh e9d6db077c [AZ-484] Fix multi-source tile reads: drop Dapper enum handler
Two integration-test failures uncovered after the initial commit:

1) GetTilesByRegionAsync outer ORDER BY referenced 'updated_at' but
   the inner DISTINCT ON subquery aliased it to 'UpdatedAt' (Postgres
   folds to 'updatedat'). DISTINCT ON already guarantees one row per
   (latitude, longitude, ...) so the third tiebreak was unreachable;
   removed it.

2) Dapper 2.1.35 silently bypasses SqlMapper.TypeHandler<T> for enum
   types during read deserialization (Dapper issue #259). The
   TileSourceTypeHandler worked for writes but reads fell through to
   Enum.TryParse, which cannot map 'google_maps' to GoogleMaps.

   Pivoted: TileEntity.Source is now a string (the wire value).
   TileSource enum stays as the public producer surface in
   Common.Enums; TileSourceConverter (Common.Enums) provides
   ToWireValue / FromWireValue / IsValidWireValue at the boundary.
   TileSourceTypeHandler deleted; registration removed from
   DapperEnumTypeHandlers.RegisterAll.

   tile-storage.md Inv-5 amended to document the storage choice.
   _docs/LESSONS.md L-001 records the Dapper bypass for future cycles.

Full suite passes (213 unit + integration suite incl. AZ-484
AC-1..AC-5, security SEC-01..SEC-04, AZ-356/362/357).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 06:44:34 +03:00
Oleksandr Bezdieniezhnykh 687d6bdd5b [AZ-484] Multi-source tile storage: source + captured_at
Add per-source tile rows to support multi-provider imagery (Google
Maps + future UAV). Migration 013 (transactional) introduces
source/captured_at columns, backfills existing rows to
(source='google_maps', captured_at=created_at), and replaces the
4-column unique index with a 5-column index that includes source.

TileRepository:
- ColumnList includes source + captured_at
- GetByTileCoordinatesAsync returns most-recent row across sources
  (ORDER BY captured_at DESC, updated_at DESC, id DESC)
- GetTilesByRegionAsync uses DISTINCT ON to pick the most-recent
  tile per cell, restoring caller-facing row order
- Insert/Update upsert on the new 5-column conflict key

TileSource enum lives in Common.Enums. Snake_case wire format
(google_maps, uav) is enforced by a focused TileSourceTypeHandler
because the generic ToLowerInvariant pattern would emit
"googlemaps", violating contract v1.0.0.

TileService stamps Source=GoogleMaps + CapturedAt=UtcNow on every
new tile. Tile-storage contract is now frozen at v1.0.0.

AC coverage 7/7. New unit + integration tests cover all ACs;
existing 200 unit + 5 smoke tests preserved.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 06:21:59 +03:00
Oleksandr Bezdieniezhnykh 5ba58b6c8d [AZ-484] [AZ-483] Add task spec + tile-storage v1.0.0 contract draft
Step-9 (new-task) cycle 1 artifacts for the AZ-483 multi-source tile
storage epic. AZ-485 (UAV upload + quality gate) deferred to a future
Step-9 loop and recorded as planned in the dependencies table.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 06:05:06 +03:00
Oleksandr Bezdieniezhnykh 08451df027 [AZ-350] Close 03-code-quality-refactoring: Phase 6+7 + FINAL_report
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Phase 6 (Verification): smoke run green (format gate + 200/200
unit + integration smoke). verification_report.md captures
metric deltas vs Phase 0 baseline; all 5 ACs met, all 4
constraints honored, 0 regressions.

Phase 7 (Documentation):
- module-layout.md: corrected DataAccess->Common dependency
  (was mistakenly documented as "Imports from: (none)" by
  prior AZ-315 baseline; csproj reference + 7 import sites
  have actually been there since AZ-309).
- architecture_compliance_baseline.md: F5 entry revised to
  reflect the actual layering invariant (one-way: Common
  MUST NOT import from DataAccess, but DataAccess MAY
  import from Common).
- 00_discovery.md: added "Updates Since Baseline" section
  enumerating the AZ-309 split + AZ-350 27-change run +
  AZ-372 tooling additions; original tree kept as a
  2026-05-10 snapshot.

FINAL_report: complete run summary (10 batches, 27 tasks,
3 K=3 cumulative reviews, baseline->final metric table,
remaining items, lessons learned).

Autodev state: advance Step 8 -> Step 9 (New Task);
sub_step reset to phase 0 awaiting-invocation.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 05:23:35 +03:00
Oleksandr Bezdieniezhnykh 9a53bff92e [AZ-375] [AZ-377] HashSet tile lookup + consolidate Earth constants
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Batch 24 of 03-code-quality-refactoring run; closes the run.

AZ-375 (C22): GoogleMapsDownloaderV2.DownloadTilesGridAsync now
builds a HashSet<(int X, int Y, int Z)> once from existingTiles
and tests Contains((x, y, zoomLevel)) per cell. Removes the per-cell
FirstOrDefault tolerance scan and the unused _processingConfig
.LatLonTolerance reference at this site.

AZ-377 (C24): promote Earth + tile-pixel constants to a single
home. GeoUtils now exposes EarthRadiusMeters, EarthEquatorial
CircumferenceMeters, MetersPerDegreeLatitude as public const.
MapConfig adds DefaultTileSizePixels (const) wired as the
TileSizePixels property default. TileRepository and Google
MapsDownloaderV2 read those constants instead of duplicating
the literals 6378137, 40075016.686, 111000.0, and 256.

Tests: +6 new (DownloaderRefactorTests, extended GeoUtils
RefactorTests). 200/200 unit tests pass.

Cumulative K=3 review (batches 22-24): PASS_WITH_WARNINGS,
4 Low findings only — see
_docs/03_implementation/reviews/cumulative_review_22-24.md.

Tooling fix: scripts/run-tests.sh --unit-only path now restores
before testing (was failing on SixLabors resolution in clean
container). Stripped stray BOM from MapConfig.cs to satisfy the
.editorconfig charset gate.

Updates _dependencies_table.md to reflect all 27 03-code-quality-
refactoring tasks done; updates _autodev_state.md to refactor
phase 5 (test-sync).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 05:14:51 +03:00
Oleksandr Bezdieniezhnykh 6099d1c86b [AZ-376] [AZ-378] [AZ-379] [AZ-380] Repo cleanup: dead code, logger discipline, ColumnList consts
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Batch 23 of refactor 03-code-quality-refactoring (4 tasks, 5 SP):

- AZ-376 (C23): Delete unused FindExistingTileAsync from
  ITileRepository / TileRepository. No callers; method also took the
  obsolete `version` arg removed by C06/AZ-357.
- AZ-378 (C25): Repository _logger discipline.
  TileRepository.GetTilesByRegionAsync now emits LogWarning when the
  query exceeds SlowQueryThresholdMs (500 ms). RegionRepository and
  RouteRepository drop the unused ILogger<TRepo> field, parameter, and
  using; Program.cs DI registrations updated.
- AZ-379 (C26): Extract `private const string ColumnList` per repo
  (TileRepository, RegionRepository, RouteRepository); SELECTs use
  $@"SELECT {ColumnList} FROM ..." (C# 10+ const interpolation).
  INSERT/UPDATE/DELETE unchanged; route_points single-site SELECT left
  inline.
- AZ-380 (C27): Delete dead alias GeoUtils.CalculatePolygonDiagonalDistance.

Tests: +9 new (RepositoryRefactorTests x8, GeoUtilsRefactorTests x1)
covering each AC via reflection / file-content assertions; pattern
mirrors ToolingConfigurationTests (b22) and AcceptanceCriteriaRT2Tests
(b19). Unit suite 181 -> 190, all green. dotnet format clean.

Code review: PASS_WITH_WARNINGS (3 Low findings, all informational or
out-of-scope for this batch). See
_docs/03_implementation/reviews/batch_23_review.md.

Cumulative review counter 2/3; next K=3 review fires after batch 24.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 04:57:49 +03:00
Oleksandr Bezdieniezhnykh 534ab41b8e [AZ-372] Apply dotnet format whitespace cleanup; archive batch 22
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Pure whitespace-only cleanup uncovered by the new format gate from the
previous commit. Verified via `git diff -w --stat`: only 4 files differ
when whitespace is ignored, and those differ only by the BOM byte.

Cleanup kinds applied across 22 source files:
- BOM removal (MapConfig.cs, SatTile.cs, GeoUtils.cs,
  IntegrationTests/Program.cs)
- CRLF -> LF (IntegrationTests/Program.cs)
- Trailing whitespace on blank lines (Common, Api, DataAccess,
  IntegrationTests, Services.RegionProcessing,
  Services.TileDownloader)
- Final newline added (RoutePoint.cs, GeoPoint.cs, others)

After this commit `dotnet format whitespace SatelliteProvider.sln
--verify-no-changes` exits 0; AC-1 is enforceable from `scripts/
run-tests.sh` going forward.

Also lands the batch 22 report, code-review report
(PASS_WITH_WARNINGS, 2 Low findings — both deferred per spec),
dependency-table status update (AZ-372 -> Done (In Testing)), task
archive (todo/ -> done/), and autodev state update.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 04:43:08 +03:00
Oleksandr Bezdieniezhnykh 68359350fc [AZ-372] Add .editorconfig, Directory.Build.props, format/coverage wiring
Wires the C19 tooling baseline so dotnet format and Coverlet gate the
test script and a small NetAnalyzers ruleset (CA1001, CA1051, CA1816,
CA2227) at warning severity is visible from the next build.

- .editorconfig (new, root=true): whitespace rules, per-extension
  indent sizes, C# style preferences as suggestions, initial CA rules.
- Directory.Build.props (new): EnableNETAnalyzers=true,
  AnalysisLevel=latest, AnalysisMode=None so only rules explicitly
  enabled in .editorconfig fire; EnforceCodeStyleInBuild=false to keep
  build clean from style.
- scripts/run-tests.sh: Step 0 runs dotnet format whitespace
  --verify-no-changes via Docker SDK; unit/integration test calls now
  collect XPlat Code Coverage into TestResults/. New --skip-format
  escape hatch.
- .gitignore: TestResults/, coverage.cobertura.xml, *.coverage.
- SatelliteProvider.Tests/ToolingConfigurationTests.cs (new, 6 tests):
  runtime assertions that the config files, script wiring, and
  coverlet.collector reference are all in place; mirrors the
  AcceptanceCriteriaRT2Tests pattern.

Whitespace cleanup that the new format gate uncovers is staged for the
next commit (per AZ-372 spec: "commit cleanup as a separate batch").

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 04:42:45 +03:00
Oleksandr Bezdieniezhnykh 8fee955bb5 [AZ-350] autodev state: ready for batch 22 (AZ-372)
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 04:25:19 +03:00
Oleksandr Bezdieniezhnykh a7c622204f [AZ-350] Cumulative K=3 review for batches 19-21: PASS_WITH_WARNINGS
F1 (Low/Maintainability): module-layout.md docs stale on DataAccess
project reference after AZ-370; tracked for refactor Phase 7.
F2 (Low/Maintainability): redundant builder.Services.AddHttpClient()
in Program.cs after AZ-374; deferred per batch 21 design note.
No Critical/High findings; auto-chain to next batch (AZ-372).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 04:23:28 +03:00
Oleksandr Bezdieniezhnykh fae0d1cc34 [AZ-374] Update autodev state: cumulative-review pending
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 04:18:08 +03:00
Oleksandr Bezdieniezhnykh 7736cfd761 [AZ-374] Add batch 21 report; autodev state batch 21 complete
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 04:11:57 +03:00
Oleksandr Bezdieniezhnykh 89b4bfd245 [AZ-374] Refactor C21: named GoogleMapsTiles HttpClient in DI
- Register IHttpClientFactory named client "GoogleMapsTiles" inside
  AddTileDownloader() with User-Agent and 100s timeout (preserves
  HttpClient's implicit default).
- Resolve the same named client from all three CreateClient() call
  sites in GoogleMapsDownloaderV2 (session token, single-tile,
  batch-tile retry lambda) and drop the duplicated per-call
  UserAgent.ParseAdd setup.
- Expose USER_AGENT, the client name, and the timeout as internal
  consts on GoogleMapsDownloaderV2 so the extension and the
  downloader share one source of truth.
- Add AC test that builds the DI container, resolves the named
  client, and asserts both the User-Agent header and the timeout.
- Archive AZ-374 task file: todo/ -> done/.

175 unit + 5 smoke pass.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 04:11:57 +03:00
Oleksandr Bezdieniezhnykh 1ca8c80d7b [AZ-373] Add batch 20 report; autodev state batch 20 complete
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 04:05:45 +03:00
Oleksandr Bezdieniezhnykh 7c37636fdf [AZ-373] Refactor C20: drop MapsVersion from new writes (option a)
- Stop writing "downloaded_YYYY-MM-DD" into tiles.maps_version: new rows
  bind @MapsVersion to NULL via TileService.BuildTileEntity.
- Retain the tiles.maps_version column (coderule.mdc forbids unprompted
  column drops); pre-existing rows keep their values for forensics.
- Remove MapsVersion property from DownloadTileResponse (API wire shape)
  and TileMetadata (internal DTO); OpenAPI schema regenerates from the
  DTO via Swashbuckle.
- Add 3 AC tests in TileServiceTests covering the captured-entity write
  (AC-1) and the DTO/wire-shape removal (AC-2).
- Update integration-test local DTO + console output; refresh docs in
  common_dtos.md, services_tile_service.md, data_model.md.
- Archive AZ-373 task file: todo/ -> done/.

174 unit + 5 smoke pass.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 04:05:40 +03:00
Oleksandr Bezdieniezhnykh 45f7852fb2 [AZ-370] Add batch 19 report
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 03:56:27 +03:00
Oleksandr Bezdieniezhnykh 23ab05766d [AZ-370] Refactor C17: status / point-type enums + AC RT2 update
Replaces bare strings with two enums in Common/Enums/:
  RegionStatus { Queued, Processing, Completed, Failed }
  RoutePointType { Start, End, Action, Intermediate }

Adds a Dapper EnumStringTypeHandler<T> (DataAccess/TypeHandlers/)
that round-trips enums to/from lowercase strings, registered once
at startup via DapperEnumTypeHandlers.RegisterAll(). DataAccess now
references Common (project ref) so entities can carry the enum types.

Sites converted: RegionService (5), RouteProcessingService (3),
RoutePointGraphBuilder (4), entity Status/PointType columns. Log
message and summary file format preserved via .ToLowerInvariant().

API JSON contract preserved by adding JsonStringEnumConverter with
JsonNamingPolicy.CamelCase to the http JSON options — single-word
enum members serialize to the same lowercase strings as before.

DTO renamed: Common.DTO.RegionStatus -> RegionStatusResponse to
free the RegionStatus name for the new enum (forced by the task's
explicit enum name); the renamed DTO has no public-API impact at
the JSON wire level. Stale doc references updated.

AC RT2 in _docs/00_problem/acceptance_criteria.md now lists all 4
point types (start/end/action/intermediate).

Tests: 171 / 171 unit + 5 / 5 smoke green (was 141 + 5; +30 new tests
covering type handler round-trip, set/parse, unknown-value rejection,
idempotent registration, and the AC RT2 doc check).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 03:55:22 +03:00
Oleksandr Bezdieniezhnykh 6d98c8f8d1 [AZ-350] Cumulative K=3 review for batches 16-18: PASS (0 findings)
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 03:34:01 +03:00
Oleksandr Bezdieniezhnykh aa8beaa684 [AZ-371] Archive task file: todo -> done
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 03:30:25 +03:00
Oleksandr Bezdieniezhnykh 4456542cec [AZ-350] autodev state: batch 18 (AZ-371) complete
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 03:30:24 +03:00
Oleksandr Bezdieniezhnykh 1dcd089d39 [AZ-371] Refactor C18: magic numbers to ProcessingConfig/MapConfig
Promotes 8 operational levers into config keys with defaults that match
the prior source literals byte-for-byte:
  ProcessingConfig: RegionProcessingTimeoutSeconds (300),
  RouteProcessingPollIntervalSeconds (5),
  MaxRoutePointSpacingMeters (200), LatLonTolerance (0.0001).
  MapConfig: TileSizePixels (256), AllowedZoomLevels ([15..19]),
  RetryBaseDelaySeconds (1), RetryMaxDelaySeconds (30).

Sites updated: RegionService, RouteProcessingService,
RoutePointGraphBuilder, RouteValidator, RouteService 4-arg ctor,
RouteImageRenderer, GoogleMapsDownloaderV2, TileService. Closes LF-2 by
forwarding HttpContext.RequestAborted from GetTileByLatLon into the
downloader. appsettings.json gains the 8 new keys at default values.

Tests: 141 / 141 unit + 5 / 5 smoke green. New ConfigDefaultsTests pins
defaults to original literals; new TileService unit test asserts CT
identity from caller to downloader (AZ-371 AC-3).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 03:30:07 +03:00
Oleksandr Bezdieniezhnykh ee42b1716b [AZ-364] [AZ-360] Archive task files: todo -> done
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 03:13:01 +03:00
Oleksandr Bezdieniezhnykh ea1ca714f6 [AZ-350] autodev state: batch 17 (AZ-364, folds AZ-360) complete
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 03:12:59 +03:00
Oleksandr Bezdieniezhnykh 6f23120c49 [AZ-364] [AZ-360] Refactor C11+C08: decompose RouteProcessingService
Extracts RouteRegionMatcher, RouteCsvWriter, RouteSummaryWriter,
RouteImageRenderer, TilesZipBuilder, RegionFileCleaner from the
~750-LOC RouteProcessingService god-class. Moves TileInfo to its
own file as a sealed record. Replaces IServiceProvider scope-
locator with a direct IRegionService injection (folds AZ-360 / C08).
Updates DI registration and tests.

Tests: 133 / 133 unit + 5 / 5 smoke green; integration suite exit 0.
Pixel-equivalent stitched route image and byte-equivalent CSV /
summary / ZIP outputs verified through the smoke run.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 03:12:49 +03:00
Oleksandr Bezdieniezhnykh 70a0a2c4d5 [AZ-367] Archive task file: todo -> done
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 02:55:51 +03:00
Oleksandr Bezdieniezhnykh 3603dd319c [AZ-350] autodev state: batch 16 (AZ-367) complete
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 02:55:29 +03:00
Oleksandr Bezdieniezhnykh 10d31b4c1c [AZ-367] Refactor C14: extract shared TileGridStitcher
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 02:55:25 +03:00
Oleksandr Bezdieniezhnykh 23d513b24c [AZ-350] Remove processed leftover after archive replay
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 02:41:38 +03:00
Oleksandr Bezdieniezhnykh 7729cee2d3 [AZ-350] Archive previously-completed task files todo -> done
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 02:40:19 +03:00
Oleksandr Bezdieniezhnykh c98f6fde48 [AZ-350] Record leftover: 3 un-archived task files from batches 11-13
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 02:39:13 +03:00
Oleksandr Bezdieniezhnykh 1b62b3268a [AZ-350] autodev state: batch 15 (AZ-365) complete; K=3 review done
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 02:08:28 +03:00
Oleksandr Bezdieniezhnykh bcb9bf5130 [AZ-350] Cumulative code review batches 13-15: PASS, 0 findings
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 02:08:26 +03:00
Oleksandr Bezdieniezhnykh f7ad7aa5ab [AZ-365] Refactor C12: decompose RouteService.CreateRouteAsync
Extract RouteValidator (aggregating validator), RoutePointGraphBuilder
(point interpolation + sequence numbering), GeofenceGridCalculator
(NW/SE region centers), and RouteResponseMapper (entity -> DTO; also
used by GetRouteAsync, eliminating duplicate DTO assembly).

CreateRouteAsync shrinks 184 -> 52 LOC of orchestration. RouteService.cs
shrinks 295 -> 138 LOC overall. Validation aggregates all failures into
a single ArgumentException (AC-2); single-violation messages preserved
verbatim so existing RouteServiceTests pass unchanged. 28 new unit
tests for the four helpers (112/112 unit tests, smoke green).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 02:08:21 +03:00
Oleksandr Bezdieniezhnykh d327000fb6 [AZ-350] autodev state: batch 14 (AZ-369) complete
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 01:55:33 +03:00
Oleksandr Bezdieniezhnykh d2d9f6352b [AZ-369] Refactor C16: move inline DTOs out of Program.cs
Move 5 cross-component DTOs (GetSatelliteTilesResponse, SatelliteTile,
SaveResult, DownloadTileResponse, RequestRegionRequest) to
SatelliteProvider.Common/DTO/. Keep UploadImageRequest in the API
project under SatelliteProvider.Api.DTOs (IFormFile depends on
Microsoft.AspNetCore.Http; pulling it into Common would force an
ASP.NET framework reference into the foundation layer and break the
module-layout "Common: Imports from: (none)" invariant). Move
ParameterDescriptionFilter to SatelliteProvider.Api.Swagger.

Program.cs shrinks from 366 to 257 lines and now contains only
endpoint wiring (AC-1). JSON wire shape and Swagger schema names are
preserved (AC-2). 84 unit + full integration suite green (AC-3).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 01:54:35 +03:00
Oleksandr Bezdieniezhnykh 4c88201e5c [AZ-350] autodev state: batch 13 (AZ-368) complete
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 01:08:19 +03:00
Oleksandr Bezdieniezhnykh 89260d0ec4 [AZ-368] Refactor C15: extract shared TileCsvWriter
Both RegionService.GenerateCsvFileAsync and
RouteProcessingService.GenerateRouteCsvAsync wrote the same CSV
shape: header "latitude,longitude,file_path", same
OrderByDescending(Latitude).ThenBy(Longitude) ordering, same F6
numeric format. Two near-identical writers with no shared abstraction.

Extracted TileCsvWriter (instance class, no DI dependencies) plus a
TileCsvRow record bridging the per-pipeline DTOs (TileMetadata vs
TileInfo) to a single contract. The header constant, ordering rule,
and StreamWriter lifecycle now live in one place.

Both call sites collapse to a one-line projection plus a delegated
WriteAsync call. Region method becomes static (no longer references
instance state). Route method preserves its existing logger line.

Coverage:
- 7 new unit tests including a byte-for-byte equivalence test that
  writes the same input via both the new TileCsvWriter and the
  inlined-original code path side by side and asserts file bytes
  are identical.
- Integration smoke + full suite green; route + region CSV outputs
  unchanged across all existing scenarios (verified by extended-route
  CSV verification step in the integration suite).
- 84/84 unit tests pass (was 77).

Side improvement: writer now respects CancellationToken mid-loop.
The pre-refactor inline code did not. Strict improvement; consistent
with every other async API in the codebase.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 01:07:51 +03:00
Oleksandr Bezdieniezhnykh 098f905796 [AZ-350] Cumulative code review batches 10-12: PASS, 0 findings
ci/woodpecker/push/01-test Pipeline was successful
ci/woodpecker/push/02-build-push Pipeline was successful
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 01:01:46 +03:00
433 changed files with 37267 additions and 2081 deletions
+136 -72
View File
@@ -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/ /problem — interactive problem gathering → _docs/00_problem/
/research — solution drafts → _docs/01_solution/ /research — solution drafts → _docs/01_solution/
/plan — architecture, components, tests → _docs/02_document/ /plan — architecture, ADRs, components, tests, epics → _docs/02_document/
/decomposeatomic task specs → _docs/02_tasks/todo/ /test-specblackbox/perf/resilience/security test specs → _docs/02_document/tests/
/implementbatched parallel implementation → _docs/03_implementation/ /decompose — atomic task specs (multi-mode) → _docs/02_tasks/todo/
/deploy containerization, CI/CD, observability → _docs/04_deploy/ /implementsequential 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 ## 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: Skills auto-chain without pausing between them. The only pauses are:
- **BLOCKING gates** inside each skill (user must confirm before proceeding) - **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: There are three flows, resolved on every invocation (see `skills/autodev/SKILL.md` § Flow Resolution):
- Session 1: Problem → Research → Research decision
- Session 2: Plan → Decompose
- Session 3: Implement (may span multiple sessions)
- Session 4: Deploy
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 ## Skill Descriptions
### autodev (meta-orchestrator) ### 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 ### 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 ### 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 ### 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 ### 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 ### 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. 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.
### 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.
### code-review ### 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 ### 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 ### 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 16 (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 ### 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 ### 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) ## 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/ 1. /problem — interactive 4-phase interview → _docs/00_problem/
- problem.md (required) required: problem.md, restrictions.md, acceptance_criteria.md, input_data/
- restrictions.md (required) optional: security_approach.md
- acceptance_criteria.md (required) 2. /research — solution drafts (Mode A draft, Mode B assess) → _docs/01_solution/
- input_data/ (required) 3. /plan — glossary, architecture vision, architecture, data model, deployment, components,
- security_approach.md (optional) risks, ADRs (Step 4.5), test specs, epics → _docs/02_document/
(Step 1 invokes /test-spec internally)
1. /research — solution drafts → _docs/01_solution/ 4. /ui-design — HTML+Tailwind mockups (UI projects only) → _docs/02_document/ui_mockups/
Run multiple times: Mode A → draft, Mode B → assess & revise 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)
2. /plan — architecture, data model, deployment, components, risks, tests, epics → _docs/02_document/ 6. /decompose — implementation tasks + module-layout + system-pipeline owner tasks →
_docs/02_tasks/todo/
3. /decompose — atomic task specs + dependency table → _docs/02_tasks/todo/ 7. /implement — sequential dependency-aware batches; per-batch code-review;
Product Completeness Gate + System-Pipeline Audit → _docs/03_implementation/
4. /implement — batched parallel agents, code review, commit per batch → _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 ### 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 ### EVOLVE
``` ```
6. /refactor — structured refactoring → _docs/04_refactoring/ 18. /retrospective — metrics + trends + lessons-log update → _docs/06_metrics/ + _docs/LESSONS.md
7. /retrospective — metrics, trends, improvement actions → _docs/06_metrics/ (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 ## Available Skills
| Skill | Triggers | Output | | 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/` | | **problem** | "problem", "define problem", "new project" | `_docs/00_problem/` |
| **research** | "research", "investigate" | `_docs/01_solution/` | | **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/` | | **test-spec** | "test spec", "blackbox tests", "test scenarios" | `_docs/02_document/tests/` + `scripts/` |
| **decompose** | "decompose", "task decomposition" | `_docs/02_tasks/todo/` | | **decompose** | "decompose", "task decomposition", "decompose tests" | `_docs/02_tasks/todo/` + `_docs/02_document/module-layout.md` |
| **implement** | "implement", "start implementation" | `_docs/03_implementation/` | | **implement** | "implement", "start implementation" | `_docs/03_implementation/` (sequential — see `no-subagents.mdc`) |
| **test-run** | "run tests", "test suite", "verify tests" | Test results + verdict | | **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 | | **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/` | | **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/` | | **ui-design** | "design a UI", "mockup", "design system" | `_docs/02_document/ui_mockups/` |
| **refactor** | "refactor", "improve code" | `_docs/04_refactoring/` | | **refactor** | "refactor", "improve code", "testability" | `_docs/04_refactoring/NN-<run-name>/` |
| **security** | "security audit", "OWASP" | `_docs/05_security/` | | **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/` | | **document** | "document", "document codebase", "reverse-engineer docs" | `_docs/02_document/` + `_docs/00_problem/` + `_docs/01_solution/` |
| **deploy** | "deploy", "CI/CD", "observability" | `_docs/04_deploy/` | | **deploy** | "deploy", "CI/CD", "observability", "containerize" | `_docs/04_deploy/` (plans + scripts) |
| **retrospective** | "retrospective", "retro" | `_docs/06_metrics/` | | **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 > 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.
| Tool | Type | Purpose |
|------|------|---------|
| `implementer` | Subagent | Implements a single task. Launched by `/implement`. |
## Project Folder Structure ## Project Folder Structure
``` ```
_project.md — project-specific config (tracker type, project key, etc.)
_docs/ _docs/
├── _autodev_state.md — autodev orchestrator state (progress, decisions, session context) ├── _autodev_state.md — autodev orchestrator state (≤30 lines; pointer only)
├── 00_problem/ problem definition, restrictions, AC, input data ├── _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 ├── 00_research/ — intermediate research artifacts
├── 01_solution/ — solution drafts, tech stack, security analysis ├── 01_solution/ — solution drafts, tech stack, security analysis
├── 02_document/ ├── 02_document/
│ ├── architecture.md │ ├── architecture.md — includes ## Architecture Vision (user-confirmed)
│ ├── glossary.md — user-confirmed terminology
│ ├── system-flows.md │ ├── system-flows.md
│ ├── data_model.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 │ ├── risk_mitigations.md
│ ├── adr/[NNN]_[decision_slug].md — Architectural Decision Records (plan Step 4.5)
│ ├── components/[##]_[name]/ — description.md + tests.md per component │ ├── components/[##]_[name]/ — description.md + tests.md per component
│ ├── contracts/<component>/<name>.md — versioned public-API contracts
│ ├── common-helpers/ │ ├── common-helpers/
│ ├── tests/ — environment, test data, blackbox, performance, resilience, security, traceability │ ├── tests/ — environment, test-data, blackbox, performance, resilience, security, resource-limit, traceability matrix
│ ├── deployment/ — containerization, CI/CD, environments, observability, procedures
│ ├── ui_mockups/ — HTML+CSS mockups, DESIGN.md (ui-design skill) │ ├── ui_mockups/ — HTML+CSS mockups, DESIGN.md (ui-design skill)
│ ├── diagrams/ │ ├── diagrams/
│ └── FINAL_report.md │ └── FINAL_report.md
@@ -192,12 +255,13 @@ _docs/
│ ├── backlog/ — parked tasks (not scheduled yet) │ ├── backlog/ — parked tasks (not scheduled yet)
│ └── done/ — completed/archived tasks │ └── done/ — completed/archived tasks
├── 02_task_plans/ — per-task research artifacts (new-task skill) ├── 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 │ └── reviews/ — code review reports per batch
├── 04_deploy/ — containerization, CI/CD, environments, observability, procedures, scripts ├── 04_deploy/ — containerization, CI/CD, environments, observability, procedures, deploy_scripts.md, reports/
├── 04_refactoring/ — baseline, discovery, analysis, execution, hardening ├── 04_refactoring/NN-<run-name>/ — baseline_metrics, discovery, analysis, test_specs, execution_log, test_sync, verification, FINAL_report (one folder per refactor run)
├── 05_security/dependency scan, SAST, OWASP review, security report ├── 04_release/ release_<version>.md (one per /release invocation), rollback_<version>.md
── 06_metrics/ — retro_[YYYY-MM-DD].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 ## Standalone Mode
-105
View File
@@ -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
+4
View File
@@ -11,6 +11,7 @@ alwaysApply: true
- Avoid boilerplate and unnecessary indirection, but never sacrifice readability for brevity. - 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. - 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) - 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 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 - Do not put code annotations unless it was asked specifically
- Write code that takes into account the different environments: development, production - 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: - 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 - **Investigate and fix** the failing test or source code
- **Remove the test** if it is obsolete or no longer relevant - **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. - 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 - 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 - 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. - 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.
+6 -5
View File
@@ -19,7 +19,7 @@ globs: [".cursor/**"]
- Kebab-case filenames - Kebab-case filenames
## Agent Files (.cursor/agents/) ## 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 ## Security
- All `.cursor/` files must be scanned for hidden Unicode before committing (see cursor-security.mdc) - 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 | | 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 | | 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 | | 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.
+41
View File
@@ -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.
+20
View File
@@ -4,6 +4,26 @@ alwaysApply: true
--- ---
# Agent Meta Rules # 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 ## 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. - 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.
+9 -1
View File
@@ -8,8 +8,16 @@ globs: ["**/*test*", "**/*spec*", "**/*Test*", "**/tests/**", "**/test/**"]
- One assertion per test when practical; name tests descriptively: `MethodName_Scenario_ExpectedResult` - One assertion per test when practical; name tests descriptively: `MethodName_Scenario_ExpectedResult`
- Test boundary conditions, error paths, and happy paths - Test boundary conditions, error paths, and happy paths
- Use mocks only for external dependencies; prefer real implementations for internal code - 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) - 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 - Never use Thread Sleep or fixed delays in tests; use polling or async waits
- Keep test data factories/builders for reusable test setup - Keep test data factories/builders for reusable test setup
- Tests must be independent: no shared mutable state between tests - 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).
+6 -3
View File
@@ -14,11 +14,14 @@ alwaysApply: true
- Issue types: Epic, Story, Task, Bug, Subtask - Issue types: Epic, Story, Task, Bug, Subtask
## Tracker Availability Gate ## 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: - 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. - **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. - 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) ## Leftovers Mechanism (non-user-input blockers only)
+6 -5
View File
@@ -1,9 +1,9 @@
--- ---
name: autodev name: autodev
description: | description: |
Auto-chaining orchestrator that drives the full BUILD-SHIP workflow from problem gathering through deployment. Auto-chaining orchestrator that drives the full BUILDSHIP → 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 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. Maximizes work per conversation by auto-transitioning between skills.
Trigger phrases: Trigger phrases:
- "autodev", "auto", "start", "continue" - "autodev", "auto", "start", "continue"
@@ -15,7 +15,7 @@ disable-model-invocation: true
# Autodev Orchestrator # 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 ## 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. B4. Read File Index — `state.md`, `protocols.md`, and the active flow file.
### Resolve (once per invocation, after Bootstrap) ### Resolve (once per invocation, after Bootstrap)
R1. Reconcile state — verify state file against `_docs/` contents; on disagreement, trust the folders R1. Reconcile state — verify state file against `_docs/` contents; probe `<workspace-root>/../docs`
and update the state file (rules: `state.md` → "State File Rules" #4). (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. After this step, `state.step` / `state.status` are authoritative.
R2. Resolve flow — see §Flow Resolution above. R2. Resolve flow — see §Flow Resolution above.
R3. Resolve current step — when a state file exists, `state.step` drives detection. R3. Resolve current step — when a state file exists, `state.step` drives detection.
+39 -9
View File
@@ -3,7 +3,7 @@
Workflow for projects with an existing codebase. Structurally it has **two phases**: Workflow for projects with an existing codebase. Structurally it has **two phases**:
- **Phase A — One-time baseline setup (Steps 18)**: 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 A — One-time baseline setup (Steps 18)**: 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 917, 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 917, 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. 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 15 (optional) | | 14 | Security Audit | security/SKILL.md | Phase 15 (optional) |
| 15 | Performance Test | test-run/SKILL.md (perf mode) | Steps 15 (optional) | | 15 | Performance Test | test-run/SKILL.md (perf mode) | Steps 15 (optional) |
| 16 | Deploy | deploy/SKILL.md | Step 17 | | 16 | Deploy | deploy/SKILL.md | Step 17 |
| 16.5 | Release | release/SKILL.md | Phase 16 |
| 17 | Retrospective | retrospective/SKILL.md (cycle-end mode) | Steps 14 | | 17 | Retrospective | retrospective/SKILL.md (cycle-end mode) | Steps 14 |
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. 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`. 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** **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** **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: 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`. 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 ## 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) | | Update Docs (13) | Auto-chain → Security Audit choice (14) |
| Security Audit (14, done or skipped) | Auto-chain → Performance Test choice (15) | | Security Audit (14, done or skipped) | Auto-chain → Performance Test choice (15) |
| Performance Test (15, done or skipped) | Auto-chain → Deploy (16) | | Performance Test (15, done or skipped) | Auto-chain → Deploy (16) |
| Deploy (16) | Auto-chain → Retrospective (17) | | Deploy (16) | Auto-chain → Release (16.5) |
| Retrospective (17) | **Cycle complete** — loop back to New Task (9) with incremented cycle counter | | 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 ## Status Summary — Step List
@@ -381,6 +409,7 @@ Flow-specific slot values:
| 14 | Security Audit | — | | 14 | Security Audit | — |
| 15 | Performance Test | — | | 15 | Performance Test | — |
| 16 | Deploy | — | | 16 | Deploy | — |
| 16.5 | Release | `DONE (Released | Released-with-override | Rolled-Back | Aborted)` |
| 17 | Retrospective | — | | 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`. 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 14 Security Audit [<state token>]
Step 15 Performance Test [<state token>] Step 15 Performance Test [<state token>]
Step 16 Deploy [<state token>] Step 16 Deploy [<state token>]
Step 16.5 Release [<state token>]
Step 17 Retrospective [<state token>] Step 17 Retrospective [<state token>]
``` ```
+35 -7
View File
@@ -1,6 +1,6 @@
# Greenfield Workflow # 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 ## Step Reference Table
@@ -8,7 +8,7 @@ Workflow for new projects built from scratch. Flows linearly: Problem → Resear
|------|------|-----------|-------------------| |------|------|-----------|-------------------|
| 1 | Problem | problem/SKILL.md | Phase 14 | | 1 | Problem | problem/SKILL.md | Phase 14 |
| 2 | Research | research/SKILL.md | Mode A: Phase 14 · Mode B: Step 08 | | 2 | Research | research/SKILL.md | Mode A: Phase 14 · Mode B: Step 08 |
| 3 | Plan | plan/SKILL.md | Step 16 + 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 08 (conditional — UI projects only) | | 4 | UI Design | ui-design/SKILL.md | Phase 08 (conditional — UI projects only) |
| 5 | Test Spec | test-spec/SKILL.md | Phases 14 | | 5 | Test Spec | test-spec/SKILL.md | Phases 14 |
| 6 | Decompose | decompose/SKILL.md (implementation task decomposition) | Step 1 + Step 1.5 + Step 2 + Step 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 15 (optional) | | 14 | Security Audit | security/SKILL.md | Phase 15 (optional) |
| 15 | Performance Test | test-run/SKILL.md (perf mode) | Steps 15 (optional) | | 15 | Performance Test | test-run/SKILL.md (perf mode) | Steps 15 (optional) |
| 16 | Deploy | deploy/SKILL.md | Step 17 | | 16 | Deploy | deploy/SKILL.md | Step 17 |
| 16.5 | Release | release/SKILL.md | Phase 16 |
| 17 | Retrospective | retrospective/SKILL.md (cycle-end mode) | Steps 14 | | 17 | Retrospective | retrospective/SKILL.md (cycle-end mode) | Steps 14 |
## Detection Rules ## 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`. 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** **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. After retrospective completes, mark Step 17 as `completed` and enter "Done" evaluation.
--- ---
**Done** **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: 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) | | Update Docs (13, done or skipped) | Auto-chain → Security Audit choice (14) |
| Security Audit (14, done or skipped) | Auto-chain → Performance Test choice (15) | | Security Audit (14, done or skipped) | Auto-chain → Performance Test choice (15) |
| Performance Test (15, done or skipped) | Auto-chain → Deploy (16) | | 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 | | Retrospective (17) | Report completion; rewrite state to existing-code flow, step 9 |
## Status Summary — Step List ## Status Summary — Step List
@@ -362,6 +388,7 @@ Flow name: `greenfield`. Render using the banner template in `protocols.md` →
| 14 | Security Audit | — | | 14 | Security Audit | — |
| 15 | Performance Test | — | | 15 | Performance Test | — |
| 16 | Deploy | — | | 16 | Deploy | — |
| 16.5 | Release | `DONE (Released | Released-with-override | Rolled-Back | Aborted)` |
| 17 | Retrospective | — | | 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`. 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 14 Security Audit [<state token>]
Step 15 Performance Test [<state token>] Step 15 Performance Test [<state token>]
Step 16 Deploy [<state token>] Step 16 Deploy [<state token>]
Step 16.5 Release [<state token>]
Step 17 Retrospective [<state token>] Step 17 Retrospective [<state token>]
``` ```
+158 -13
View File
@@ -5,7 +5,8 @@ Workflow for **meta-repositories** — repos that aggregate multiple components
This flow differs fundamentally from `greenfield` and `existing-code`: 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 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 - **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 - **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 | Config Review | (human checkpoint, no sub-skill) | — |
| 2.5 | Glossary & Architecture Vision | (inline, no sub-skill) | Steps 15 | | 2.5 | Glossary & Architecture Vision | (inline, no sub-skill) | Steps 15 |
| 3 | Status | monorepo-status/SKILL.md | Sections 15 | | 3 | Status | monorepo-status/SKILL.md | Sections 15 |
| 3.5 | Suite Implement | implement/SKILL.md (suite-level invocation context) | Steps 114 + 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 17 (conditional on doc drift) | | 4 | Document Sync | monorepo-document/SKILL.md | Phase 17 (conditional on doc drift) |
| 4.5 | Integration Test Sync | monorepo-e2e/SKILL.md | Phase 16 (conditional on suite-e2e drift; skipped if `suite_e2e:` block absent in config) | | 4.5 | Integration Test Sync | monorepo-e2e/SKILL.md | Phase 16 (conditional on suite-e2e drift; skipped if `suite_e2e:` block absent in config) |
| 5 | CICD Sync | monorepo-cicd/SKILL.md | Phase 17 (conditional on CI drift) | | 5 | CICD Sync | monorepo-cicd/SKILL.md | Phase 17 (conditional on CI drift) |
@@ -184,11 +186,16 @@ The status report identifies:
- Registry/config mismatches - Registry/config mismatches
- Unresolved questions - 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)** 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.
- Else if **CI drift** (only) found → auto-chain to **Step 5 (CICD Sync)** 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 36 below to the post-implementation state.
- Else if **registry mismatch** found (new components not in config) → present Choose format: 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 (114, 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 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 | | Config Review (2, user picked B) | **Session boundary** — end session, await re-invocation |
| Glossary & Architecture Vision (2.5) | Auto-chain → Status (3) | | Glossary & Architecture Vision (2.5) | Auto-chain → Status (3) |
| Status (3, doc drift) | Auto-chain → Document Sync (4) | | Status (3, todo tasks present) | Auto-chain → Suite Implement (3.5) — pre-routing gate fires before drift-based routing |
| Status (3, suite-e2e drift only) | Auto-chain → Integration Test Sync (4.5) | | Status (3, no todo tasks, doc drift) | Auto-chain → Document Sync (4) |
| Status (3, CI drift only) | Auto-chain → CICD Sync (5) | | Status (3, no todo tasks, suite-e2e drift only) | Auto-chain → Integration Test Sync (4.5) |
| Status (3, no drift) | **Cycle complete** — end session, await re-invocation | | 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) | | 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) + 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) + CI drift only pending | Auto-chain → CICD Sync (5) |
| Document Sync (4) + no further drift | **Cycle complete** | | Document Sync (4) + no further drift | **Cycle complete** |
@@ -317,11 +456,12 @@ Flow-specific slot values:
| 2 | Config Review | `IN PROGRESS (awaiting human)` | | 2 | Config Review | `IN PROGRESS (awaiting human)` |
| 2.5 | Glossary & Architecture Vision | `SKIPPED (already captured)` | | 2.5 | Glossary & Architecture Vision | `SKIPPED (already captured)` |
| 3 | Status | `DONE (no drift)`, `DONE (N drifts)` | | 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 | 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)` | | 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)` | | 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: Row rendering format:
@@ -330,6 +470,7 @@ Row rendering format:
Step 2 Config Review [<state token>] Step 2 Config Review [<state token>]
Step 2.5 Glossary & Architecture Vision [<state token>] Step 2.5 Glossary & Architecture Vision [<state token>]
Step 3 Status [<state token>] Step 3 Status [<state token>]
Step 3.5 Suite Implement [<state token>]
Step 4 Document Sync [<state token>] Step 4 Document Sync [<state token>]
Step 4.5 Integration Test Sync [<state token>] Step 4.5 Integration Test Sync [<state token>]
Step 5 CICD Sync [<state token>] Step 5 CICD Sync [<state token>]
@@ -337,8 +478,12 @@ Row rendering format:
## Notes for the meta-repo flow ## 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. - **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. - **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`). - **Failure handling**: uses the same retry/escalation protocol as other flows (see `protocols.md`).
+2 -1
View File
@@ -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 | | 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 | 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 | | 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 ### 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. 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. - `<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. - `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) ### State token set (shared)
+15 -2
View File
@@ -13,7 +13,7 @@ The autodev persists its position to `_docs/_autodev_state.md`. This is a lightw
## Current Step ## Current Step
flow: [greenfield | existing-code | meta-repo] 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] name: [step name from the active flow's Step Reference Table]
status: [not_started / in_progress / completed / skipped / failed] status: [not_started / in_progress / completed / skipped / failed]
sub_step: sub_step:
@@ -82,6 +82,19 @@ retry_count: 0
cycle: 1 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 flow: existing-code
step: 10 step: 10
@@ -100,7 +113,7 @@ cycle: 3
1. **Create** on the first autodev invocation (after state detection determines Step 1) 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. 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 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 directorys `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 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` 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 7. **Failed state on re-entry**: if `status: failed` with `retry_count: 3`, do NOT auto-retry — present the issue to the user first
+10 -4
View File
@@ -2,7 +2,7 @@
name: code-review name: code-review
description: | description: |
Multi-phase code review against task specs with structured findings output. 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. 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. Invoked by /implement skill after each batch, or manually.
Trigger phrases: Trigger phrases:
@@ -106,11 +106,12 @@ When multiple tasks were implemented in the same batch:
## Phase 7: Architecture Compliance ## 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**: **Inputs**:
- `_docs/02_document/architecture.md` — layering, allowed dependencies, patterns - `_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/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) - The cumulative list of changed files (for per-batch invocation) or the full codebase (for baseline invocation)
**Checks**: **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. 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)**: **Detection approach (per language)**:
- Python: parse `import` / `from ... import` statements; optionally AST with `ast` module for reliable symbol resolution. - 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 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 ## Verdict Logic
@@ -232,7 +238,7 @@ The implement skill invokes code-review by:
1. Reading `.cursor/skills/code-review/SKILL.md` 1. Reading `.cursor/skills/code-review/SKILL.md`
2. Providing the inputs above as context (read the files, pass content to the review phases) 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 4. Consuming the verdict from the output
### Outputs (returned to the implement skill) ### Outputs (returned to the implement skill)
+17
View File
@@ -65,6 +65,7 @@ Announce the selected entrypoint and resolved paths to the user before proceedin
| 1 Bootstrap Structure | `steps/01_bootstrap-structure.md` | ✓ | — | — | | 1 Bootstrap Structure | `steps/01_bootstrap-structure.md` | ✓ | — | — |
| 1t Test Infrastructure | `steps/01t_test-infrastructure.md` | — | — | ✓ | | 1t Test Infrastructure | `steps/01t_test-infrastructure.md` | — | — | ✓ |
| 1.5 Module Layout | `steps/01-5_module-layout.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` | ✓ | ✓ | — | | 2 Task Decomposition | `steps/02_task-decomposition.md` | ✓ | ✓ | — |
| 3 Blackbox Test Tasks | `steps/03_blackbox-test-decomposition.md` | — | — | ✓ | | 3 Blackbox Test Tasks | `steps/03_blackbox-test-decomposition.md` | — | — | ✓ |
| 4 Cross-Verification | `steps/04_cross-verification.md` | ✓ | — | ✓ | | 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) ### Step 2: Task Decomposition (implementation and single component modes)
Read and follow `steps/02_task-decomposition.md`. Read and follow `steps/02_task-decomposition.md`.
@@ -243,6 +258,8 @@ Read and follow `steps/04_cross-verification.md`.
│ [BLOCKING: user confirms structure] │ │ [BLOCKING: user confirms structure] │
│ 1.5 Module Layout → steps/01-5_module-layout.md │ │ 1.5 Module Layout → steps/01-5_module-layout.md │
│ [BLOCKING: user confirms layout] │ │ [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 │ │ 2. Component Tasks → steps/02_task-decomposition.md │
│ 4. Cross-Verification → steps/04_cross-verification.md │ │ 4. Cross-Verification → steps/04_cross-verification.md │
│ [BLOCKING: user confirms dependencies] │ │ [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). 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. 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). 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 ## Self-verification
@@ -26,6 +27,8 @@
- [ ] No component's `Imports from` list points at a higher layer - [ ] No component's `Imports from` list points at a higher layer
- [ ] Paths follow the detected language's convention - [ ] Paths follow the detected language's convention
- [ ] No two components own overlapping paths - [ ] 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 ## 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 ### Test
- Unit tests: [framework and command] - Unit tests: [framework and command]
- Blackbox tests: [framework and command, uses docker-compose.test.yml] - 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 - Coverage report published as pipeline artifact
### Security ### Security
+57 -6
View File
@@ -64,6 +64,27 @@ TASKS_DIR/
└── done/ ← completed tasks (moved here after implementation) └── 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 (114, 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) ## Prerequisite Checks (BLOCKING)
1. `TASKS_DIR/todo/` exists and contains at least one task file for the selected context — **STOP if missing** 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 ### 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: For each task in the batch:
- Read the task spec's **Component** field. - 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) ### 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) - **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 - **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) - **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 ### 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. **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. - **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. - **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 18) 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: Save the audit to `_docs/03_implementation/implementation_completeness_cycle[N]_report.md` with:
- Per-task classification - Per-task classification
- Evidence files/symbols checked - Evidence files/symbols checked
- Any unresolved scaffold/native placeholders - Any unresolved scaffold/native placeholders
- Any named promised technologies not integrated - 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 - Required remediation task suggestions, each sized to 5 points or less
Gate: Gate:
- If every product task is `PASS` or `BLOCKED` with explicit prerequisite evidence, continue to Final Test Run. - 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`, 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: - 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 - 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 - B) Mark the missing behavior explicitly out of scope in task/docs, then re-run this gate
- C) Abort for manual correction - C) Abort for manual correction
- Recommendation must normally be A unless the user deliberately accepts reduced scope. - 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` - **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`. - **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` - **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). 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).
+53 -7
View File
@@ -84,14 +84,46 @@ Assess the change along these dimensions:
- **Novelty**: does it involve libraries, protocols, or patterns not already in the codebase? - **Novelty**: does it involve libraries, protocols, or patterns not already in the codebase?
- **Risk**: could it break existing functionality or require architectural changes? - **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 23 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 | **12** | 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 23 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 |
|----------|-----------------|---------------|
| **15** | 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 | | 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) | | **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] Scope: [low / medium / high]
Novelty: [low / medium / high] Novelty: [low / medium / high]
Risk: [low / medium / high] Risk: [low / medium / high]
Points: [1 / 2 / 3 / 5 / 8 / 13] (project aim: 23, rarely 5)
Routing: [Continue in /new-task | Hand off to /decompose]
══════════════════════════════════════ ══════════════════════════════════════
Recommendation: [Research needed / Skip research] Recommendation: [Research needed | Skip research | Decompose required]
Reason: [one-line justification] 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. 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. 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. **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 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 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 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 -3
View File
@@ -15,7 +15,7 @@ disable-model-invocation: true
# Solution Planning # 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 ## Core Principles
@@ -55,7 +55,7 @@ Read `steps/01_artifact-management.md` for directory structure, save timing, sav
## Progress Tracking ## 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 ## 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 24 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 ### Step 5: Test Specifications
Read and follow `steps/05_test-specifications.md`. 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 | | Missing acceptance_criteria.md, restrictions.md, or input_data/ | **STOP** — planning cannot proceed |
| Ambiguous requirements | ASK user | | 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 | | Technology choice with multiple valid options | ASK user |
| Component naming | PROCEED, confirm at next BLOCKING gate | | Component naming | PROCEED, confirm at next BLOCKING gate |
| File structure within templates | PROCEED | | File structure within templates | PROCEED |
@@ -146,6 +156,8 @@ Read and follow `steps/07_quality-checklist.md`.
│ [BLOCKING: user confirms components] │ │ [BLOCKING: user confirms components] │
│ 4. Review & Risk → risk register, iterations │ │ 4. Review & Risk → risk register, iterations │
│ [BLOCKING: user confirms mitigations] │ │ [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 │ │ 5. Test Specifications → per-component test specs │
│ 6. Work Item Epics → epic per component + bootstrap │ │ 6. Work Item Epics → epic per component + bootstrap │
│ ───────────────────────────────────────────────── │ │ ───────────────────────────────────────────────── │
@@ -26,6 +26,10 @@ DOCUMENT_DIR/
│ └── deployment_procedures.md │ └── deployment_procedures.md
├── risk_mitigations.md ├── risk_mitigations.md
├── risk_mitigations_02.md (iterative, ## as sequence) ├── risk_mitigations_02.md (iterative, ## as sequence)
├── adr/
│ ├── 001_[decision_slug].md
│ ├── 002_[decision_slug].md
│ └── ...
├── components/ ├── components/
│ ├── 01_[name]/ │ ├── 01_[name]/
│ │ ├── description.md │ │ ├── description.md
@@ -66,6 +70,8 @@ DOCUMENT_DIR/
| Step 3 | Common helpers generated | `common-helpers/[##]_helper_[name].md` | | Step 3 | Common helpers generated | `common-helpers/[##]_helper_[name].md` |
| Step 3 | Diagrams generated | `diagrams/` | | Step 3 | Diagrams generated | `diagrams/` |
| Step 4 | Risk assessment complete | `risk_mitigations.md` | | 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 5 | Tests written per component | `components/[##]_[name]/tests.md` |
| Step 6 | Epics created in work item tracker | Tracker via MCP | | Step 6 | Epics created in work item tracker | Tracker via MCP |
| Final | All steps complete | `FINAL_report.md` | | 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 2. Identify the last completed step based on which artifacts exist
3. Resume from the next incomplete step 3. Resume from the next incomplete step
4. Inform the user which steps are being skipped 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 24 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.5a4.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". 515 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 **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. **Constraints**: Test specs only — no test code. Each test must trace to an acceptance criterion.
+67
View File
@@ -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 (36 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 13 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 # 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 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 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: 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 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 ## 2c. Create Epic
Create a work item tracker epic for this refactoring run: 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) - [ ] Task dependencies are consistent (no circular dependencies)
- [ ] `_dependencies_table.md` includes all refactoring tasks - [ ] `_dependencies_table.md` includes all refactoring tasks
- [ ] Every task has a work item ticket (or PENDING placeholder) - [ ] 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 **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) 1. Scan the project for existing test files (unit tests, integration tests, blackbox tests)
2. Run the existing test suite — record pass/fail counts 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) 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% - 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 public APIs must have blackbox tests
- All error handling paths must be tested - 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 4. Document any discovered issues
**Self-verification**: **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 tests pass on current codebase
- [ ] All public APIs in refactoring scope have blackbox tests - [ ] All public APIs in refactoring scope have blackbox tests
- [ ] Test data fixtures are configured - [ ] Test data fixtures are configured
@@ -45,7 +45,7 @@ Write `RUN_DIR/test_sync/new_tests.md`:
- [ ] All obsolete tests removed or merged - [ ] All obsolete tests removed or merged
- [ ] All pre-existing tests pass after updates - [ ] All pre-existing tests pass after updates
- [ ] New code from Phase 4 has test coverage - [ ] 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 - [ ] No tests reference removed or renamed code
**Save action**: Write test_sync artifacts; implemented tests go into the project's test folder **Save action**: Write test_sync artifacts; implemented tests go into the project's test folder
+290
View File
@@ -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 560 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}
+4 -4
View File
@@ -2,9 +2,9 @@
name: retrospective name: retrospective
description: | description: |
Collect metrics from implementation batch reports and code review findings, analyze trends across cycles, Collect metrics from implementation batch reports and code review findings, analyze trends across cycles,
and produce improvement reports with actionable recommendations. and produce improvement reports plus a lessons-log update with actionable recommendations.
3-step workflow: collect metrics, analyze trends, produce report. 4-step workflow: collect metrics, analyze trends, produce report, update lessons log.
Outputs to _docs/06_metrics/. Outputs to _docs/06_metrics/ and appends to _docs/LESSONS.md (ring buffer, last 15).
Trigger phrases: Trigger phrases:
- "retrospective", "retro", "run retro" - "retrospective", "retro", "run retro"
- "metrics review", "feedback loop" - "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/ │ │ PREREQ: batch reports exist in _docs/03_implementation/ │
│ │ │ │
+4 -3
View File
@@ -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 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 | | Missing input_data/expected_results/results_report.md | **STOP** — ask user to provide expected results mapping using the template |
| Ambiguous requirements | ASK user | | 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 | | 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 | | Test scenario conflicts with restrictions | ASK user to clarify intent |
| System interfaces unclear (no architecture.md) | ASK user or derive from solution.md | | 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 | | 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 ## Common Mistakes
@@ -252,7 +252,8 @@ When the user wants to:
│ │ │ │
│ Phase 3: Test Data & Expected Results Validation Gate (HARD GATE) │ │ Phase 3: Test Data & Expected Results Validation Gate (HARD GATE) │
│ → phases/03-data-validation-gate.md │ │ → 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) │ │ Hardware-Dependency Assessment (BLOCKING, pre-Phase-4) │
│ → phases/hardware-assessment.md │ │ → phases/hardware-assessment.md │
@@ -1,7 +1,7 @@
# Phase 3: Test Data & Expected Results Validation Gate (HARD GATE) # Phase 3: Test Data & Expected Results Validation Gate (HARD GATE)
**Role**: Professional Quality Assurance Engineer **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. **Constraints**: This phase is MANDATORY and cannot be skipped.
## Step 1 — Build the requirements checklist ## Step 1 — Build the requirements checklist
+42
View File
@@ -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
+35
View File
@@ -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
+7
View File
@@ -11,3 +11,10 @@ Content/
tiles/ tiles/
ready/ ready/
.DS_Store .DS_Store
TestResults/
coverage.cobertura.xml
coverage.opencover.xml
*.coverage
_docs/03_implementation/test_runs/
_docs/04_run_results/
certs/
+35
View File
@@ -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"
}
]
}
+41
View File
@@ -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"
}
]
}
+1 -1
View File
@@ -7,7 +7,7 @@ labels:
steps: steps:
- name: unit-tests - name: unit-tests
image: mcr.microsoft.com/dotnet/sdk:8.0 image: mcr.microsoft.com/dotnet/sdk:10.0
commands: commands:
- dotnet restore SatelliteProvider.sln - 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 - 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
+8 -6
View File
@@ -2,11 +2,11 @@
## System Overview ## 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 ## Tech Stack
- **.NET 8.0** with ASP.NET Core Web API - **.NET 10** with ASP.NET Core Web API
- **PostgreSQL** database (via Docker) - **PostgreSQL** database (via Docker)
- **Dapper** for data access (ORM) - **Dapper** for data access (ORM)
- **DbUp** for database migrations - **DbUp** for database migrations
@@ -177,7 +177,7 @@ docker-compose -f docker-compose.yml -f docker-compose.tests.yml up --build --ab
### Configuration Values ### Configuration Values
Development defaults: 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 - API: http://localhost:5100
- Max zoom level: 20 - Max zoom level: 20
- Default zoom level: 18 - Default zoom level: 18
@@ -236,10 +236,12 @@ Development defaults:
## Dependencies and Versions ## Dependencies and Versions
Key packages (all .NET 8.0): Key packages (all .NET 10):
- Microsoft.AspNetCore.OpenApi 8.0.21 - Microsoft.AspNetCore.OpenApi 10.0.7
- Microsoft.AspNetCore.Authentication.JwtBearer 10.0.7
- Microsoft.Extensions.* 10.0.7
- Swashbuckle.AspNetCore 6.6.2 - 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 - SixLabors.ImageSharp 3.1.11
- Newtonsoft.Json 13.0.4 - Newtonsoft.Json 13.0.4
- Dapper (check DataAccess csproj) - Dapper (check DataAccess csproj)
+10
View File
@@ -0,0 +1,10 @@
<Project>
<PropertyGroup>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisLevel>latest</AnalysisLevel>
<AnalysisMode>None</AnalysisMode>
<EnforceCodeStyleInBuild>false</EnforceCodeStyleInBuild>
</PropertyGroup>
</Project>
+2 -2
View File
@@ -73,7 +73,7 @@ The service follows a layered architecture:
### Download Single Tile ### Download Single Tile
```http ```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. 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 ### Service won't start
- Check Docker is running - 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` - Check logs: `docker-compose logs api`
### Tiles not downloading ### 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; }
}
+2 -2
View File
@@ -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 WORKDIR /app
EXPOSE 8080 EXPOSE 8080
EXPOSE 8081 EXPOSE 8081
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src WORKDIR /src
COPY ["SatelliteProvider.Api/SatelliteProvider.Api.csproj", "SatelliteProvider.Api/"] COPY ["SatelliteProvider.Api/SatelliteProvider.Api.csproj", "SatelliteProvider.Api/"]
COPY ["SatelliteProvider.Common/SatelliteProvider.Common.csproj", "SatelliteProvider.Common/"] COPY ["SatelliteProvider.Common/SatelliteProvider.Common.csproj", "SatelliteProvider.Common/"]
@@ -1,3 +1,4 @@
using System.Text.Json;
using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@@ -60,6 +61,30 @@ public sealed class GlobalExceptionHandler : IExceptionHandler
{ {
httpContext.Response.StatusCode = badRequest.StatusCode; 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 var problem = new ProblemDetails
{ {
Status = badRequest.StatusCode, Status = badRequest.StatusCode,
@@ -73,4 +98,36 @@ public sealed class GlobalExceptionHandler : IExceptionHandler
contentType: "application/problem+json", contentType: "application/problem+json",
cancellationToken: cancellationToken); 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
View File
@@ -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.AspNetCore.Mvc;
using Microsoft.OpenApi.Models; using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.OpenApi;
using Swashbuckle.AspNetCore.SwaggerGen; using Swashbuckle.AspNetCore.SwaggerGen;
using SatelliteProvider.Api; 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;
using SatelliteProvider.DataAccess.Repositories; using SatelliteProvider.DataAccess.Repositories;
using SatelliteProvider.DataAccess.TypeHandlers;
using SatelliteProvider.Common.Configs; using SatelliteProvider.Common.Configs;
using SatelliteProvider.Common.DTO; using SatelliteProvider.Common.DTO;
using SatelliteProvider.Common.Interfaces; using SatelliteProvider.Common.Interfaces;
@@ -21,13 +29,41 @@ builder.Host.UseSerilog((context, configuration) =>
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") var connectionString = builder.Configuration.GetConnectionString("DefaultConnection")
?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
DapperEnumTypeHandlers.RegisterAll();
builder.Services.Configure<MapConfig>(builder.Configuration.GetSection("MapConfig")); builder.Services.Configure<MapConfig>(builder.Configuration.GetSection("MapConfig"));
builder.Services.Configure<StorageConfig>(builder.Configuration.GetSection("StorageConfig")); builder.Services.Configure<StorageConfig>(builder.Configuration.GetSection("StorageConfig"));
builder.Services.Configure<ProcessingConfig>(builder.Configuration.GetSection("ProcessingConfig")); 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<ITileRepository>(sp => new TileRepository(connectionString, sp.GetRequiredService<ILogger<TileRepository>>()));
builder.Services.AddSingleton<IRegionRepository>(sp => new RegionRepository(connectionString, sp.GetRequiredService<ILogger<RegionRepository>>())); builder.Services.AddSingleton<IRegionRepository>(sp => new RegionRepository(connectionString));
builder.Services.AddSingleton<IRouteRepository>(sp => new RouteRepository(connectionString, sp.GetRequiredService<ILogger<RouteRepository>>())); builder.Services.AddSingleton<IRouteRepository>(sp => new RouteRepository(connectionString));
builder.Services.AddHttpClient(); builder.Services.AddHttpClient();
@@ -35,6 +71,17 @@ builder.Services.AddTileDownloader();
builder.Services.AddRegionProcessing(); builder.Services.AddRegionProcessing();
builder.Services.AddRouteManagement(); 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 allowedOrigins = builder.Configuration.GetSection("CorsConfig:AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();
var allowAnyOrigin = builder.Configuration.GetValue<bool>("CorsConfig:AllowAnyOrigin"); var allowAnyOrigin = builder.Configuration.GetValue<bool>("CorsConfig:AllowAnyOrigin");
CorsConfigurationValidator.EnsureSafeForEnvironment(allowedOrigins, allowAnyOrigin, builder.Environment.EnvironmentName); CorsConfigurationValidator.EnsureSafeForEnvironment(allowedOrigins, allowAnyOrigin, builder.Environment.EnvironmentName);
@@ -53,32 +100,74 @@ builder.Services.AddCors(options =>
builder.Services.AddProblemDetails(); builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>(); 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 => builder.Services.ConfigureHttpJsonOptions(options =>
{ {
options.SerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase; options.SerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
options.SerializerOptions.PropertyNameCaseInsensitive = true; 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.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c => builder.Services.AddSwaggerGen(c =>
{ {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Satellite Provider API", Version = "v1" }); c.SwaggerDoc("v1", new OpenApiInfo { Title = "Satellite Provider API", Version = "v1" });
c.MapType<UploadImageRequest>(() => new OpenApiSchema c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{ {
Type = "object", Name = "Authorization",
Properties = new Dictionary<string, OpenApiSchema> 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" }, new OpenApiSecuritySchemeReference("Bearer"),
["lat"] = new() { Type = "number", Format = "double", Description = "Latitude coordinate where image was captured" }, new List<string>()
["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" }, c.MapType<UavTileBatchUploadRequest>(() => new OpenApiSchema
["sensorHeight"] = new() { Type = "number", Format = "double", Description = "Camera sensor height in millimeters" } {
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>(); c.OperationFilter<ParameterDescriptionFilter>();
@@ -113,41 +202,81 @@ if (app.Environment.IsDevelopment())
app.UseExceptionHandler(); app.UseExceptionHandler();
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseCors("TilesCors"); app.UseCors("TilesCors");
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/tiles/{z:int}/{x:int}/{y:int}", ServeTile) 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)" }); .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) 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" }); .WithOpenApi(op => new(op) { Summary = "Get satellite tile by latitude and longitude coordinates" });
app.MapGet("/api/satellite/tiles/mgrs", GetSatelliteTilesByMgrs) app.MapGet("/api/satellite/tiles/mgrs", GetSatelliteTilesByMgrs)
.RequireAuthorization()
.ProducesProblem(StatusCodes.Status501NotImplemented) .ProducesProblem(StatusCodes.Status501NotImplemented)
.WithOpenApi(op => new(op) { Summary = "Get satellite tiles by MGRS coordinates (NOT IMPLEMENTED)" }); .WithOpenApi(op => new(op) { Summary = "Get satellite tiles by MGRS coordinates (NOT IMPLEMENTED)" });
app.MapPost("/api/satellite/upload", UploadImage) app.MapPost("/api/satellite/tiles/inventory", GetTilesInventory)
.Accepts<UploadImageRequest>("multipart/form-data") .RequireAuthorization()
.ProducesProblem(StatusCodes.Status501NotImplemented) .WithValidation<TileInventoryRequest>()
.WithOpenApi(op => new(op) { Summary = "Upload image with metadata (NOT IMPLEMENTED)" }) .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(); .DisableAntiforgery();
app.MapPost("/api/satellite/request", RequestRegion) app.MapPost("/api/satellite/request", RequestRegion)
.RequireAuthorization()
.WithValidation<RequestRegionRequest>()
.Accepts<RequestRegionRequest>("application/json")
.Produces<RegionStatusResponse>(StatusCodes.Status200OK)
.ProducesProblem(StatusCodes.Status400BadRequest)
.WithOpenApi(op => new(op) .WithOpenApi(op => new(op)
{ {
Summary = "Request tiles for a region", 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) app.MapGet("/api/satellite/region/{id:guid}", GetRegionStatus)
.RequireAuthorization()
.WithOpenApi(op => new(op) { Summary = "Get region status and file paths" }); .WithOpenApi(op => new(op) { Summary = "Get region status and file paths" });
app.MapPost("/api/satellite/route", CreateRoute) app.MapPost("/api/satellite/route", CreateRoute)
.RequireAuthorization()
.WithValidation<CreateRouteRequest>()
.Accepts<CreateRouteRequest>("application/json")
.Produces<RouteResponse>(StatusCodes.Status200OK)
.ProducesProblem(StatusCodes.Status400BadRequest)
.WithOpenApi(op => new(op) .WithOpenApi(op => new(op)
{ {
Summary = "Create a route with intermediate points", 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) app.MapGet("/api/satellite/route/{id:guid}", GetRoute)
.RequireAuthorization()
.WithOpenApi(op => new(op) { Summary = "Get route information with calculated points" }); .WithOpenApi(op => new(op) { Summary = "Get route information with calculated points" });
app.Run(); 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); 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 var response = new DownloadTileResponse
{ {
@@ -173,7 +304,6 @@ async Task<IResult> GetTileByLatLon([FromQuery] double Latitude, [FromQuery] dou
TileSizeMeters = tile.TileSizeMeters, TileSizeMeters = tile.TileSizeMeters,
TileSizePixels = tile.TileSizePixels, TileSizePixels = tile.TileSizePixels,
ImageType = tile.ImageType, ImageType = tile.ImageType,
MapsVersion = tile.MapsVersion,
Version = tile.Version, Version = tile.Version,
FilePath = tile.FilePath, FilePath = tile.FilePath,
CreatedAt = tile.CreatedAt, CreatedAt = tile.CreatedAt,
@@ -191,25 +321,50 @@ IResult GetSatelliteTilesByMgrs(string mgrs, double squareSideMeters)
detail: "MGRS-based tile retrieval is not implemented."); 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( return Results.Problem(
statusCode: StatusCodes.Status501NotImplemented, statusCode: StatusCodes.Status400BadRequest,
title: "Not implemented", title: "Invalid UAV tile batch",
detail: "Image upload is not implemented."); detail: result.EnvelopeError);
}
return Results.Ok(result.Response);
} }
async Task<IResult> RequestRegion([FromBody] RequestRegionRequest request, IRegionService regionService) 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( var status = await regionService.RequestRegionAsync(
request.Id, request.Id,
request.Latitude, request.Lat,
request.Longitude, request.Lon,
request.SizeMeters, request.SizeMeters,
request.ZoomLevel, request.ZoomLevel,
request.StitchTiles); request.StitchTiles);
@@ -254,113 +409,3 @@ async Task<IResult> GetRoute(Guid id, IRouteService routeService)
return Results.Ok(route); 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"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <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="Newtonsoft.Json" Version="13.0.4" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" /> <PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" /> <PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.11" /> <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>
<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": { "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": { "MapConfig": {
"Service": "GoogleMaps", "Service": "GoogleMaps",
+24 -2
View File
@@ -23,9 +23,27 @@
"ConnectionStrings": { "ConnectionStrings": {
"DefaultConnection": "Host=localhost;Database=satelliteprovider;Username=postgres;Password=postgres" "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": { "MapConfig": {
"Service": "GoogleMaps", "Service": "GoogleMaps",
"ApiKey": "" "ApiKey": "",
"TileSizePixels": 256,
"AllowedZoomLevels": [ 15, 16, 17, 18, 19 ],
"RetryBaseDelaySeconds": 1,
"RetryMaxDelaySeconds": 30
}, },
"StorageConfig": { "StorageConfig": {
"TilesDirectory": "./tiles", "TilesDirectory": "./tiles",
@@ -37,7 +55,11 @@
"DefaultZoomLevel": 20, "DefaultZoomLevel": 20,
"QueueCapacity": 1000, "QueueCapacity": 1000,
"DelayBetweenRequestsMs": 50, "DelayBetweenRequestsMs": 50,
"SessionTokenReuseCount": 100 "SessionTokenReuseCount": 100,
"RegionProcessingTimeoutSeconds": 300,
"RouteProcessingPollIntervalSeconds": 5,
"MaxRoutePointSpacingMeters": 200.0,
"LatLonTolerance": 0.0001
}, },
"CorsConfig": { "CorsConfig": {
"AllowedOrigins": [] "AllowedOrigins": []
+11 -1
View File
@@ -1,7 +1,17 @@
namespace SatelliteProvider.Common.Configs; namespace SatelliteProvider.Common.Configs;
public class MapConfig public class MapConfig
{ {
public string Service { get; set; } = null!; public string Service { get; set; } = null!;
public string ApiKey { 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 QueueCapacity { get; set; } = 100;
public int DelayBetweenRequestsMs { get; set; } = 50; public int DelayBetweenRequestsMs { get; set; } = 50;
public int SessionTokenReuseCount { get; set; } = 100; 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 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; } public Guid Id { get; set; }
[JsonRequired]
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
public string? Description { get; set; } public string? Description { get; set; }
[JsonRequired]
public double RegionSizeMeters { get; set; } public double RegionSizeMeters { get; set; }
[JsonRequired]
public int ZoomLevel { get; set; } public int ZoomLevel { get; set; }
[JsonRequired]
public List<RoutePoint> Points { get; set; } = new(); public List<RoutePoint> Points { get; set; } = new();
[JsonPropertyName("geofences")] [JsonPropertyName("geofences")]
public Geofences? Geofences { get; set; } public Geofences? Geofences { get; set; }
public bool RequestMaps { get; set; } = false; [JsonRequired]
public bool CreateTilesZip { get; set; } = false; 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; }
}
+2
View File
@@ -6,9 +6,11 @@ public class GeoPoint
{ {
const double PRECISION_TOLERANCE = 0.00005; const double PRECISION_TOLERANCE = 0.00005;
[JsonRequired]
[JsonPropertyName("lat")] [JsonPropertyName("lat")]
public double Lat { get; set; } public double Lat { get; set; }
[JsonRequired]
[JsonPropertyName("lon")] [JsonPropertyName("lon")]
public double Lon { get; set; } public double Lon { get; set; }
@@ -4,15 +4,18 @@ namespace SatelliteProvider.Common.DTO;
public class GeofencePolygon public class GeofencePolygon
{ {
[JsonRequired]
[JsonPropertyName("northWest")] [JsonPropertyName("northWest")]
public GeoPoint? NorthWest { get; set; } public GeoPoint? NorthWest { get; set; }
[JsonRequired]
[JsonPropertyName("southEast")] [JsonPropertyName("southEast")]
public GeoPoint? SouthEast { get; set; } public GeoPoint? SouthEast { get; set; }
} }
public class Geofences public class Geofences
{ {
[JsonRequired]
[JsonPropertyName("polygons")] [JsonPropertyName("polygons")]
public List<GeofencePolygon> Polygons { get; set; } = new(); 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();
}
@@ -1,9 +1,11 @@
using SatelliteProvider.Common.Enums;
namespace SatelliteProvider.Common.DTO; namespace SatelliteProvider.Common.DTO;
public class RegionStatus public class RegionStatusResponse
{ {
public Guid Id { get; set; } public Guid Id { get; set; }
public string Status { get; set; } = string.Empty; public RegionStatus Status { get; set; }
public string? CsvFilePath { get; set; } public string? CsvFilePath { get; set; }
public string? SummaryFilePath { get; set; } public string? SummaryFilePath { get; set; }
public int TilesDownloaded { get; set; } public int TilesDownloaded { get; set; }
@@ -11,4 +13,3 @@ public class RegionStatus
public DateTime CreatedAt { get; set; } public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { 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 public class RoutePoint
{ {
[JsonRequired]
[JsonPropertyName("lat")] [JsonPropertyName("lat")]
public double Latitude { get; set; } public double Latitude { get; set; }
[JsonRequired]
[JsonPropertyName("lon")] [JsonPropertyName("lon")]
public double Longitude { get; set; } public double Longitude { get; set; }
} }
@@ -1,12 +1,13 @@
using SatelliteProvider.Common.Enums;
namespace SatelliteProvider.Common.DTO; namespace SatelliteProvider.Common.DTO;
public class RoutePointDto public class RoutePointDto
{ {
public double Latitude { get; set; } public double Latitude { get; set; }
public double Longitude { 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 SequenceNumber { get; set; }
public int SegmentIndex { get; set; } public int SegmentIndex { get; set; }
public double? DistanceFromPrevious { get; set; } public double? DistanceFromPrevious { get; set; }
} }
+1 -1
View File
@@ -1,4 +1,4 @@
using SatelliteProvider.Common.Utils; using SatelliteProvider.Common.Utils;
namespace SatelliteProvider.Common.DTO; 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 double TileSizeMeters { get; set; }
public int TileSizePixels { get; set; } public int TileSizePixels { get; set; }
public string ImageType { get; set; } = string.Empty; public string ImageType { get; set; } = string.Empty;
public string? MapsVersion { get; set; }
public int? Version { get; set; } public int? Version { get; set; }
public string FilePath { get; set; } = string.Empty; public string FilePath { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; } 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 public interface IRegionService
{ {
Task<RegionStatus> RequestRegionAsync(Guid id, double latitude, double longitude, double sizeMeters, int zoomLevel, bool stitchTiles = false); Task<RegionStatusResponse> RequestRegionAsync(Guid id, double latitude, double longitude, double sizeMeters, int zoomLevel, bool stitchTiles = false);
Task<RegionStatus?> GetRegionStatusAsync(Guid id); Task<RegionStatusResponse?> GetRegionStatusAsync(Guid id);
Task ProcessRegionAsync(Guid id, CancellationToken cancellationToken = default); 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<IEnumerable<TileMetadata>> GetTilesByRegionAsync(double latitude, double longitude, double sizeMeters, int zoomLevel);
Task<TileBytes> GetOrDownloadTileAsync(int z, int x, int y, CancellationToken cancellationToken = default); Task<TileBytes> GetOrDownloadTileAsync(int z, int x, int y, CancellationToken cancellationToken = default);
Task<TileMetadata> DownloadAndStoreSingleTileAsync(double latitude, double longitude, int zoomLevel, 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"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.11" />
</ItemGroup>
</Project> </Project>
+8 -11
View File
@@ -1,10 +1,12 @@
using SatelliteProvider.Common.DTO; using SatelliteProvider.Common.DTO;
namespace SatelliteProvider.Common.Utils; namespace SatelliteProvider.Common.Utils;
public static class GeoUtils 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) 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.Cos(lat1Rad) * Math.Cos(lat2Rad) *
Math.Sin(dLon / 2) * Math.Sin(dLon / 2); Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
var c = 2 * Math.Asin(Math.Sqrt(a)); 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 y = Math.Sin(dLon) * Math.Cos(lat2Rad);
var x = Math.Cos(lat1Rad) * Math.Sin(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) 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 azimuthRadians = ToRadians(direction.Azimuth);
var startLatRad = ToRadians(startPoint.Lat); var startLatRad = ToRadians(startPoint.Lat);
var startLonRad = ToRadians(startPoint.Lon); var startLonRad = ToRadians(startPoint.Lon);
@@ -73,11 +75,11 @@ public static class GeoUtils
{ {
var latRad = centerGeoPoint.Lat * Math.PI / 180.0; 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 minLat = Math.Max(centerGeoPoint.Lat - latDiff, -90.0);
var maxLat = Math.Min(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 minLon = Math.Max(centerGeoPoint.Lon - lonDiff, -180.0);
var maxLon = Math.Min(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; var centerLon = (northWest.Lon + southEast.Lon) / 2.0;
return new GeoPoint(centerLat, centerLon); 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);
+94
View File
@@ -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