Files

29 KiB
Raw Permalink Blame History

Architecture B implementation plan

Prepared: 2026-10-14. Status: approved with conditions on 2026-10-14. Implementation authorized by Docs/ApprovalRequirements/architecture-b-implementation-approval.md; Stage 0 begins under its Q1–Q5 decisions.

1. Authority, baseline and preservation

Follow the complete current working-tree AGENT.md. Functional requirements in Docs/Requirements/ and security intent in Docs/Design/ govern behaviour. ArchitectureProposal/software-architecture.md, ADR-01–ADR-08 and the seven target diagrams govern structure, subject to this approval gate. Existing baseline service design is superseded only where the target expressly replaces it. ArchitectureSuggestions/ contains alternatives, not the selected contract. Root README describes the earlier design-only phase and will need an implementation update after approval.

Reference Recorded state
Original repository /home/steffen/Nextcloud/Documents/Master Thesis/HealthAppRepository; verified distinct Git working tree; strictly read-only
Original baseline 2117236366130775214d9fd2611984d4348f2b79; clean working tree at inspection
B preparation baseline 3426236c6cfcece36e94642ae84d1843288f86d5
Target proposal revision 3426236c6cfcece36e94642ae84d1843288f86d5, last commit affecting ArchitectureProposal/
Existing B changes Modified AGENT.md; untracked AGENTOldOutdated.md. Preserve without staging, reverting or including in implementation commits; approval requested
As-built documentation snapshot Describes 5d9371388c15066eeb2bc124ed227659c644dab5, not the current source HEAD. Source HEAD adds documentation; use pinned HEAD as implementation reference

Supporting records: documentation inventory, baseline manifest, original test inventory, open questions, functional preservation, conformance, log.

Inventory covers all 63 files in Docs/ and 18 target-proposal files, including 24 editable Draw.io files across both trees. Target diagrams have 16 pages: context, components, domain, conceptual classes, data ownership, local/remote deployment and four interaction sequences. Their labels/relationships were inspected as XML; GUI rendering was not tested. Historical JPEGs/backups are inventoried; current diagrams and explicit supersession govern. Hashes preserve inputs, including both existing instruction files.

Never build, restore, migrate, test, stage or commit inside the original repository: such operations can write generated files. After approval, copy only required tracked inputs from the pinned revision into B. Do not import its operating instructions, experiment outputs, generated binaries, credentials or unrelated tools. Preserve reused source identifiers and annotate their provenance in this log. Keep original tests available as unchanged baseline evidence before adapting the executable suite.

2. Existing system and observed differences

The original solution has five net10.0 ASP.NET Core applications, a transient C# provisioning utility and three xUnit acceptance projects. global.json selects SDK 10.0.100 with latestFeature roll-forward. Persistence uses Npgsql EF Core 10.0.3, EF Core Relational/Design 10.0.12; ASP.NET testing/Windows service hosting uses 10.0.12. Test SDK is 17.14.1, xUnit 2.9.3, runner 3.1.5. Retain these versions initially; no technology migration is proposed.

