Kulcare Docs
DeveloperHospital surgery center

Recovery U3 Execution

Local resource commands, canonical capacity counts, focused proof, and integration limits.

State And Scope

Source HEAD: 0a9932352c4c328129b398d6ad33b314e1e12376. The writer verified this HEAD before edits. No tracked changes were present. The pre-existing .context/ and .compound-engineering/ paths were not read or changed. The writer did not delegate, install, stage, commit, push, merge, deploy, or invoke review. No credentials, ignored configuration, full schema export, or patient records were inspected. Tests created synthetic fixtures only in the assigned disposable database.

The internal U3 implementation passes focused proof and canonical backend CI. The complete CE review and a focused correction review ran. CodeRabbit reviewed the scoped implementation and corrections in three completed runs. All accepted findings are fixed. The last checkpoint-label correction was checked locally, not sent for a fourth external review. HTTP/UI and clinical activation are not U3 capabilities.

Clinical owns the implementation. Current references are Hospital CaseStock::Command, MarPolicy's fresh membership lookup, MedicationMar::DosePolicy's active assignments, SchedulingLock, canonical capacity models, and Audit::Dispatch. No production configuration model change was necessary.

Changed Paths

Backend paths below are relative to backend/domains/clinical/.

  • services/hospital/recovery/resource_command.rb
  • services/hospital/recovery/resource_input.rb
  • services/hospital/recovery/resource_projection.rb
  • policies/hospital/recovery_resource_policy.rb
  • test/services/hospital/recovery_resources_test.rb
  • test/services/hospital/recovery_resource_concurrency_test.rb
  • test/models/hospital/facility_configuration_test.rb
  • test/policies/clinical_policy_matrix_test.rb
  • docs/guides/developer/hospital-surgery-center/recovery-u3-execution.md (repository root)
  • docs/guides/developer/hospital-surgery-center/README.md (repository root)
  • docs/guides/developer/hospital-surgery-center/implementation-backlog.md (repository root)
  • docs/testing/hospital-recovery-qa.md (repository root)

Internal Interfaces

Clinical::Hospital::Recovery::ResourceCommand.call(facility:, actor:, operation_key:, action:, input:) returns Result(command:, error_code:, replayed:, outcome:), with success?. Successful outcomes are confirmed. Failures are rolled_back or unknown. Callers supply authenticated server-side facility and actor objects. The service also checks selected Shared::Current.tenant and Shared::Current.facility.

All inputs are flat hashes. Unknown fields, duplicate symbol/string keys, invalid UUIDs, coerced versions, and non-boolean activity values are rejected. Every command requires a nonblank reason. Identity and care-owner fields are not inputs.

ActionSelector and inputs
provision_resourcetarget_type is ward, room, or bed; requires configuration_version
Ward provisioningRequires name; optional description and floor
Room provisioningRequires room_number, ward_id, and ward_version
Bed provisioningRequires name, bed_number, care_area, room_id, room_version, and ward_version
configure_resourceRequires target_type, target_id, and version; applies the fields below
Ward configurationname, description, floor, is_active
Room configurationroom_number, is_active; optional ward_id with ward_version
Bed configurationname, bed_number, care_area, is_active; optional room_id with both parent versions
clean_resourceRequires bed selector/version and status; uses the existing canonical transitions

Bed versions are nonnegative integers. Room/group versions are UTC timestamps from updated_at.iso8601(6). Configuration versions follow the existing Blueprint: the same timestamp format, or new for an unsaved configuration. Purpose is exactly recovery, inpatient, or unclassified. The bed category stays the canonical general default for provisioning.

Cleaning commands can complete cleaning, enter/complete maintenance, or block/unblock where the existing state machine allows it. They cannot reserve, occupy, release, or convert an occupied bed directly to availability. Care writers own release to cleaning.

The immutable RecoveryCommand is the resource event. Its result contains the resource identity, descriptive fields, parent identities, state, and resulting version. No RecoveryEvent is created: that table belongs to stay movement. Audit::Dispatch must persist the required activity record in the same transaction. An absent or failed audit rolls back both resource and receipt.

Safe errors include VALIDATION_FAILED, STALE_WRITE, RESOURCE_NOT_FOUND, FORBIDDEN, OPERATION_KEY_REUSED, RESOURCE_CONFLICT, RESOURCE_OCCUPIED, PARENT_INACTIVE, INVALID_TRANSITION, RECOVERY_UNAVAILABLE, and AUDIT_UNAVAILABLE. Uncertain database/connection outcomes return RESOURCE_COMMAND_UNAVAILABLE with outcome: 'unknown'. SQL exception details are not returned.

Clinical::Hospital::Recovery::ResourceProjection.call(facility:, actor:) returns { resources:, totals:, error_code: nil } on success. Resources have string keys; totals have symbol keys. Totals include recovery, inpatient, unclassified, and deduplicated facility counts. Each has provisioned, active, available, occupied, reserved, cleaning, and unavailable. These counts overlap: unavailable means every resource not currently available. Active and available require active bed, room, and group records. Occupancy includes canonical owner evidence and owner pointers, not planning counts. An occupied resource without matching active owner evidence reports owner_state: 'missing' and cannot be assignable. No patient, stay, encounter, or actor identity is projected. Recovery assignability uses actual recovery purpose and canonical resource predicates. Source failure returns only RESOURCE_PROJECTION_UNAVAILABLE, not empty/zero success. Denied reads return only FORBIDDEN.

