diff --git a/docs/CODING_STANDARDS.md b/docs/CODING_STANDARDS.md new file mode 100644 index 0000000..ec6a4c5 --- /dev/null +++ b/docs/CODING_STANDARDS.md @@ -0,0 +1,142 @@ +# MinerOps Coding Standards + +## Purpose + +This document defines the engineering conventions for MinerOps. Task specifications may add feature-specific requirements, but they should not weaken these standards without an explicit architectural decision. + +## Core Principles + +1. Prefer explicit domain operations over generic CRUD. +2. Preserve operational history. +3. Enforce critical invariants in PostgreSQL. +4. Keep operations atomic. +5. Separate network identity from durable asset identity. +6. Use server-controlled timestamps and authenticated actor identities. +7. Design for self-hosted deployment and safe recovery. +8. Prefer clear, maintainable code over clever abstractions. +9. Keep each implementation task focused and reviewable. +10. Treat safety as more important than convenience for actions affecting miners. + +## Layered Architecture + +```text +Router + -> Service + -> Repository + -> PostgreSQL +``` + +### Router + +Routers may define HTTP routes, validate requests, enforce authentication and permissions, and serialize responses. + +Routers must not contain SQL, manage transactions, implement domain decisions, import database drivers directly, or bypass the service layer. + +### Service + +Services implement domain workflows, coordinate repositories, enforce domain rules, and raise domain exceptions. + +Services must not import FastAPI, raise HTTP-specific exceptions, contain raw SQL, or trust actor identity supplied in request bodies. + +### Repository + +Repositories own database queries, row locking, persistence details, and PostgreSQL-specific integrity behavior. + +Repositories must not import FastAPI, make permission decisions, define HTTP behavior, or commit independently inside a larger service transaction. + +## Domain Operations + +Use explicit operations such as: + +```http +POST /api/repairs +POST /api/repairs/{repair_id}/complete +POST /api/miners/{miner_id}/move +POST /api/miners/{miner_id}/replace-control-board +``` + +Only `POST /api/repairs` is implemented by the modular Repairs domain today. +The other routes are illustrative names for possible future explicit workflows, +not existing API contracts. + +Avoid broad mutable CRUD endpoints when the request represents a meaningful operational event. + +## Transactions and Concurrency + +Any workflow that changes multiple authoritative records must execute atomically. + +Use row locks and database constraints when concurrent requests could violate an invariant. Do not rely only on pre-insert application checks when PostgreSQL can enforce the rule. + +## Database Integrity + +Use constraints for uniqueness, valid state combinations, referential integrity, one-active-record rules, event-sequence integrity, and actor/timestamp requirements. + +Operational history should generally use `RESTRICT` rather than disappearing through cascades. + +Every migration must support upgrade, safe downgrade or explicit refusal, previous-head testing, re-upgrade, and empty-database-through-head validation. A downgrade must never invent historical values. + +## Identity + +A miner's durable identity must not depend on its current IP address, MAC address, control board, hostname, or location. + +Network identifiers are observations or replaceable hardware attributes and must retain history. + +Actor identity must come from the authenticated principal, never an authoritative request-body field. + +## Time + +Use timezone-aware timestamps. Authoritative operational timestamps are server- or database-controlled. Never use timestamp order as a substitute for an explicit event sequence. + +## Immutable Operational History + +Timeline and audit events are append-only. Once written, an event is never edited, deleted, reordered, or silently replaced. Corrections are new events. + +Sequenced domain timeline events should include an event UUID, parent UUID, +sequence, event type, actor UUID, timestamp, and structured JSON payload. + +## API Design + +- Use UUID types for UUID fields. +- Use constrained domain values. +- Use 404 for missing resources, 409 for state conflicts, 422 for invalid input, and established project behavior for 401 and 403. +- Do not expose internal fields without a product requirement. +- Keep routes focused. +- Protect existing static routes when introducing parameter routes. + +## Permissions + +Permissions describe capabilities, not roles. Implemented examples include +`repairs.read` and `repairs.create`. Names such as `repairs.complete` and +`miners.move` illustrate possible future capabilities and are not currently +registered permissions. + +Every protected route requires unauthenticated, unauthorized, and authorized-role tests. Read-only roles may view history but may not perform actions. + +## Testing and Validation + +Feature work should cover happy paths, validation, permissions, missing records, conflicts, rollback, concurrency where relevant, constraints, migrations, route compatibility, and architecture boundaries. + +Unless a task says otherwise, run: + +- Python compilation +- shell syntax validation +- focused tests +- relevant regression suites +- migration upgrade, downgrade, re-upgrade, and empty database +- disposable development baseline +- router SQL/driver/transaction audit +- service/repository FastAPI audit +- route-count audit +- `git diff --check` + +## Security + +Never commit credentials, tokens, environment files, dumps, private configuration, caches, or local database data. Do not log secrets. Apply least privilege and preserve audit history for sensitive actions. + +## Documentation + +Every implementation task should have a version-controlled specification under `docs/tasks/`. Update roadmaps only after validation passes. Add an ADR only for a genuinely new architectural principle. + +## Review Checklist + +Before approval, confirm scope, transaction boundaries, database invariants, actor attribution, timestamps, immutable history, permissions, migrations, regressions, route behavior, performance risks, and the reviewed file set. diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md new file mode 100644 index 0000000..5142db1 --- /dev/null +++ b/docs/CONTRIBUTING.md @@ -0,0 +1,68 @@ +# Contributing to MinerOps + +## Workflow + +```text +Product decision + -> Task specification + -> Implementation + -> Architecture review + -> Focused review and fixes + -> Commit + -> Push +``` + +Substantial work should begin from an approved specification in `docs/tasks/`. + +## Before Starting + +1. Confirm repository, branch, working tree, and expected latest commit. +2. Read the architecture, product, decisions, coding standards, task + specification, and relevant release planning document when one exists. +3. Confirm the current Alembic head. +4. Report material conflicts before deviating. + +## Scope + +Each task should implement one coherent feature. Adjacent ideas belong in later tasks rather than being bundled into the current change. + +## Branches and Commits + +Do not force-push, rebase shared branches, amend approved commits, or mix unrelated work without explicit approval. + +Use concise conventional commit messages, for example: + +```text +feat: add begin repair workflow +feat: add repair timeline read APIs +fix: restore lifecycle during repair downgrade +docs: add MinerOps coding standards +``` + +Commit only after implementation, validation, review, and file-set confirmation. + +## Completion Report + +Report files created and modified, migrations, routes, permissions, domain behavior, test counts, validation results, risks, and final `git status --short`. + +## Architecture + +Follow `docs/CODING_STANDARDS.md` and preserve: + +```text +Router -> Service -> Repository -> PostgreSQL +``` + +Use explicit operational APIs and immutable history. + +## Migrations + +Validate previous head to new head, downgrade, re-upgrade, empty database through head, constraints, indexes, permission assignments, and transactional failure behavior. + +## Review + +Review for scope creep, hidden CRUD, incorrect transactions, application-only invariants, unsafe downgrades, route shadowing, permission regressions, loss of history, N+1 queries, concurrency gaps, and accidental sensitive files. + +## AI-Assisted Work + +AI tools must inspect the repository, follow the task, preserve conventions, report conflicts, run validation, avoid commits and pushes unless instructed, and provide a complete report. Human approval is still required. diff --git a/docs/releases/v0.2-repair-workflow.md b/docs/releases/v0.2-repair-workflow.md new file mode 100644 index 0000000..915d758 --- /dev/null +++ b/docs/releases/v0.2-repair-workflow.md @@ -0,0 +1,50 @@ +# MinerOps v0.2: Repair Workflow + +## Status + +Planning document. The version label and remaining scope are provisional and do +not override the current version summary in `README.md` or phase ordering in +`docs/ROADMAP.md`. + +## Goal + +Deliver a complete, auditable repair lifecycle based on durable miner identity +and immutable history. + +## Completed + +- [x] Begin Repair (`POST /api/repairs`) +- [x] Repair detail and timeline read APIs + +## Planned + +- [ ] Return to Service +- [ ] Control Board Replacement +- [ ] Repair Parts Tracking + +These planned items refer to explicit workflows in the modular Repairs domain. +Existing legacy repair, maintenance, location, and parts-summary behavior does +not make these workflows complete. + +## Definition of Done + +- all planned tasks are implemented +- repair actions are atomic +- history is immutable +- actor and timestamps are authoritative +- critical invariants are enforced in PostgreSQL +- migration lifecycle tests pass +- repair and inventory regressions pass +- no generic repair CRUD is introduced +- operator behavior is documented +- the release candidate is built from a clean, reproducible repository state + +## Candidate Task Order + +1. `003-return-to-service.md` +2. `004-control-board-replacement.md` +3. `005-repair-parts-tracking.md` + +These are proposed future files under `docs/tasks/`. They do not exist yet and +must not be treated as approved specifications until they are created and +reviewed. diff --git a/docs/releases/v0.3-operations.md b/docs/releases/v0.3-operations.md new file mode 100644 index 0000000..107f67d --- /dev/null +++ b/docs/releases/v0.3-operations.md @@ -0,0 +1,38 @@ +# MinerOps v0.3: Operations + +## Status + +Planning document. The version label and candidate scope are provisional and do +not override the current version summary in `README.md` or phase ordering in +`docs/ROADMAP.md`. + +## Goal + +Add safe operational control for individual miners and groups while preserving +guardrails and auditability. + +## Candidate Scope + +- [ ] Miner move workflow +- [ ] Maintenance mode +- [ ] Bulk tagging and location updates +- [ ] Safe reboot and shutdown +- [ ] Scheduled actions +- [ ] Staggering and cooldown controls +- [ ] Action history +- [ ] Partial-failure reporting +- [ ] Role-based action permissions + +This scope spans the roadmap's Operations and Fleet Control phases. Inventory, +identity, maintenance context, and monitoring dependencies remain governed by +`docs/ROADMAP.md`. + +The repository already contains early-stage legacy movement, command, +scheduling, and action-status behavior. Unchecked items mean the modular, +permissioned, fully validated product workflow remains planned; they do not +claim that no related code exists. + +## Definition of Done + +Actions are explicit, permissioned, audited, safety-limited, recoverable, and +tested for authorization, concurrency, retries, and partial failure. diff --git a/docs/releases/v0.4-monitoring.md b/docs/releases/v0.4-monitoring.md new file mode 100644 index 0000000..4a07d73 --- /dev/null +++ b/docs/releases/v0.4-monitoring.md @@ -0,0 +1,38 @@ +# MinerOps v0.4: Monitoring + +## Status + +Planning document. The version label and candidate scope are provisional and do +not override the current version summary in `README.md` or phase ordering in +`docs/ROADMAP.md`. + +## Goal + +Provide reliable current-state and historical visibility across the fleet. + +## Candidate Scope + +- [ ] Configurable discovery +- [ ] MAC-based asset reconciliation +- [ ] Miner status and telemetry +- [ ] Historical retention +- [ ] Fleet dashboard +- [ ] Room, rack, model, and electrical summaries +- [ ] Alert generation and lifecycle +- [ ] Notification integrations + +Discovery and network reconciliation depend on the roadmap's Inventory & +Identity phase, while electrical summaries depend on Infrastructure. Their +presence here does not change those dependencies. + +The repository already contains early-stage discovery, telemetry, retention, +dashboard, and infrastructure-summary foundations. Unchecked items describe +work needed for a coherent, supported monitoring product rather than an absence +of related implementation. + +## Definition of Done + +Observations remain distinct from authoritative inventory, stale data is +explicit, discovery does not blindly create assets, retention is documented, +alerts are auditable, and monitoring failures cannot corrupt inventory or +repair history. diff --git a/docs/releases/v1.0.md b/docs/releases/v1.0.md new file mode 100644 index 0000000..bd4909c --- /dev/null +++ b/docs/releases/v1.0.md @@ -0,0 +1,34 @@ +# MinerOps v1.0 + +## Status + +Planning document. The version label is provisional. This file describes release criteria, not current +capabilities or a delivery commitment. It does not override the current version +summary in `README.md` or phase ordering and completion status in +`docs/ROADMAP.md`. + +## Goal + +Deliver a production-ready, self-hosted operating platform for cryptocurrency +mining operations. + +## Release Themes + +- durable inventory and identity +- complete repair workflow +- safe operational controls +- monitoring and alerting +- work orders and maintenance +- spare parts and component history +- electrical mapping +- backup, restore, and migration +- security, roles, and auditability +- documented deployment and upgrades + +## Production Readiness + +v1.0 requires tested backup and restore, safe migrations, health checks, +reproducible deployment, encrypted credential handling, HTTPS guidance, +database-backed integrity, documented regression coverage for critical +workflows, performance testing at representative fleet size, release notes, and +documented limitations. diff --git a/docs/tasks/TEMPLATE.md b/docs/tasks/TEMPLATE.md new file mode 100644 index 0000000..fd12be9 --- /dev/null +++ b/docs/tasks/TEMPLATE.md @@ -0,0 +1,88 @@ +# Task NNN: Feature Name + +## Objective + +Describe the operational outcome. + +## Background + +Summarize relevant current behavior and dependencies. + +## Scope + +List exactly what is included. + +## API + +Define every route, request, response, permission, and status code. + +## Permissions + +Define capabilities and role assignments. + +## Domain Rules + +List invariants and lifecycle rules. + +## Architecture + +Preserve: + +```text +Router -> Service -> Repository -> PostgreSQL +``` + +## Database and Migration + +Define schema changes, constraints, indexes, migration order, and downgrade behavior. + +## Events and History + +Define immutable events, sequence, actor, timestamp, and structured payload. + +## Models and Validation + +Define UUID, time, enum, normalization, length, and JSON requirements. + +## Repository Requirements + +Define focused query and locking behavior. Avoid N+1 queries and generic CRUD. + +## Service Requirements + +Define validation, workflow, transaction boundaries, and domain exceptions. + +## Router Requirements + +Define dependencies, exception mapping, and route-count constraints. + +## Error Behaviour + +Define 401, 403, 404, 409, 422, and any additional statuses. + +## Concurrency and Atomicity + +Describe races and database enforcement. + +## Tests + +Cover authorization, domain behavior, rollback, constraints, migrations, regressions, routing, and architecture audits. + +## Validation + +Run compilation, shell validation, focused and regression tests, migration lifecycle tests, disposable baseline, architecture audits, route audit, and `git diff --check`. + +## Documentation + +List required roadmap, release, API, or operator documentation. + +## Explicitly Out of Scope + +List adjacent features that must not be added. + +## Completion Report + +Report files, migration, routes, permissions, tests, validation, limitations, and final `git status --short`. + +Do not commit. +Do not push.