Concern Observed source Necessary Architecture B change
Runtime Gateway, Profile, Observation, Insights, Overview separately hosted One HTTPS host with API/access, Profile, Observations, Analytics, Overview, Guidance modules
Communication Gateway forwards requests; downstream clients call back through gateway with service keys Typed acyclic in-process interfaces; remove business HTTP clients, callback routing and service authentication
Public contracts Controllers, REST/JSON DTOs, validation and history selection headers Reuse route/JSON vocabulary and success/absence/access behaviour; explicit dependency-error reconciliation below
Authentication Framework opaque bearer token, 30-minute default, persistent data-protection keys, framework password hashing Reuse; keep normalized account/role identity, persistent key scope, provider replaceability; no service identity path
Authorization Middleware resolves profile and full observation via HTTP Trusted request-scoped authorized patient/action context; narrow owner/association lookups; authorize before external serialization, then owner-scoped operation
Profile lifecycle Unique nullable account column; account and new profile saved in one row; uniqueness race handled Reuse atomic lifecycle; require non-null unique association in target schema; reconcile historical null associations before import
Persistence Two databases/public schemas; independent DbContexts; no cross-database FK One database, owned profile/observations schemas, per-module migration history/owners, restricted FK and runtime DML role
Context EF owned value already flattened into observation row Reuse fields, unknown/null/omission semantics; no separate context entity or inference
Writes EF patch loads/saves row without explicit row locking; deletes by observation ID Transaction with actual-owner recheck and row lock; validate proposed changes atomically; preserve concurrent disjoint patches
Reads Independently timed ownership and source reads; overview sequential HTTP composition Shared repeatable-read snapshot from ownership lookup through capture; release before calculation and transmission
Ordering/time Latest measurement/creation/UUID; history measurement/UUID; UTC clock encoding in timestamp without timezone Preserve UTC encoding/wire behaviour; verify PostgreSQL unsigned UUID-byte ordering explicitly, rather than sort raw platform-endian GUID bytes
Analytics Fresh summaries/trends; compiled combined numerical/context/clinical implementation Reuse numerical formulas; separate SummaryPolicy, TrendPolicy, ClinicalPolicy and reference catalog; no result store/cache
Guidance Static home guidance in gateway controller; clinic/other explained unavailable Move existing content to versioned Guidance-owned bundle/catalog; preserve applicability and public availability during DB outages
Resources/failures No shared bounded request policy; upstream HTTP failures 502/504 Shared bounded pool, configurable admission/deadline/cancellation; 503 dependency/overload, 504 deadline, 500 unexpected failure
Deployment Five units, separate databases/credentials/certificates, Linux and optional Windows/macOS/distribution adapters One systemd app unit; local or verified-TLS remote DB; generated protected settings/roles/API certificate; administrative tool exits
Tests Two/four/five HTTP hosts and separate DB fixtures; independent-service installer assertions One real HTTP host/isolated database with owned schemas; retain functional assertions; approved replacement of obsolete topology tests

Concrete reuse sources include Profile Application/PatientApplicationService.cs, Domain/Patient.cs, request/response contracts and persistence mapping; Observation Application/ObservationApplicationService.cs, domains, patch presence/validation contracts and repositories; Insights Domain/InsightCalculator.cs, InsightCalculator.Trends.cs and result records; Overview composition and DTO vocabulary; Gateway credential/assignment/token logic and guidance content. Reuse is selective: mutable entities, repositories and HTTP clients are not exported as module contracts.

3. Proposed implementation layout and dependencies

Use one Web SDK project src/HealthApp/HealthApp.csproj, class-library module projects under src/Modules/{Profile,Observations,Analytics,Overview,Guidance}/, a small src/HealthApp.Contracts/ for immutable module contracts and patient/action authorization scope, and src/HealthApp.Infrastructure/ for transaction/pool coordination. API/access belongs to the host. This is a proposed implementation organization, not additional runtime services; exact filenames can change without changing boundaries.

Private domain entities, EF contexts and repositories remain internal to each owning module. Only query/command facades, registration and immutable return values are exposed. Infrastructure knows transaction mechanics, not clinical tables or access policy. Contracts contain no repositories, EF entities, SQL or configuration secrets. Architecture tests enforce project dependencies and private persistence types.

Allowed dependency graph: API/access → Profile, Observations, Analytics, Overview, Guidance; Observations → Profile query interface; Analytics → Observation query interface and Guidance reference interface; Overview → Profile, Observation, Analytics query interfaces. Facades depend on contracts, with implementations wired at composition. No module depends on the host or calls public routing. Profile and Observations adapters participate in the same scoped infrastructure transaction without accessing each other's tables. Analytics, Overview and Guidance have no health persistence adapter.