Authorization And Locks

Resource reads require view_hospital. Writes also require manage_hospital_configuration. Each service clears effective-permission cache and uses a fresh active membership. Active user, selected tenant/facility, and current active staff/practitioner assignment are required. Only owner/admin have the facility-administration assignment exception. This grants no clinical authority. Suspended practices can read but cannot write.

Provisioning requires the Recovery module and Hospital app flag. Authorized replay, existing-resource configuration, cleaning, and projection remain available when these availability settings are disabled. They cannot erase receipt history.

Lock order is SchedulingLock, facility/key advisory lock, configuration row, sorted groups, sorted rooms, then sorted beds. Authorization is repeated after advisory lock acquisition, before receipt lookup. Replay checks action and a sorted-input SHA-256 fingerprint, including the selector, before versions or availability settings. No care-owner row locks are taken after beds. U2 database guards remain active.

SchedulingLock deliberately serializes facility resource commands against settings updates. Both paths need one settings view before provisioning. A separate physical ledger, IPD flag, or new configuration lock protocol was not introduced.

Populated-room parent changes require one data-modifying CTE. Separate model updates failed the existing immediate scoped room/bed foreign key in a focused test. The CTE changes the room and its locked child beds in one SQL statement, increments bed versions, and preserves the existing constraints and triggers. It validates the room first and accepts only the bounded service attributes. No migration is needed.

Proof And Commands

The first sandbox test attempt failed on PostgreSQL connection permission before behavioral proof. The same focused runner then ran with approved escalation. Before production code, recovery_resources_test.rb produced 14 runs, 28 assertions, 14 errors, and no skips. The expected error was the absent Recovery service namespace.

Fixture corrections did not change production authority. The fixture graph needed an explicitly active staff record. Cross-tenant inputs had to be captured before the tenant switch. Organization fixtures were moved outside enforced-role blocks, and suspension used the existing non_payment value. The populated-room regression then exposed the immediate FK described above. One CTE heredoc syntax error was corrected before the passing run. No repeated unresolved repair assumption remains.

Post-cleanup worker checkpoint before review corrections: 28 runs, 215 assertions, 0 failures, 0 errors, 0 skips, seed 20530. That checkpoint included three independent-connection races with distinct backend PIDs under kulcare_rls_test: identical-key retry, duplicate same-room code, and one key with different payloads. Each leaves one committed resource/receipt. The retry race also proves one required audit. The worker ran no full suite or CI.

Current three-file result after review corrections: 32 runs, 268 assertions, 0 failures, 0 errors, 0 skips, seed 57580. The five committed concurrency scenarios cover identical-key retry, duplicate code, different payloads on one key, populated-room relocation against a child edit, and membership revocation while a command waits for the facility lock. The last test uses uncached lock-manager reads. Earlier test-observation attempts reused a cached result and timed out. No production authority rule was weakened.

From backend/, use the configured Ruby and PostgreSQL toolchain. This portable form uses the same owned database and runner safeguards as the recorded command:

RAILS_ENV=test PARALLEL_WORKERS=1 DATABASE_URL=postgresql:///kulcare_hospital_recovery_u3_20261020_test bundle exec rails runner 'ActiveRecord.maintain_test_schema = false; abort("Unexpected database") unless ActiveRecord::Base.connection.select_value("SELECT current_database()") == "kulcare_hospital_recovery_u3_20261020_test"; $LOAD_PATH.unshift(Rails.root.join("test").to_s); require Rails.root.join("domains/clinical/test/services/hospital/recovery_resources_test").to_s; require Rails.root.join("domains/clinical/test/services/hospital/recovery_resource_concurrency_test").to_s; require Rails.root.join("domains/clinical/test/models/hospital/facility_configuration_test").to_s'

The runner verifies the assigned database name before loading tests. The reusable race test does not hardcode a database name. This lets the parent assign other disposable resources for canonical verification. The pre-cleanup worker checkpoint had 218 assertions. Removing three redundant setup assertions produced the post-cleanup worker checkpoint of 215 assertions. No behavior scenario was removed. Schema maintenance stayed disabled for the focused runs. They did not reset, migrate, load or repair a database. The later canonical CI run prepared only owned disposable test databases. The normal test harness loads its reference catalog helpers only in this owned database. The nontransactional race tests reuse the current synthetic-fixture cleanup helpers; their temporary trigger changes and restoration are inside the cleanup transaction.

The exact focused lint command, also from backend/, was:

bundle exec rubocop domains/clinical/services/hospital/recovery/resource_command.rb domains/clinical/services/hospital/recovery/resource_input.rb domains/clinical/services/hospital/recovery/resource_projection.rb domains/clinical/policies/hospital/recovery_resource_policy.rb domains/clinical/test/services/hospital/recovery_resources_test.rb domains/clinical/test/services/hospital/recovery_resource_concurrency_test.rb domains/clinical/test/models/hospital/facility_configuration_test.rb --cache false --format simple