Infrastructure supplies a single bounded Npgsql data source/pool and a scoped coordinator. Participating EF contexts use the same connection/transaction and module-owned mappings. Protected read workflows begin repeatable-read before the first ownership lookup, materialize immutable values, and finish capture before calculations/JSON. Write workflows use an explicit transaction and owner-scoped row locking/recheck. Do not commit a read snapshot while deferred EF enumeration remains outstanding. Dispose/rollback on failures and cancellation; no automatic mutation retry after ambiguous commit.

4. ADR-to-task mapping

Decision / specification Source affected Planned target tasks and verification
ADR-01; §§1–2; component/classes diagrams Five Program.cs files, gateway forwarding controllers, downstream Clients/, solution Create host/module projects and typed facades; adapt controllers to facades; remove internal HTTP and service-key endpoints. Build all; dependency tests and runtime one-process check
ADR-02; §7; ownership diagram Profile/Observation contexts, SQL repositories, migrations; provisioning DB code Owned schemas/history, restricted FK, non-null account uniqueness, positive/category/time constraints, patient/time/original/UUID index, separate migration owners and DML role. Test twice-applied migrations, runtime DDL denial, ownership and referential integrity
ADR-03; §§3–5; creation sequence Profile application/repository, account migration; create/authentication tests Preserve trusted account derivation and durable single-row insert; translate uniqueness violation to 409; failure recovery and /me. Test simultaneous creation, lost response, rollback, restart and spoofed identities
ADR-04; §§4–5,8; context/access model Gateway Program/security/login/professional controllers; token support Keep framework ticket protection and password hashing, trusted role policies and key persistence; remove Service role/key selector; introduce owner resolver and non-forgeable request scope. Test full US-13/14 matrix, expired/tampered tokens, restart, replacement handler and absent internal routes
ADR-05; §5,7; snapshot sequence Observation/Insights/Overview reads and middleware Capture authorized source values in shared repeatable-read transaction; fetch selected series once; close before evaluation. Deterministic interleaving tests demonstrate coherent overview, observation owner/read consistency and next-request freshness after commits
ADR-06; §6; Analytics/Guidance class/domain pages Calculator partials/result types, guidance controller, TRENDS.md, trend/guidance tests Extract policies and versioned reference/guidance catalog; retain current numerical algorithm; document reproducible fixtures, claim-specific prerequisites, evidence and unresolved narrative meaning. Run original numerical/interpretation tests; require content review and escalate unsupported rules
ADR-07; §§3–4; observation classes Observation context/domain/contracts, EF owned mapping, PATCH Retain flattened optional context, original text/note, independent selection AND/Unknown and omitted/set/clear semantics. Lock row, validate whole mutation and preserve omissions. Context migration/patch/deletion tests plus concurrent disjoint patches
ADR-08; §9; deployment/install sequence deploy/HealthApp.Provisioning/, build-release, installer scripts, systemd, examples, CI Reuse appropriate certificate/config/bootstrap logic; replace service inventory with whole app/local-or-remote DB; one service identity and unit; generated roles/config/secrets, migrations, stage errors, no overwrite, readiness and restart/workflow proof. Separate process-level tests from native systemd installation evidence

Additional specification obligations: no-store on protected/login responses; sanitized failures/logging with correlation IDs and no identifying route values; public guidance during DB failure; readiness without health data; configurable pool/admission/deadlines with separate assessment budget; complete history with no silent truncation; verified remote DB TLS and hostname checking. Each gets a conformance/test entry; no production SLA or invented capacity guarantee.

5. Public compatibility and functional preservation

Preserve all 18 documented route/method combinations in target §4, including /patients/me, public login/guidance and own professional assignment list. Preserve DTO field names, enum tokens, camel-case JSON, optional text/null shape, request validation, Location paths, and history X-Measurement-Setting/X-Activity-Condition. Internal /by-account becomes an interface only. Observation DTO currently omits creation/update timestamps: preserve that omission even though internal snapshots retain original recording time. Patient response likewise does not expose account association or internal timestamps.

Ordinary HTTP semantics: create 201, successful reads/updates/patch 200, delete 204; validation 400; generic missing/invalid/expired auth 401; prohibited role operations 403; unauthorized resources uniform non-disclosing 404; duplicates 409; no latest/profile/observation 404; empty history 200 array; no insight 404 with existing title; empty trend 200 with explicit unavailable parts; overview retains profile and nullable parts/absence explanations. Keep missing-data and dependency failures distinct.

Explicit approval is required for structural incompatibilities: independent-service installation disappears under the proposed US-16 revision; 502 internal-upstream failures no longer exist and are replaced by §8's 503 DB/dependency/overload and 504 deadline behaviour. Preserve fail-closed, no disclosure/no write and failure-versus-absence assertions. Do not silently alter old tests to assert different codes.

Functional-equivalence.md maps every story to source suites and planned checks. Acceptance register retains the proposal's 146 individually identified common/US-01–US-15 entries and required outcomes, with planned suite allocation and unverified status. Expand theory examples and map exact test methods/results during implementation; suite allocation alone is not proof of coverage. Original tests are evidence, not authority to override a requirement.

Trend method proposal: retain the baseline mathematics. Raw means/minima/maxima/range use every selected observation; final means half-up two decimals. Group tied measurement instants by decimal mean; distinct instants have equal weight. Preserve all successive nonzero changes/reversals, total absolute successive change, full-period normalized-time ordinary least-squares slope and six-decimal output slope. Direction requires at least two distinct instants; identifier/recording order does not participate. Separate numerical and clinical policy structurally, add a method version and reproducible examples in implementation docs without gratuitous wire additions. No smoothing, replacement formula or arbitrary clinical variation cutoff.

Clinical catalog extraction must preserve existing source URLs/review metadata and allowed results pending verification. The baseline's favourable/concerning rules are explicitly described as cautious inferences, not independently reviewed clinical decision rules. Document each claim/prerequisite and review support; do not invent new medical rules. If evidence requires changing externally visible classifications, stop the affected step and request approval. Finite English/Danish conflict phrases remain limited detection; preserve text, known conflicts and explicit unresolved narrative limits rather than claim universal language understanding. Clinic guidance stays explained unavailable unless approved reviewed content is supplied.

6. Persistence and migration arrangements

Fresh installation: one dedicated PostgreSQL database; profile.patient and observations.observation (physical name aligned with proposal). Preserve public identifiers and values regardless of table rename. Account association unique, non-null and immutable via module commands. Restricted patient FK; flattened context; positive numerical/category/rest checks and required timestamps. Profile owner creates only Profile objects; Observation owner creates only Observation objects, with the narrowly necessary REFERENCES grant. Runtime role has needed SELECT/INSERT/UPDATE and Observation DELETE, schema USAGE, no DDL/admin/role membership. Module migration histories stay owned separately. No generated insight/trend/overview tables. Runtime never invokes migrations.

Keep legacy UTC-clock timestamp encoding if needed for byte-compatible public timestamps; normalize all input instants consistently. Document UUID network-byte tie order and test fixed UUIDs that distinguish network-byte ordering from little-endian byte-array sorting. Retain existing decimal means and optional rest-duration unit (minutes).

Approved Q4 scope is independently provisioned fresh B databases and equivalent reproducible synthetic datasets, no import or live migration required or authorized. A future migration procedure remains documentation only. No source database access or source repository mutation is authorized. If import is required, add an offline administrative import step from administrator-provided snapshots, with separate approval of dataset and account mappings. Preflight missing/duplicate accounts, orphan observations, unsupported categories/non-positive values and timestamp interpretation; reject ambiguous input without silently discarding/reassigning data. Preserve IDs, account IDs, original/update/measurement instants, raw values, complete/partial/unknown context, text/notes and predefined assignments. Validate counts and fields against snapshots. Retain source snapshots and take backups; never run an automatic destructive conversion in place.

Protect compatible token keys when migrating installations; reuse baseline application discriminator if valid tickets must survive cutover. Key export/import is administrative, no keys enter Git. Fresh installations get their own key state. No claims of live upgrade continuity until verified.