It used the configured Ruby toolchain. Result: 7 files inspected, no offenses detected. The first lint attempt could not write its default cache; the subsequent runs disabled cache. Existing project lint-configuration warnings remain unchanged. Local metric directives cover the finite input contract, projection shape, and race coordination. Two intentional raw fixture writes have local validation-skip directives. No project lint baseline or configuration was changed. git diff --check also passed.

RequirementFocused evidence
R1, R2; KTD1, KTD2Distinct named canonical resources; real groups/rooms; duplicate code, parent versions, parent moves, occupied structure protection; purpose-separated totals
R3 resource boundaryCleaning completion changes canonical assignability; occupied-to-free is denied; no stay command added
R8; KTD7, KTD8Fresh membership and assignment denial, selected tenant/facility checks under non-bypass role, suspended-practice restrictions, audit rollback
R10Planning/preset characterization creates no groups, rooms, or beds and retains custom restrictions; parent inactivity removes availability
R11Identical replay once, changed action/payload conflict, stale versions, independent races, explicit unknown outcomes

Limits And Release Gates

No controllers, routes, new nursing permissions, policy grants, schema, migrations, lockfiles, frontend, U2 records, or plan body changed. U6 owns HTTP and Blueprint wiring. U7 owns UI/settings integration. Stay receive/move/handoff/release and clinical policy are not U3 capabilities. No clinical constant or approval was inferred. No generic second event table, reservation engine, or inpatient gate was built.

The parent ran canonical verification and the required scoped reviews. The implementation worker did not invoke external reviews. Broader schema parity, alternate generic-writer races, HTTP/browser acceptance, deployment, nursing QA, D5/D4 acceptance, and pilot approval remain open. The stable-tree review covered the CTE and local metric exceptions.

  • Parent runs canonical verification and required scoped reviews, then fixes all accepted findings.
  • Through later U6/U7 surfaces, provision two resources and confirm stale rename protection.
  • Compare planning counts with actual capacity after maintenance and cleaning.
  • Verify disabled-module reconciliation and revoked-assignment denial in real HTTP mode.
  • Record manual QA, nursing acceptance, deployment, and pilot decisions separately.

Model And Usage Receipts

The parent dispatched hospital_implementer worker 01a15926-15ee-78a3-bcbf-aac34253f393 for this bounded unit. The configured model was gpt-6.1-sol with high effort. The parent collected its terminal result and closed the worker before integration. The worker did not delegate. Observed served-model, reasoning-effort, billing/token usage, and cost receipts are unavailable. The guide's configured strings are not observed receipts.

Parent Verification And Review

The parent reproduced the post-cleanup worker checkpoint of 28 tests and 215 assertions before the review regressions. The current three-file result is 32 tests and 268 assertions above. The five-file run also includes the Clinical matrix and role inventory: 99 tests, 2,635 assertions, no failures/errors, one existing matrix skip, seed 6228. The first full backend gate ran 18,861 tests and found two new registration gaps: the Clinical policy matrix and the role-check inventory. Neither failure was waived. The matrix now includes the resource policy. The policy reuses the existing membership admin? helper instead of copying its owner/admin role comparison. That helper already has an inventory entry.

A separate regression now uses a real active target room to prove that an occupied bed cannot be moved. The earlier invalid-room case remains unchanged.

Final canonical backend gate: CI_DOMAINS_SHARDS=4 bin/ci, with CI_BASE_REF=origin/docs/new-schema-design, test environment and the owned kulcare_hospital_recovery_u2_sql_20261020_test scratch database. It prepared four isolated shards and removed them after use. Result: 18,866 domain tests, 87,649 assertions, no failures/errors, eight existing skips, seed 9458. Pricing passed 20 tests, 26 assertions. All setup, schema, RLS and changed-file lint gates passed. No baseline changed.

The docs build passed: cd docs-site then pnpm build, with 511 indexed pages. The existing Reports HTML Pagefind warning remains unrelated. No frontend runtime changed, so no new frontend runtime CI result is claimed.

The CE full review run 20261020-174222-0d8c5672 completed with eight lenses and one confirmed P2 test gap. The parent added stale-child-version and fresh-version assertions around a populated-room move, plus committed relocation, admission occupancy and post-lock revocation proof. A fresh focused reviewer found no remaining correction defect and confirmed that P2 finding closed.

CodeRabbit CLI 0.9.0, with review --agent, completed three scoped runs. The first requested portable commands; the second requested current proof counts; the third requested distinct pre-cleanup and post-cleanup checkpoint labels. All three documentation corrections are included. The last wording correction was checked locally. No fourth external run or zero-finding final receipt is claimed. Snapshots excluded credentials, local configuration, full schema dumps, patient data and session artifacts. The snapshots had no remote and used the CLI allowance.

The CE cross-model route did not run. Its sanctioned transport requires npx, which project instructions prohibit. The local adversarial lens ran instead. No different-provider receipt is claimed by that route.

On this page