7. Configuration and deployment

Retain .NET 10 / ASP.NET Core controllers / EF Core / PostgreSQL / xUnit. One ConnectionStrings:HealthDatabase; protected accounts and assignments; persistent key directory and application scope; 30-minute configurable token lifetime; HTTPS listener/certificate; reviewed content/method versions; bounded pool, request and assessment admission limits and deadlines. Provide safe examples without secrets. Remove backend URLs, callback keys and per-feature listeners from active configuration.

Approved portability requirement: portable Linux installation for explicitly documented systemd-based distributions, with distribution-specific dependency adapters. Intended families: Debian/Ubuntu (apt), Fedora/RHEL (dnf), and Arch/Manjaro (pacman), conditional on compatible .NET 10/PostgreSQL packages and systemd. Perform a real end-to-end native installation on at least one identified distribution; record verified versus intended support separately. Do not restrict design to Ubuntu or claim universal Linux support. Linux is required; do not port old Windows/macOS/SSH feature-service distribution adapters as required deliverables. Preserve their provenance rather than import obsolete deployment modes into B. Broader platform support requires separate evidence/scope.

Build bundle contains one app, transient provisioner, systemd unit and installer. Normal installer provisions dependencies, local database if selected, migration owners/runtime role, generated credentials/accounts, certificate/trust, restricted paths, persistent keys, configuration, migrations, service enable/start and verification. For remote DB accept protected admin connection/CA and network prerequisites; create app DB/schemas/roles remotely with verified TLS, do not install local PostgreSQL. Client trust is established; no certificate-validation bypass.

Installation verifier checks single app PID/HTTPS/configured DB, synthetic login/profile/observation/history/insight/overview, and app stop/restart while PostgreSQL remains running. Existing generated empty professional is valid; assigned reads require a predefined fixture, not a new assignment API. Ensure verification reports any synthetic data it creates and does not masquerade as a production-cleanup workflow. Refuse overwrite, identify failed stage and retain protected diagnostics; no transactional installer rollback promise. Document upgrade backup/key retention/schema coordination and certificate replacement with evidence limits.

8. Incremental sequence and checkpoints

Each approved stage is a small cohesive change with relevant tests and updated conformance/equivalence/log evidence. Do not mark or commit a stage as complete with known broken checks. Use focused commits if authorized by plan approval; never include pre-existing instruction changes. Obtain deviations approval before affected implementation.

Stage Concrete deliverable Required checkpoint
0 — Approval and executable reference Q1–Q5 approved; reference/SDK/disposable PostgreSQL established; baseline 299 tests passed; preserve baseline tests and selective inputs with source hashes; run baseline in a B-local reference checkout outside final solution Record actual reference build/test results, failures and test expansions; original repo stays clean
1 — Module foundation Solution, one host and immutable contracts, private module registration/persistence boundaries; port public guidance and framework login Build independent B projects; login/guidance contract fixtures, one host, project dependencies, no service-key trust path
2 — Profile/data foundation (US-01–03,13–14) Profile schema/migrations/roles, atomic profile association, access facade and profile endpoints; prepared Observation schema/FK migration ordering Profile/auth/assignment tests; race/rollback/lost-response/restart; runtime cannot migrate/create/drop schemas; repeated migrations
3 — Observation lifecycle (US-04–09) Observation facades/mapping/constraints, actual-owner policy, record/get/latest/history/PUT/PATCH/delete; transaction locking Original observation/context/selection tests; UUID ties/timezones; atomic invalid patch; concurrent disjoint/same-field writes and delete interactions; no unauthorized writes
4 — Analytics (US-10–11) In-process current-series capture; reused summary/trend formulas; separate clinical policy/reference catalog and method docs Summary rounding, every US-11 criterion, temporal ties/storage order/reversals/excursions/context conflicts; claim review; DB failure never means empty result
5 — Overview/snapshot composition (US-12) Shared authorization/profile/latest/series snapshot; calculate after capture; preserve latest/insight bases and absence Original overview assertions; deterministic concurrent-update tests; source series queried once; transaction released before calculation/response
6 — Operational boundary Readiness/liveness, sanitized failure/no-store handling, pool/admission/deadline/cancellation and remote DB transport configuration DB outage/timeout/rollback/overload; guidance/login independence as applicable; no silent truncation; config/key/TLS failure tests
7 — Native release/installer (revised US-16) One app/systemd unit and local/remote DB automation, certificate/config/roles, no-overwrite/staged diagnostics, restart verifier Publish bundle; installer/process tests; real Ubuntu systemd local install and verified remote-DB placement; preserve DB while app restarts
8 — Final audit Accurate build/run/deployment README, all required evidence and limitations, approved deviations only Full solution Release build/tests/publish; criterion-level coverage review, architectural dependency/schema/process inspection, input hashes and original Git status

No HTTP upstream simulations are carried into runtime code merely to satisfy obsolete tests. Before adapting each affected test, record original scenario/assertions and replacement proof in the log. Preserve unaffected assertions. Keep unchanged original test sources as reference evidence, separate from final executable test projects.

9. Build/start/test preparation and evidence limits

Original documented commands (run only on approved B-local reference/final files): dotnet build HealthApp.slnx -c Release; TEST_POSTGRES_CONNECTION=... dotnet test HealthApp.slnx -c Release; original service migration mode --migrate; original release bash deploy/build-release.sh --output NEW_DIRECTORY. Reference tests create/drop isolated random databases; use an explicit non-production administrator connection. Final test fixture uses one isolated DB per fixture and applies both schemas twice, with runtime access separately tested from migration/admin credentials.

Preparation environment: dotnet absent from PATH; /home/steffen/.dotnet/dotnet provides SDK 9.0.200/runtime 9.0.2, incompatible with source target. psql exists; default /run/postgresql:5432 has no response. No usable configured test server has been established. Do not downgrade source to .NET 9. Provision .NET 10 and isolated PostgreSQL after approval, with tool escalation where required. Native installation needs an administrator-controlled supported systemd host; process tests/mock package tests alone do not prove it.

No restore, build, application test, installer, live import, clinical publisher verification or energy measurement was performed during preparation. Source/doc inspection is not passing verification. Clinical review and real native deployment remain acceptance dependencies. Final evidence must distinguish verified, partially verified and not verified per criterion; count passing tests only from executed results.

10. Risks and approval gate

Main risks: combined process/role blast radius; shared connection/EF transaction enlistment errors; snapshot lifetime/large-series memory; concurrency/lost-update regressions; legacy null accounts/orphans; obsolete topology assertions and error-code mismatch; clinical claims/narrative ambiguity; SDK/test DB/systemd availability; remote TLS/certificate/key preservation; partial installer failure/upgrade recovery.

Mitigation is explicit ownership and transaction tests, unchanged functional assertion intent, import preflight/no live conversion, preserved formulas/content provenance, focused review before any changed classification, native verification and candid limits. No workload/HA/backup SLA is invented. No energy-efficiency benefit is claimed.

Approval received: Q1 revised US-16/dependency errors; Q2 preserved instruction files; Q3 unchanged mathematics, thresholds and clinical outputs with uncertainty disclosure; Q4 fresh provisioning only; Q5 portable distribution-aware Linux installer and actual native verification. See approval register. Further approval is required only for material actions outside these boundaries.

Execution outcome — 2026-10-14

Approved stages 0–8 implemented and engineering verification completed. Baseline 299/299 tests; B 283/283 tests; Release build/publish clean; actual native Debian 12 systemd local/remote installation and independent restart passed. All 146 acceptance entries mapped to concrete executed methods; six retain explicitly partial independent clinical support under Q3. Other intended distributions have adapter tests but no native execution claim. No unapproved deviation, A database access/import, source/input/instruction mutation, or energy-efficiency claim. See final-verification.json and the conformance/equivalence registers for exact evidence and limits.