diff --git a/backend/src/domus/application/fixed_batch_review.py b/backend/src/domus/application/fixed_batch_review.py index ce893e80..67b7eeee 100644 --- a/backend/src/domus/application/fixed_batch_review.py +++ b/backend/src/domus/application/fixed_batch_review.py @@ -1,6 +1,6 @@ """Prepare and atomically replace eligible future fixed obligations.""" -from dataclasses import dataclass, replace +from dataclasses import asdict, dataclass, replace from datetime import timedelta from functools import partial @@ -21,6 +21,7 @@ StorageFailure, ) from domus.domain.identity import MemberStatus, validate_revision +from domus.domain.inventory import InventoryEffect from domus.domain.recurrence_planning import FixedBatch, FixedCursor, cursor_binding from domus.domain.recurrence_records import ( FixedExceptionKind, @@ -104,6 +105,7 @@ class ReplacementSource: definition: TaskDefinition replaceable: tuple[AffectedWork, ...] retained: tuple[AffectedWork, ...] + effects: tuple[InventoryEffect, ...] def prepare(self, planner: FixedRecurrencePlanner, now: int) -> PreparedReplacement: rule = self.upcoming @@ -319,7 +321,10 @@ def replacement_source( revision=rule.revision + 1, pattern_revision=rule.pattern_revision + 1, ) - return ReplacementSource(rule, upcoming, progress, definition, tuple(replaced), tuple(retained)) + effects = unit.inventory.effects(home, tuple(item.work.occurrence_id for item in replaced)) + return ReplacementSource( + rule, upcoming, progress, definition, tuple(replaced), tuple(retained), effects + ) @dataclass(frozen=True, slots=True) @@ -345,6 +350,20 @@ def document(self) -> JsonDocument: "before": self.before.local.isoformat(), "retained_work": [item.value() for item in rule.retained], "cancelled_work": [item.value() for item in rule.replaceable], + **( + { + "inventory_effects": [ + { + **asdict(effect), + "kind": effect.kind.value, + "remaining": str(effect.remaining), + } + for effect in rule.effects + ] + } + if rule.effects + else {} + ), "prospective_slots": [ { "planned": planned.value(), @@ -389,7 +408,7 @@ def commit( ), progress.revision, ) - replacements: JsonObject = {} + replacements: dict[str, str] = {} additions: list[JsonValue] = [] originals = iter(self.pairing) for batch in self.steps: @@ -427,12 +446,40 @@ def commit( transition.document(), partial(transition_occurrence, household_id=home, request=transition), ) + moved, retained = self._transfer_effects(unit, replacements) return { "kind": "fixed_replacement", "schedule_id": rule.schedule_id, "schedule_revision": rule.revision, "pattern_revision": rule.pattern_revision, - "replacements": replacements, + "replacements": dict[str, JsonValue](replacements), "cancelled": [item.work.occurrence_id for item in self.source.replaceable], "added": additions, + **( + {"inventory_transferred": moved, "inventory_retained": retained} + if moved or retained + else {} + ), } + + def _transfer_effects( + self, unit: UnitOfWork, replacements: dict[str, str] + ) -> tuple[list[JsonValue], list[JsonValue]]: + # New occurrences are materialized from this exact reviewed definition. + materials = { + (line.line_id, line.binding.reference_id) for line in self.source.definition.materials + } + moved: list[JsonValue] = [] + retained: list[JsonValue] = [] + for effect in self.source.effects: + assert effect.occurrence_id is not None + replacement = replacements.get(effect.occurrence_id) + if replacement is None or (effect.line_id, effect.reference_id) not in materials: + retained.append(effect.effect_id) + continue + unit.inventory.update_effect( + replace(effect, occurrence_id=replacement, revision=effect.revision + 1), + effect.revision, + ) + moved.append({"id": effect.effect_id, "from": effect.occurrence_id, "to": replacement}) + return moved, retained diff --git a/backend/src/domus/application/inventory.py b/backend/src/domus/application/inventory.py new file mode 100644 index 00000000..78b96b34 --- /dev/null +++ b/backend/src/domus/application/inventory.py @@ -0,0 +1,247 @@ +"""Own physical movements and task-linked commitments in the caller's transaction.""" + +from collections.abc import Callable +from dataclasses import asdict, dataclass, replace +from typing import cast + +from domus.application.authorization import HouseholdAccess, MembershipAuthorization +from domus.application.commands import AtomicCommands, Change +from domus.application.identity_ports import CurrentHuman +from domus.application.inventory_ports import InventoryRecords +from domus.application.ports import Clock, Identifiers, Transactions, UnitOfWork +from domus.application.task_material_ports import InventoryMaterialResult, MaterialPostingRequest +from domus.domain.errors import Conflict, InvalidInput, StorageFailure +from domus.domain.identity import Permission +from domus.domain.inventory import ( + MAX_STOCK_UNITS, + EffectKind, + InventoryEffect, + StockMovement, + stock_units, +) +from domus.domain.storage import CommandKey, JsonDocument, Receipt +from domus.domain.task_material_values import ( + MaterialBinding, + MaterialPendingReason, + MaterialQuantity, +) +from domus.domain.task_materials import MaterialPosting + + +@dataclass(frozen=True, slots=True) +class InventorySettlement: + records: InventoryRecords + clock: Clock + identifiers: Identifiers + + def resolve( + self, household_id: str, actor_member_id: str, reference_id: str + ) -> MaterialBinding | None: + # TaskMaterialAccess has already proved actor and household inside this unit. + return self.records.material(household_id, reference_id) + + def settle(self, request: MaterialPostingRequest) -> InventoryMaterialResult: + intent = request.intent + home, reference = intent.household_id, intent.line.binding.reference_id + previous = self.records.movement(home, request.source_key) + if previous is not None: + return InventoryMaterialResult(posting=previous.posting) + if self.records.material(home, reference) != intent.line.binding: + return InventoryMaterialResult(pending_reason=MaterialPendingReason.BINDING_CHANGED) + quantity = cast(MaterialQuantity, intent.quantity) + used = stock_units(quantity) + corrects = None + if intent.posting is not None: + corrects = intent.posting.movement_id + original = self.records.movement_by_id(home, corrects) + if original is None or original.posting != intent.posting: + raise StorageFailure("invalid_inventory_posting_source") + used -= stock_units(intent.posting.quantity) + reservation = next( + ( + item + for item in self.records.effects(home, (intent.occurrence_id,)) + if item.kind is EffectKind.RESERVATION + and item.reference_id == reference + and item.line_id == intent.line.line_id + ), + None, + ) + balance = self.records.balance(home, reference) + available = balance - self.records.reserved(home, reference) + usable = available + (0 if reservation is None else reservation.remaining) + if used > usable or balance - used > MAX_STOCK_UNITS: + return InventoryMaterialResult(pending_reason=MaterialPendingReason.STOCK_SHORTAGE) + if reservation is not None and used > 0: + self.records.update_effect( + replace( + reservation, + remaining=max(0, reservation.remaining - used), + revision=reservation.revision + 1, + ), + reservation.revision, + ) + posted = MaterialPosting( + intent.intent_id, + home, + intent.occurrence_id, + intent.cycle_id, + intent.line.line_id, + reference, + intent.line.binding.revision, + intent.revision, + intent.effect_revision, + quantity, + self.identifiers.new(), + self.identifiers.new(), + self.clock.now(), + ) + self.records.append( + StockMovement( + home, + reference, + posted.movement_id, + request.source_key, + request.actor_member_id, + -used, + posted.posted_at, + intent.reason, + posted, + corrects, + ), + balance - used, + ) + return InventoryMaterialResult(posting=posted) + + +@dataclass(frozen=True, slots=True) +class InventoryCommands: + """Internal Inventory manager operations used by the task integration.""" + + transactions: Transactions + actor: CurrentHuman + clock: Clock + identifiers: Identifiers + household_id: str = "home" + + def _execute( + self, + action: str, + key: str, + payload: JsonDocument, + apply: Callable[[UnitOfWork, str, CommandKey], JsonDocument], + ) -> Receipt: + human = self.actor.current() + command = CommandKey(self.household_id, human.ha_user_id, action, key) + access = HouseholdAccess(human) + authority = MembershipAuthorization(access, action, Permission.INVENTORY_MANAGE) + + def change(unit: UnitOfWork) -> Change: + member = access.require(unit, self.household_id, Permission.INVENTORY_MANAGE) + result = apply(unit, member.member_id, command) + return Change(result, payload, JsonDocument.from_value({"version": 1, "kind": action})) + + return AtomicCommands(self.transactions, authority, self.clock, self.identifiers).execute( + command, payload, change + ) + + def receive(self, key: str, binding: MaterialBinding, quantity: MaterialQuantity) -> Receipt: + binding.require_quantity(quantity) + if binding.household_id != self.household_id or binding.revision != 1 or quantity.is_zero: + raise InvalidInput("invalid_inventory_receipt") + payload = JsonDocument.from_value({"binding": asdict(binding), "quantity": quantity.value}) + + def apply(unit: UnitOfWork, member: str, command: CommandKey) -> JsonDocument: + stock = unit.inventory + home, reference = binding.household_id, binding.reference_id + current = stock.material(home, reference) + if current is None: + stock.add_material(binding) + elif current != binding: + raise Conflict("inventory_binding_changed") + received = stock_units(quantity) + balance = stock.balance(home, reference) + received + if balance > MAX_STOCK_UNITS: + raise Conflict("inventory_stock_capacity") + movement = StockMovement( + home, + reference, + self.identifiers.new(), + JsonDocument.from_value(asdict(command)).fingerprint, + member, + received, + self.clock.now(), + "receipt", + ) + stock.append(movement, balance) + return JsonDocument.from_value({"movement_id": movement.movement_id}) + + return self._execute("inventory.receive", key, payload, apply) + + def commit_effect( + self, + key: str, + kind: EffectKind, + reference_id: str, + quantity: MaterialQuantity, + *, + occurrence_id: str | None = None, + ) -> Receipt: + if ( + not isinstance(kind, EffectKind) + or quantity.is_zero + or (occurrence_id is None and kind is EffectKind.RESERVATION) + ): + raise InvalidInput("invalid_inventory_effect") + payload = JsonDocument.from_value( + { + "kind": kind.value, + "reference_id": reference_id, + "quantity": quantity.value, + "occurrence_id": occurrence_id, + } + ) + + def apply(unit: UnitOfWork, member: str, command: CommandKey) -> JsonDocument: + home, stock = self.household_id, unit.inventory + binding = stock.material(home, reference_id) + if binding is None: + raise InvalidInput("invalid_material_reference") + binding.require_quantity(quantity) + line_id = None + if occurrence_id is not None: + work = unit.tasks.occurrence(home, occurrence_id) + line = ( + None + if work is None + else next( + ( + item + for item in work.definition_snapshot.materials + if item.binding == binding + ), + None, + ) + ) + if line is None: + raise InvalidInput("invalid_material_reference") + line_id = line.line_id + amount = stock_units(quantity) + if kind is EffectKind.RESERVATION and amount > stock.balance( + home, reference_id + ) - stock.reserved(home, reference_id): + raise Conflict("inventory_insufficient_stock") + value = InventoryEffect( + home, + self.identifiers.new(), + kind, + reference_id, + occurrence_id, + occurrence_id, + line_id, + amount, + ) + stock.add_effect(value) + return JsonDocument.from_value({"effect_id": value.effect_id}) + + return self._execute("inventory.commit-effect", key, payload, apply) diff --git a/backend/src/domus/application/inventory_ports.py b/backend/src/domus/application/inventory_ports.py new file mode 100644 index 00000000..30910936 --- /dev/null +++ b/backend/src/domus/application/inventory_ports.py @@ -0,0 +1,20 @@ +"""Inventory records belong to the current unit of work.""" + +from typing import Protocol + +from domus.domain.inventory import InventoryEffect, StockMovement +from domus.domain.task_material_values import MaterialBinding + + +class InventoryRecords(Protocol): + def material(self, home: str, reference: str) -> MaterialBinding | None: ... + def add_material(self, binding: MaterialBinding) -> None: ... + def balance(self, home: str, reference: str) -> int: ... + def reserved(self, home: str, reference: str) -> int: ... + def effect(self, home: str, effect_id: str) -> InventoryEffect | None: ... + def effects(self, home: str, occurrences: tuple[str, ...]) -> tuple[InventoryEffect, ...]: ... + def add_effect(self, value: InventoryEffect) -> None: ... + def update_effect(self, value: InventoryEffect, previous_revision: int) -> None: ... + def movement(self, home: str, source_key: str) -> StockMovement | None: ... + def movement_by_id(self, home: str, movement_id: str) -> StockMovement | None: ... + def append(self, value: StockMovement, balance: int) -> None: ... diff --git a/backend/src/domus/application/ports.py b/backend/src/domus/application/ports.py index eabfb7d0..2416bfa0 100644 --- a/backend/src/domus/application/ports.py +++ b/backend/src/domus/application/ports.py @@ -3,6 +3,7 @@ from contextlib import AbstractContextManager from typing import Protocol +from domus.application.inventory_ports import InventoryRecords from domus.application.member_profile_ports import MemberPreferencesRepository, MemberPresentations from domus.application.points_ports import PointsRepository from domus.application.recurrence_ports import RecurrenceRepository @@ -97,6 +98,9 @@ def save(self, category: TaskCategory, expected_revision: int) -> None: ... class UnitOfWork(Protocol): + @property + def inventory(self) -> InventoryRecords: ... + @property def points(self) -> PointsRepository: ... diff --git a/backend/src/domus/composition/tasks.py b/backend/src/domus/composition/tasks.py index dd576ef0..c81f1477 100644 --- a/backend/src/domus/composition/tasks.py +++ b/backend/src/domus/composition/tasks.py @@ -7,7 +7,8 @@ from domus.application.calendar_queries import CalendarQueries from domus.application.fixed_materialization import MaintenanceScope from domus.application.fixed_recurrence import FixedRecurrencePlanner -from domus.application.ports import Transactions +from domus.application.inventory import InventorySettlement +from domus.application.ports import Transactions, UnitOfWork from domus.application.recurrence_commands import RecurrenceCommands from domus.application.recurrence_review import RecurrenceReview from domus.application.relative_recurrence import RelativeRecurrencePlanner @@ -42,6 +43,9 @@ def task_contexts( planner = RelativeRecurrencePlanner(PinnedRecurrenceTime()) cursors = TaskCursor(clock, SecureEntropy().new().encode("ascii")) + def inventory(unit: UnitOfWork) -> InventorySettlement: + return InventorySettlement(unit.inventory, clock, identifiers) + def context(actor: TaskSession) -> TaskHTTPContext: return TaskHTTPContext( lambda: TaskQueries( @@ -51,7 +55,7 @@ def context(actor: TaskSession) -> TaskHTTPContext: installation, schedule_data_identity=planner.times.data_identity, ), - TaskCommands(store, actor, clock, identifiers), + TaskCommands(store, actor, clock, identifiers, inventory_factory=inventory), RecurrenceReview(store, installation, actor, actor.read, clock, identifiers, planner), lambda: CalendarQueries( store, MaintenanceScope(installation, "home"), actor.read(), cursors, planner.times @@ -63,6 +67,7 @@ def context(actor: TaskSession) -> TaskHTTPContext: clock, identifiers, FixedRecurrencePlanner(CalendarNominalExpansion(), planner.times), + inventory_factory=inventory, bind_household_policy=True, ), RelativeRecurrenceCommands( @@ -71,6 +76,7 @@ def context(actor: TaskSession) -> TaskHTTPContext: clock, identifiers, planner.times, + inventory_factory=inventory, bind_household_policy=True, ), TaskCategoryCommands(store, actor, actor.read, clock, identifiers), diff --git a/backend/src/domus/domain/inventory.py b/backend/src/domus/domain/inventory.py new file mode 100644 index 00000000..3672ab3f --- /dev/null +++ b/backend/src/domus/domain/inventory.py @@ -0,0 +1,46 @@ +"""Exact stock movements and stable task-linked Inventory effects.""" + +from dataclasses import dataclass +from enum import StrEnum + +from domus.domain.task_material_values import MaterialQuantity +from domus.domain.task_materials import MaterialPosting + +MAX_STOCK_UNITS = 10**18 - 1 + + +def stock_units(quantity: MaterialQuantity) -> int: + whole, _, fraction = quantity.value.partition(".") + return int(whole) * 1_000_000 + int(fraction.ljust(6, "0")) + + +class EffectKind(StrEnum): + RESERVATION = "reservation" + DEMAND = "demand" + + +@dataclass(frozen=True, slots=True) +class InventoryEffect: + household_id: str + effect_id: str + kind: EffectKind + reference_id: str + origin_id: str | None + occurrence_id: str | None + line_id: str | None + remaining: int + revision: int = 1 + + +@dataclass(frozen=True, slots=True) +class StockMovement: + household_id: str + reference_id: str + movement_id: str + source_key: str + member_id: str + delta: int + created_at: int + reason: str + posting: MaterialPosting | None = None + corrects: str | None = None diff --git a/backend/src/domus/infrastructure/sqlite.py b/backend/src/domus/infrastructure/sqlite.py index 53f1b4a7..66194dfe 100644 --- a/backend/src/domus/infrastructure/sqlite.py +++ b/backend/src/domus/infrastructure/sqlite.py @@ -37,6 +37,11 @@ ) from domus.infrastructure.sqlite_history import HISTORY_STATEMENTS, SQLiteHistory from domus.infrastructure.sqlite_identity import SQLiteMembers, SQLitePolicies +from domus.infrastructure.sqlite_inventory import ( + INVENTORY_STATEMENTS, + INVENTORY_TABLES, + SQLiteInventory, +) from domus.infrastructure.sqlite_member_profile_schema import PROFILE_STATEMENTS, PROFILE_TABLES from domus.infrastructure.sqlite_member_profiles import SQLitePreferences, SQLitePresentations from domus.infrastructure.sqlite_points import POINTS_STATEMENTS, POINTS_TABLE, SQLitePoints @@ -69,7 +74,7 @@ ) from domus.infrastructure.sqlite_tasks import SQLiteTasks -SCHEMA_VERSION = 16 +SCHEMA_VERSION = 17 APPLICATION_ID = 0x444F4D55 BASE_STATEMENTS = ( "CREATE TABLE installation(singleton INTEGER PRIMARY KEY CHECK(singleton=1), " @@ -142,6 +147,7 @@ MISSED_OCCURRENCE_STATEMENT, *CATEGORY_STATEMENTS, *POINTS_STATEMENTS, + *INVENTORY_STATEMENTS, ) BASE_TABLES = {"installation", "households", "receipts", "audit", "outbox"} IDENTITY_TABLES = BASE_TABLES | {"members", "household_policy"} @@ -155,7 +161,8 @@ CALENDAR_SCHEMA_TABLES = LIFECYCLE_SCHEMA_TABLES | {"calendar_preferences"} MISSED_SCHEMA_TABLES = CALENDAR_SCHEMA_TABLES | {MISSED_OCCURRENCE_TABLE} CATEGORY_SCHEMA_TABLES = MISSED_SCHEMA_TABLES | {CATEGORY_TABLE} -TABLES = CATEGORY_SCHEMA_TABLES | {POINTS_TABLE} +POINTS_SCHEMA_TABLES = CATEGORY_SCHEMA_TABLES | {POINTS_TABLE} +TABLES = POINTS_SCHEMA_TABLES | INVENTORY_TABLES def _schema(connection: sqlite3.Connection) -> tuple[tuple[str, str], ...]: @@ -187,6 +194,7 @@ def _expected_schema(version: int) -> tuple[tuple[str, str], ...]: *((MISSED_OCCURRENCE_STATEMENT,) if version >= 14 else ()), *(CATEGORY_STATEMENTS if version >= 15 else ()), *(POINTS_STATEMENTS if version >= 16 else ()), + *(INVENTORY_STATEMENTS if version >= 17 else ()), ) for statement in statements: connection.execute(statement) @@ -382,6 +390,7 @@ def __init__(self, connection: sqlite3.Connection, installation: Installation) - self.task_materials = SQLiteTaskMaterials(connection) self.task_categories = SQLiteTaskCategories(connection) self.points = SQLitePoints(connection) + self.inventory = SQLiteInventory(connection) class SQLiteDatabase: @@ -448,6 +457,7 @@ def _inspect( 13: CALENDAR_SCHEMA_TABLES, 14: MISSED_SCHEMA_TABLES, 15: CATEGORY_SCHEMA_TABLES, + 16: POINTS_SCHEMA_TABLES, }.get(version, TABLES) if application_id != APPLICATION_ID or objects != expected_tables: raise DatabaseRejected("unrelated_database") @@ -509,7 +519,8 @@ def initialize(self, *, require_existing: bool = False) -> None: *((HOUSEHOLD_FOLD_STATEMENT,) if version < 13 else ()), *((MISSED_OCCURRENCE_STATEMENT,) if version < 14 else ()), *(CATEGORY_STATEMENTS if version < 15 else ()), - *POINTS_STATEMENTS, + *(POINTS_STATEMENTS if version < 16 else ()), + *INVENTORY_STATEMENTS, ) for statement in migration: connection.execute(statement) diff --git a/backend/src/domus/infrastructure/sqlite_inventory.py b/backend/src/domus/infrastructure/sqlite_inventory.py new file mode 100644 index 00000000..60b6c990 --- /dev/null +++ b/backend/src/domus/infrastructure/sqlite_inventory.py @@ -0,0 +1,252 @@ +"""Transaction-local SQLite Inventory with append-only stock evidence.""" + +import sqlite3 +from dataclasses import astuple, dataclass +from typing import cast + +from domus.domain.errors import Conflict, StorageFailure +from domus.domain.inventory import ( + MAX_STOCK_UNITS, + EffectKind, + InventoryEffect, + StockMovement, + stock_units, +) +from domus.domain.storage import JsonDocument, validate_identifier +from domus.domain.task_material_values import MaterialBinding +from domus.domain.task_values import validate_task_time +from domus.infrastructure.sqlite_task_material_records import posting_value, read_posting + +INVENTORY_TABLES = {"inventory_materials", "inventory_effects", "inventory_movements"} +INVENTORY_STATEMENTS = ( + "CREATE TABLE inventory_materials(household_id TEXT NOT NULL " + "REFERENCES households(household_id), " + "reference_id TEXT NOT NULL, product_id TEXT NOT NULL, unit_id TEXT NOT NULL, " + "location_id TEXT NOT NULL, revision INTEGER NOT NULL CHECK(revision=1), " + "precision INTEGER NOT NULL CHECK(precision BETWEEN 0 AND 6), label TEXT NOT NULL, " + f"balance INTEGER NOT NULL CHECK(balance BETWEEN 0 AND {MAX_STOCK_UNITS}), " + "PRIMARY KEY(household_id,reference_id), UNIQUE(household_id,product_id,location_id)) STRICT", + "CREATE TABLE inventory_effects(household_id TEXT NOT NULL, effect_id TEXT NOT NULL, " + "kind TEXT NOT NULL CHECK(kind IN ('reservation','demand')), reference_id TEXT NOT NULL, " + "origin_id TEXT, occurrence_id TEXT, line_id TEXT, " + f"remaining INTEGER NOT NULL CHECK(remaining BETWEEN 0 AND {MAX_STOCK_UNITS}), " + "revision INTEGER NOT NULL CHECK(revision>=1), PRIMARY KEY(household_id,effect_id), " + "UNIQUE(household_id,occurrence_id,reference_id,kind), " + "CHECK((origin_id IS NOT NULL AND occurrence_id IS NOT NULL AND line_id IS NOT NULL) OR " + "(kind='demand' AND origin_id IS NULL AND occurrence_id IS NULL AND line_id IS NULL)), " + "FOREIGN KEY(household_id,reference_id) " + "REFERENCES inventory_materials(household_id,reference_id), " + "FOREIGN KEY(household_id,origin_id) REFERENCES task_occurrences(household_id,occurrence_id), " + "FOREIGN KEY(household_id,occurrence_id) " + "REFERENCES task_occurrences(household_id,occurrence_id)) STRICT", + "CREATE INDEX inventory_reservations ON inventory_effects(household_id,reference_id) " + "WHERE kind='reservation' AND remaining>0", + "CREATE TABLE inventory_movements(position INTEGER PRIMARY KEY, household_id TEXT NOT NULL, " + "reference_id TEXT NOT NULL, movement_id TEXT NOT NULL, source_key TEXT NOT NULL, " + "member_id TEXT NOT NULL, delta INTEGER NOT NULL " + f"CHECK(delta BETWEEN {-MAX_STOCK_UNITS} AND {MAX_STOCK_UNITS} AND delta!=0), " + "created_at INTEGER NOT NULL CHECK(created_at>=0), " + "reason TEXT NOT NULL, posting TEXT, corrects TEXT, " + "UNIQUE(household_id,movement_id), UNIQUE(household_id,source_key), " + "UNIQUE(household_id,reference_id,movement_id), UNIQUE(household_id,corrects), " + "CHECK((posting IS NOT NULL) OR (delta>0 AND corrects IS NULL)), " + "FOREIGN KEY(household_id,reference_id) " + "REFERENCES inventory_materials(household_id,reference_id), " + "FOREIGN KEY(household_id,reference_id,corrects) " + "REFERENCES inventory_movements(household_id,reference_id,movement_id), " + "FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id)) STRICT", +) + + +def _effect(row: sqlite3.Row) -> InventoryEffect: + return InventoryEffect( + row["household_id"], + row["effect_id"], + EffectKind(row["kind"]), + row["reference_id"], + row["origin_id"], + row["occurrence_id"], + row["line_id"], + row["remaining"], + row["revision"], + ) + + +def _movement(row: sqlite3.Row) -> StockMovement: + posting = row["posting"] + return StockMovement( + row["household_id"], + row["reference_id"], + row["movement_id"], + row["source_key"], + row["member_id"], + row["delta"], + row["created_at"], + row["reason"], + None if posting is None else read_posting(JsonDocument(posting).decode()), + row["corrects"], + ) + + +@dataclass(frozen=True, slots=True) +class SQLiteInventory: + connection: sqlite3.Connection + + def material(self, home: str, reference: str) -> MaterialBinding | None: + row = self.connection.execute( + "SELECT household_id,reference_id,product_id,unit_id,location_id," + "revision,precision,label " + "FROM inventory_materials WHERE household_id=? AND reference_id=?", + (home, reference), + ).fetchone() + return None if row is None else MaterialBinding(*row) + + def add_material(self, binding: MaterialBinding) -> None: + self.connection.execute( + "INSERT INTO inventory_materials VALUES (?,?,?,?,?,?,?,?,0)", astuple(binding) + ) + + def balance(self, home: str, reference: str) -> int: + row = self.connection.execute( + "SELECT balance FROM inventory_materials WHERE household_id=? AND reference_id=?", + (home, reference), + ).fetchone() + return cast(int, row["balance"]) + + def reserved(self, home: str, reference: str) -> int: + row = self.connection.execute( + "SELECT COALESCE(SUM(remaining),0) FROM inventory_effects WHERE household_id=? " + "AND reference_id=? AND kind='reservation' AND remaining>0", + (home, reference), + ).fetchone() + return cast(int, row[0]) + + def effect(self, home: str, effect_id: str) -> InventoryEffect | None: + row = self.connection.execute( + "SELECT * FROM inventory_effects WHERE household_id=? AND effect_id=?", + (home, effect_id), + ).fetchone() + return None if row is None else _effect(row) + + def effects(self, home: str, occurrences: tuple[str, ...]) -> tuple[InventoryEffect, ...]: + if not occurrences: + return () + placeholders = ",".join("?" for _ in occurrences) + return tuple( + _effect(row) + for row in self.connection.execute( + "SELECT * FROM inventory_effects WHERE household_id=? " + f"AND occurrence_id IN ({placeholders}) AND remaining>0 ORDER BY effect_id", + (home, *occurrences), + ) + ) + + def add_effect(self, value: InventoryEffect) -> None: + self.connection.execute( + "INSERT INTO inventory_effects VALUES (?,?,?,?,?,?,?,?,?)", astuple(value) + ) + + def update_effect(self, value: InventoryEffect, previous_revision: int) -> None: + updated = self.connection.execute( + "UPDATE inventory_effects SET occurrence_id=?,remaining=?,revision=? " + "WHERE household_id=? AND effect_id=? AND revision=?", + ( + value.occurrence_id, + value.remaining, + value.revision, + value.household_id, + value.effect_id, + previous_revision, + ), + ) + if updated.rowcount != 1: + raise Conflict("inventory_effect_stale") + + def _movement(self, sql: str, home: str, key: str) -> StockMovement | None: + row = self.connection.execute(sql, (home, key)).fetchone() + return None if row is None else _movement(row) + + def movement(self, home: str, source_key: str) -> StockMovement | None: + return self._movement( + "SELECT * FROM inventory_movements WHERE household_id=? AND source_key=?", + home, + source_key, + ) + + def movement_by_id(self, home: str, movement_id: str) -> StockMovement | None: + return self._movement( + "SELECT * FROM inventory_movements WHERE household_id=? AND movement_id=?", + home, + movement_id, + ) + + def append(self, value: StockMovement, balance: int) -> None: + posting = ( + None if value.posting is None else JsonDocument.from_value(posting_value(value.posting)) + ) + self.connection.execute( + "INSERT INTO inventory_movements(household_id,reference_id,movement_id,source_key," + "member_id,delta,created_at,reason,posting,corrects) VALUES (?,?,?,?,?,?,?,?,?,?)", + ( + value.household_id, + value.reference_id, + value.movement_id, + value.source_key, + value.member_id, + value.delta, + value.created_at, + value.reason, + None if posting is None else posting.encoded, + value.corrects, + ), + ) + self.connection.execute( + "UPDATE inventory_materials SET balance=? WHERE household_id=? AND reference_id=?", + (balance, value.household_id, value.reference_id), + ) + + +def verify_inventory_records(connection: sqlite3.Connection) -> None: + stock = SQLiteInventory(connection) + balances: dict[tuple[str, str], int] = {} + for row in connection.execute("SELECT * FROM inventory_movements ORDER BY position"): + movement = _movement(row) + key = movement.household_id, movement.reference_id + validate_identifier(movement.source_key) + validate_identifier(movement.movement_id) + validate_task_time(movement.created_at) + balance = balances.get(key, 0) + movement.delta + posting = movement.posting + if posting is not None: + if ( + posting.household_id != movement.household_id + or posting.reference_id != movement.reference_id + or posting.movement_id != movement.movement_id + or posting.posted_at != movement.created_at + ): + raise StorageFailure("invalid_inventory_movement") + prior_units = 0 + if movement.corrects is not None: + prior = stock.movement_by_id(movement.household_id, movement.corrects) + if ( + prior is None + or prior.posting is None + or prior.posting.intent_id != posting.intent_id + ): + raise StorageFailure("invalid_inventory_movement") + prior_units = stock_units(prior.posting.quantity) + if movement.delta != prior_units - stock_units(posting.quantity): + raise StorageFailure("invalid_inventory_movement") + if not 0 <= balance <= MAX_STOCK_UNITS: + raise StorageFailure("invalid_inventory_balance") + balances[key] = balance + for row in connection.execute( + "SELECT household_id,reference_id,balance FROM inventory_materials" + ): + home, reference, balance = row + stock.material(home, reference) + if ( + balance != balances.get((home, reference), 0) + or stock.reserved(home, reference) > balance + ): + raise StorageFailure("invalid_inventory_balance") diff --git a/backend/src/domus/infrastructure/sqlite_snapshots.py b/backend/src/domus/infrastructure/sqlite_snapshots.py index c1e38021..99285e72 100644 --- a/backend/src/domus/infrastructure/sqlite_snapshots.py +++ b/backend/src/domus/infrastructure/sqlite_snapshots.py @@ -41,6 +41,7 @@ last_committed_at, verify_history, ) +from domus.infrastructure.sqlite_inventory import verify_inventory_records from domus.infrastructure.sqlite_points import verify_points_records from domus.infrastructure.sqlite_recovery import _record as _recovery from domus.infrastructure.sqlite_recurrence_integrity import ( @@ -195,6 +196,8 @@ def _records(connection: sqlite3.Connection, version: int, installation: Install verify_relative_lifecycle_records(connection, installation) if version >= 16: verify_points_records(connection, installation) + if version >= 17: + verify_inventory_records(connection) except DomusError as error: raise DatabaseRejected("invalid_snapshot_records") from error diff --git a/backend/src/domus/infrastructure/sqlite_task_material_records.py b/backend/src/domus/infrastructure/sqlite_task_material_records.py index 8862ba7c..8442412f 100644 --- a/backend/src/domus/infrastructure/sqlite_task_material_records.py +++ b/backend/src/domus/infrastructure/sqlite_task_material_records.py @@ -101,7 +101,13 @@ def _quantity(value: JsonValue) -> MaterialQuantity | None: return None if value is None else MaterialQuantity(cast(str, value)) -def _posting(value: JsonValue) -> MaterialPosting | None: +def posting_value(value: MaterialPosting) -> JsonObject: + row = asdict(value) + row["quantity"] = value.quantity.value + return cast(JsonObject, row) + + +def read_posting(value: JsonValue) -> MaterialPosting | None: if value is None: return None row = _object(value, _POSTING) @@ -136,7 +142,7 @@ def material_document(value: MaterialIntent) -> JsonDocument: quantity=None if value.quantity is None else value.quantity.value, ) if value.posting is not None: - row["posting"]["quantity"] = value.posting.quantity.value + row["posting"] = posting_value(value.posting) return JsonDocument.from_value(row) @@ -164,7 +170,7 @@ def read_material(encoded: str) -> MaterialIntent: if row["pending_reason"] is None else MaterialPendingReason(cast(str, row["pending_reason"])), cast(str, row["reason"]), - _posting(row["posting"]), + read_posting(row["posting"]), cast(int, row["effect_revision"]), cast(int, row["revision"]), ) diff --git a/docs/evidence/recurrence-calendar-qualification.md b/docs/evidence/recurrence-calendar-qualification.md index 743efdba..2b79250e 100644 --- a/docs/evidence/recurrence-calendar-qualification.md +++ b/docs/evidence/recurrence-calendar-qualification.md @@ -243,3 +243,30 @@ The default CI test uses the checked-out image and invokes each channel with its actual entrypoint on an independent private directory. Stable and Edge in this test are scoped installations. Distribution and live Supervisor acceptance require their own evidence. + +## Points and Inventory follow-up for issue 23 + +The qualification tables above preserve the state of the original review. The +following witnesses cover the six cross-domain assertions left open at that +revision. The existing cases, refinement counts and integration aliases remain +with their owning specifications. + +- `recurrence-calendar-C27` — `test_points_consumer.py::test_pending_relative_work_advances_once_before_approval_posts_points` observes one successor and no allocation while approval is pending, then one real allocation after approval. +- `recurrence-calendar-C29` — `test_points_consumer.py::test_weekly_missed_slots_stay_on_anchor_and_never_earn_points` observes missed weekly work, one eligible positive control and the persisted result after restoration. +- `recurrence-execution-C24` — `test_points_consumer.py::test_pending_relative_work_advances_once_before_approval_posts_points` exercises the default successor policy and a durable receipt with no premature allocation. +- `recurrence-calendar-C33` — `test_inventory_recurrence.py::test_reviewed_batch_recovers_original_stock_reservations_and_demand` exercises an actual reservation, task demand and manual extra. The original key recovers the accepted transfer once after restart and restoration. Physical stock and manual demand stay unchanged. +- `recurrence-execution-C27` — `test_inventory_recurrence.py::test_source_reopening_keeps_completed_successor_and_real_stock_after_restore` records real consumption and Points on the completed successor. Reopening reverses the original Points award once and preserves the successor's movement, balance, remaining reservation and award across restoration. +- `recurrence-lifecycle-calendar-C24` — `test_inventory_recurrence.py::test_started_work_wins_independent_invalidation_and_preserves_inventory` uses independent SQLite writers and asserts one retained review with unchanged real reservation, demand and ledger. Restoration preserves the same review and the exact Points award and source reversal. The failed reviewed-transfer test covers rollback. + +The first three rows use the reviewed Points head +`e0753b675439e64671783581362bb06c9c0c30fb`. +[Points PR](https://github.com/vypdev/domus/pull/58) · +[Exact CI run](https://github.com/vypdev/domus/actions/runs/42658034090) + +The final three rows use the [Inventory follow-up](https://github.com/vypdev/domus/issues/57) +and the [published Inventory delta](../../specs/household-inventory.md). +The SQLite adapter also exercises the genuine schema 16 fixture, atomic +schema 17 migration, transaction rollback after stock append, exact linked +correction, and production task HTTP settlement in Ingress and standalone. +The follow-up PR carries the current commit's check results. The wider Inventory +catalog and replenishment workflows retain their separate readiness gates. diff --git a/specs/CATALOG.md b/specs/CATALOG.md index 9ea5bd1c..b398af86 100644 --- a/specs/CATALOG.md +++ b/specs/CATALOG.md @@ -16,7 +16,7 @@ debt or convert unknown historic intent into a design decision. | `recurrence-calendar` | Proposed | A bounded scheduler turns task definitions into stable occurrences and a family calendar distinguishes planned start, deadline and actual completion. Original recurrence outcomes bind receipt status, action, result and source-cycle identity before replay and snapshot acceptance. | [Recurrence engine and family calendar](./recurrence-calendar.md) + 3 companion | 37 paths · 2026-11-09 | | `points-rewards` | Proposed | Task completion produces auditable point entries. Household-configurable collaboration policies determine each share and the actual award total; corrections preserve history and optional rewards never control basic participation. | [Auditable points, participation and optional rewards](./points-rewards.md) | 14 paths · 2026-11-09 | | `shopping-management` | Proposed | Shopping combines manual intent, replenishment and task materials without losing provenance. Buying an item and physically receiving it are separate recorded facts. | [Shared shopping demand, purchases and receipt](./shopping-management.md) | 5 paths · 2026-10-29 | -| `household-inventory` | Proposed | The household knows what is available, where it is stored and what needs replenishment through a local product catalog and an immutable stock movement ledger. | [Product catalog, pantry stock and replenishment](./household-inventory.md) | 5 paths · 2026-10-31 | +| `household-inventory` | Proposed | The household knows what is available, where it is stored and what needs replenishment through a local product catalog and an immutable stock movement ledger. | [Product catalog, pantry stock and replenishment](./household-inventory.md) | 11 paths · 2026-10-31 | | `home-assistant-surface` | Proposed | Domus exposes its household capabilities as native Home Assistant entities, services and events. The already integrated HA MCP consumes these surfaces; no gateway work or second MCP is included. | [Home Assistant entities, services and integration](./home-assistant-surface.md) + 1 companion | 5 paths · 2026-10-29 | | `application-experience` | Proposed | A complete household interface serves all six domains from the first release with fast daily actions, responsive navigation and clear operation results, independently of entity dashboards and AI.; combined native/standalone browser CI uses a bounded complete-suite deadline with protected candidate workflow qualification | [Responsive application, household dashboard and navigation](./application-experience.md) + 1 companion | 37 paths · 2026-11-08 | | `delivery-quality` | Proposed | Every implemented capability starts with meaningful tests and enforced architecture boundaries. A CI Check workflow validates each PR update, and both deployment targets ship isolated experimental and production channels. | [Clean Architecture, CI Check and isolated Stable and Edge channels](./delivery-quality.md) | 27 paths · 2026-10-31 | @@ -97,9 +97,9 @@ debt or convert unknown historic intent into a design decision. - Specifications: [`specs/household-inventory.md`](./household-inventory.md) - Workflows: Not applicable for this capability. - Entrypoints: Not yet implemented (proposed capability). -- Core code: Not yet implemented (proposed capability). -- Tests: Not yet implemented (proposed capability). -- User documentation: [`docs/product-vision.md`](../docs/product-vision.md) · [`docs/architecture.md`](../docs/architecture.md) · [`docs/operations.md`](../docs/operations.md) · [`docs/user-guide.md`](../docs/user-guide.md) · [`docs/contracts/home-assistant.md`](../docs/contracts/home-assistant.md) +- Core code: [`backend/src/domus/domain/inventory.py`](../backend/src/domus/domain/inventory.py) · [`backend/src/domus/application/inventory.py`](../backend/src/domus/application/inventory.py) · [`backend/src/domus/infrastructure/sqlite_inventory.py`](../backend/src/domus/infrastructure/sqlite_inventory.py) +- Tests: [`tests/backend/test_inventory_recurrence.py`](../tests/backend/test_inventory_recurrence.py) · [`tests/fixtures/sqlite/v16-inventory-source.sql`](../tests/fixtures/sqlite/v16-inventory-source.sql) +- User documentation: [`docs/product-vision.md`](../docs/product-vision.md) · [`docs/architecture.md`](../docs/architecture.md) · [`docs/operations.md`](../docs/operations.md) · [`docs/user-guide.md`](../docs/user-guide.md) · [`docs/contracts/home-assistant.md`](../docs/contracts/home-assistant.md) · [`docs/evidence/recurrence-calendar-qualification.md`](../docs/evidence/recurrence-calendar-qualification.md) ### `home-assistant-surface` — Home Assistant entities, services and integration diff --git a/specs/catalog.json b/specs/catalog.json index cb987981..baffec2d 100644 --- a/specs/catalog.json +++ b/specs/catalog.json @@ -677,18 +677,26 @@ ], "workflows": [], "entrypoints": [], - "code": [], - "tests": [], + "code": [ + "backend/src/domus/domain/inventory.py", + "backend/src/domus/application/inventory.py", + "backend/src/domus/infrastructure/sqlite_inventory.py" + ], + "tests": [ + "tests/backend/test_inventory_recurrence.py", + "tests/fixtures/sqlite/v16-inventory-source.sql" + ], "documentation": [ "docs/product-vision.md", "docs/architecture.md", "docs/operations.md", "docs/user-guide.md", - "docs/contracts/home-assistant.md" + "docs/contracts/home-assistant.md", + "docs/evidence/recurrence-calendar-qualification.md" ], "readiness": { "state": "draft", - "implementationEvidence": "absent", + "implementationEvidence": "partial", "blockingDecisions": "Unit/package policy; reservation/replenishment review; barcode library/device evidence; external lookup provider feasibility, terms and response contract. The owner confirmed barcode scope, adjustable material recording and pending regularization rather than negative stock for task material shortfalls on 2026-10-29. Adult participation approval and narrow task-material defaults are owner-confirmed; their domain implementation remains pending.", "copilotChangesAllowed": false } diff --git a/specs/household-inventory.md b/specs/household-inventory.md index b3639416..5b538d01 100644 --- a/specs/household-inventory.md +++ b/specs/household-inventory.md @@ -326,3 +326,130 @@ These are internal implementation steps within the first integrated release; the Primary sources: [Copilot standard](https://github.com/vypdev/copilot/blob/f5e5a4cf9a80248994469cd88ad55eecab5b95ca/specs/README.md), [original template](https://github.com/vypdev/copilot/blob/f5e5a4cf9a80248994469cd88ad55eecab5b95ca/specs/_template.md), and the linked [reference investigation](../docs/reference-investigation.md). Confirmed owner choices and unresolved proposals are separated in [decisions](../docs/decisions.md). [Issue #2](https://github.com/vypdev/domus/issues/2) tracks the documentation foundation. The [adoption note](../docs/copilot-adoption.md) records the current catalog evidence limitation. Optional future depth remains explicitly deferred in the product vision; the gateway's installation and MCP internals are outside Domus scope. + +## Inventory effects for reviewed recurring work + +- Status: Draft +- Owners: Domus maintainers and the Household Inventory capability +- Scope: Inventory persistence and task integration needed to verify the three remaining cross-domain recurrence obligations +- Source baseline: develop at 9b2495922c57a7fddef7c75885fd22acd6a7bd9a +- Related work: https://github.com/vypdev/domus/issues/57 and https://github.com/vypdev/domus/issues/23 + +### 1. Executive summary + +Give scheduled task material reservations, task-generated replenishment demand and physical movements a production Inventory owner. An accepted fixed recurrence replacement moves only compatible unfulfilled effects linked to the affected work. A task can record real material use. Reopening and independent recurrence invalidation preserve movements from retained work. Original command recovery and restored state preserve each decision once. + +### 2. Problem, current behavior, and evidence + +The selected baseline has task-owned material intents, scoped posting authority and a transaction-local Inventory port in `backend/src/domus/application/task_material_ports.py`. Production task composition in `backend/src/domus/composition/tasks.py` has no concrete Inventory port. Existing recurrence tests observe work, schedule and review state. The Points consumer from https://github.com/vypdev/domus/pull/58 provides real award and reversal observations. Inventory must provide its own positive reservation, demand and movement controls. This delta adds prospective behavior to `specs/household-inventory.md`. + +### 3. Actors, surfaces, and terminology + +An authorized household Inventory manager records a material reference and stock and establishes the reservation and demand needed by a task. Existing task material permission rules govern actual posting. A household scheduler uses the existing reviewed replacement command. The original work and its replacement are linked through the accepted operation. A reservation affects availability, demand records a replenishment need, and a movement affects physical stock. + +### 4. Goals, non-goals, and fixed invariants + +| Requirement | Behavior | +|---|---| +| inventory-recurrence-R1 | A reviewed fixed replacement binds the eligible Inventory effects to the review and transfers each compatible unfulfilled task reservation or demand to its exact linked replacement, with durable provenance and unchanged physical stock. | +| inventory-recurrence-R2 | Authorized task material posting appends an exact original-source movement in the real household ledger. Reopening and recurrence invalidation preserve material effects belonging to retained downstream work. | +| inventory-recurrence-R3 | The authoritative receipts, reservations, demands, movements and retained review state preserve household and source identity across contention, rollback, retry, restart, schema migration and compatible restoration. | + +Retain immutable physical history and stable source identities. Keep the wider Inventory catalog, shopping UI, external lookups, Gateway and release work with their owning milestones. + +### 5. Current versus proposed product journey + +An Inventory manager establishes the material, stock and open effects. The scheduler previews a replacement, confirms the same reviewed state and sees the existing linked batch receipt. Recovery uses the original command key. When an authorized member performs work and records actual material use, the ledger records the physical movement. Reopening source work leaves retained successors and their movements visible to the owning services. + +### 6. Functional behavior and state model + +Bind reviewed replacement to the exact current source effect identities and state. Move only compatible unfulfilled, slot-linked task effects to the matching replacement under the same transaction. Preserve original identity and provenance and keep manual extras outside the replacement. Incompatible effects remain with their source for review. A stale preview cannot silently apply new effects. Cancellation and planning do not change physical stock. + +Resolve material references in the household. Record actual consumption using exact quantities and stable task, cycle, line and source-operation identity. Preserve prior movement history. Insufficient stock uses existing pending regularization behavior. An explicit authorized correction links to its original posting. Recurrence invalidation is independent of correction and preserves completed or started work with its existing movements, reservations and demand. Points reverses only the actual award belonging to the reopened source cycle. + +### 7. User-facing configuration + +Use the existing household roles, task material policy and reviewed recurrence commands. Keep the existing browser settings, material unit values and completion rules. This slice adds no member configuration or new public task response contract. + +### 8. Clean Architecture design + +Inventory domain policy owns stock quantities, effect compatibility and linked movement rules. Inventory application services enforce authority and coordinate semantic persistence. Recurrence consumes a transaction-local interface to preview and apply reviewed effects. Task material settlement consumes its existing Inventory port. SQLite implements durable identities and shared transactions. Composition binds both deployment modes to the same implementation. Reuse the existing household permission checks and immutable task material values. + +### 9. UI/UX and content contract + +Use the existing reviewed plan, recovery, material status and retained work surfaces. Keep their English and Spanish behavior and keyboard access. The real Inventory controls are verified through scoped application calls. Broader Inventory presentation remains outside this increment. + +### 10. Failure, recovery, and cleanup + +The batch command, affected work, Inventory effects and durable receipt commit together. A write failure leaves the prior state and permits original-key retry. A lost response recovers the committed result. Independent SQLite writers serialize before a competing start or invalidation can create conflicting effects. Review retention and restoration preserve actual stock history and prohibit synthetic compensation. + +### 11. Security, permissions, and privacy + +Scope every effect, reference and movement to the household. Require existing Inventory permission for administrator commands and the existing task-scoped material authority for posting. Preserve actor and original source identity. Keep unrelated work and manual demand outside a scheduler's affected set. + +### 12. Observability and operational UX + +Integration tests observe exact old and new linked identities, operation receipt, real ledger movement identity and balance, and the existing retained-work review. Record exact test and check revisions in evidence. Keep historical qualification separate from executions on the new change. + +### 13. Compatibility, migration, rollout, and rollback + +If migration is needed, start from the actual schema 16 SQLite database and preserve its fixture. Its independently captured SQL has SHA-256 032954fc9be4ca2f96359c34df1e6e2a23e5562a481ddbc8fbcb9dcbbeebeb8b. Keep historical task, Points, household and recurrence records readable. Prove migration and rollback with the real fixture and restore through the supported snapshot flow. Use the same production composition in Ingress and standalone. + +### 14. Testing strategy and numeric budget + +Minimum 4 distinct cases in this delta. The existing recurrence and Inventory acceptance inventories retain their definitions and counts. + +| Area | Minimum distinct cases | Behaviors/risks covered | +|---|---:|---| +| Integration and recovery | 2 | Observable scenarios in the case inventory. | +| State and concurrency | 1 | Observable scenarios in the case inventory. | +| Adapters and persistence | 1 | Observable scenarios in the case inventory. | +| Total | 4 | Distinct inventory cases; repeated executions do not add cases. | + +| Case ID | Area | Requirements | Scenario | +|---|---|---|---| +| inventory-recurrence-C01 | Integration and recovery | inventory-recurrence-R1, inventory-recurrence-R3 | Given a fixed recurrence batch with real open task reservations and demand, a manual extra and observable physical stock, accept the reviewed replacement, lose the response and recover by its original key after restart. Observe each exact linked transfer once, unchanged physical stock and manual demand, and no extra transfer on recovery. | +| inventory-recurrence-C02 | Integration and recovery | inventory-recurrence-R2, inventory-recurrence-R3 | Given real Points awards and actual material consumption on downstream work, reopen the source cycle. Observe one Points reversal linked to the source award, unchanged downstream award, unchanged movement identity and balance, and no stock return. | +| inventory-recurrence-C03 | State and concurrency | inventory-recurrence-R1, inventory-recurrence-R2, inventory-recurrence-R3 | Given independently connected SQLite writers and downstream work that starts before invalidation, preserve work with its actual Inventory effects and at most one retained review. Roll back a deliberately failed reviewed transfer, reject stale review state, and restore a compatible snapshot without duplicate effects or synthetic compensation. | +| inventory-recurrence-C04 | Adapters and persistence | inventory-recurrence-R2, inventory-recurrence-R3 | Given the preserved schema 16 fixture, migrate and verify existing Points and task records. Run an authorized positive material posting through both deployment compositions, observe its exact persisted movement, and verify that insufficient stock and cross-household access do not create movements. | + +### 15. Documentation and discoverability + +Record the owner delta and implementation evidence with the retained contracts. Keep planned file navigation derived from the following inventory. + +[specs/household-inventory.md](household-inventory.md) · [specs/catalog.json](catalog.json) · [docs/evidence/recurrence-calendar-qualification.md](../docs/evidence/recurrence-calendar-qualification.md) · [backend/src/domus/application/fixed\_batch\_review.py](../backend/src/domus/application/fixed_batch_review.py) · [backend/src/domus/application/recurrence\_review.py](../backend/src/domus/application/recurrence_review.py) · [backend/src/domus/composition/tasks.py](../backend/src/domus/composition/tasks.py) · [backend/src/domus/infrastructure/sqlite.py](../backend/src/domus/infrastructure/sqlite.py) · [tests/fixtures/sqlite/v16-inventory-source.sql](../tests/fixtures/sqlite/v16-inventory-source.sql) + +| Path | Change | +|---|---| +| specs/household-inventory.md | update | +| specs/catalog.json | update | +| docs/evidence/recurrence-calendar-qualification.md | update | +| backend/src/domus/application/fixed_batch_review.py | update | +| backend/src/domus/application/recurrence_review.py | update | +| backend/src/domus/composition/tasks.py | update | +| backend/src/domus/infrastructure/sqlite.py | update | +| tests/fixtures/sqlite/v16-inventory-source.sql | create | + +### 16. Acceptance scenarios + +Use the actual persisted effects in the four case rows and exercise the linked retained recurrence scenarios from the parent issue. Distinguish a positive ledger witness from an asserted absence. Check both actual container architectures and browser compositions in CI for the reviewed revision. + +### 17. Requirements traceability + +| Requirement | Cases | +|---|---| +| inventory-recurrence-R1 | inventory-recurrence-C01, inventory-recurrence-C03 | +| inventory-recurrence-R2 | inventory-recurrence-C02, inventory-recurrence-C03, inventory-recurrence-C04 | +| inventory-recurrence-R3 | inventory-recurrence-C01, inventory-recurrence-C02, inventory-recurrence-C03, inventory-recurrence-C04 | + +### 18. Implementation sequence + +Preserve the selected fixture. Implement the minimal transaction-local Inventory domain, commands and SQLite mapping. Wire normal task posting and reviewed batch application. Add compound assertions for exact identity, permission, rollback, concurrency, receipt recovery and restoration. Record checked evidence after execution. + +### 19. Definition of Done + +All new case rows have actual persisted positive controls and pass on the same reviewed revision. The parent recurrence obligations can cite exact runs. Both compositions, English and Spanish, full global and per-file coverage, amd64 and ARM64, Copilot Verification and Bugbot pass. Catalog publication and runtime acceptance have separate evidence. + +### 20. References and decisions + +The Inventory owner is `specs/household-inventory.md`. The retained recurrence contracts are `specs/recurrence-calendar.md`, `specs/recurrence-execution-foundation.md` and `specs/recurrence-lifecycle-calendar.md`. Keep existing cases with their owners. The Points consumer in https://github.com/vypdev/domus/pull/58 supplies the authoritative award and reversal witness. This draft records planned behavior. diff --git a/tests/backend/test_activation_compatibility.py b/tests/backend/test_activation_compatibility.py index 7afdf39e..842321de 100644 --- a/tests/backend/test_activation_compatibility.py +++ b/tests/backend/test_activation_compatibility.py @@ -79,7 +79,7 @@ def test_real_activation_upgrades_only_target_from_frozen_source_and_checkpoint( selected = open_storage(root, "edge") try: with selected.database._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == 16 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 17 assert connection.execute("SELECT COUNT(*) FROM retained_operations").fetchone()[0] == ( 2 if version == 4 else 1 ) diff --git a/tests/backend/test_inventory_recurrence.py b/tests/backend/test_inventory_recurrence.py new file mode 100644 index 00000000..49b4bd18 --- /dev/null +++ b/tests/backend/test_inventory_recurrence.py @@ -0,0 +1,683 @@ +"""Compound recurrence acceptance with real Points, reservations and physical movements.""" + +import sqlite3 +from concurrent.futures import ThreadPoolExecutor +from contextlib import closing, contextmanager +from dataclasses import replace +from datetime import date +from hashlib import sha256 +from pathlib import Path +from threading import Event + +import pytest +from test_activation_compatibility import identity_at +from test_household_commands import Actor, Clock +from test_points_consumer import adult_id, consumer, cycle_of, running +from test_recurrence_creation import request as fixed_request +from test_recurrence_creation import setup as fixed_setup +from test_recurrence_review import reviewed +from test_relative_recurrence_creation import request as relative_request +from test_relative_recurrence_creation import setup as relative_setup +from test_task_commands import fixture +from test_task_http import PREFIX, create +from test_task_material_http import complete, selection +from test_task_material_settlement import request as settlement_request +from test_task_runtime import api as api + +from domus.application.fixed_batch_review import FixedReplacement +from domus.application.fixed_materialization import FixedMaintenance, MaintenanceScope +from domus.application.inventory import InventoryCommands, InventorySettlement +from domus.application.recurrence_review import RecurrenceReview, ReviewAction +from domus.application.recurrence_sources import RecurrenceSourceObservations +from domus.application.relative_lifecycle import RelativeLifecycle +from domus.application.relative_materialization import RelativeMaintenance +from domus.application.relative_recurrence import RelativeRecurrencePlanner +from domus.application.task_material_ports import MaterialPostingRequest +from domus.application.task_requests import ( + AssignTask, + CompleteTask, + CreateTask, + ReopenTask, + TransitionTask, +) +from domus.domain.errors import Conflict, DatabaseRejected, Forbidden, InvalidInput, StorageFailure +from domus.domain.identity import HumanIdentity +from domus.domain.inventory import EffectKind +from domus.domain.recurrence_rule_text import parse_fixed_pattern +from domus.domain.recurrence_rules import NominalDate +from domus.domain.storage import Installation +from domus.domain.task_material_values import ( + MaterialAction, + MaterialBinding, + MaterialQuantity, + MaterialSelection, + MaterialUsage, +) +from domus.domain.task_values import MaterialRecording, OccurrenceState, TaskContent, TaskOverrides +from domus.infrastructure import sqlite as storage +from domus.infrastructure.application_runtime import SecureIdentifiers +from domus.infrastructure.owned_storage import open_storage +from domus.infrastructure.sqlite import SQLiteAudit, SQLiteDatabase +from domus.infrastructure.sqlite_activation import SQLiteActivation +from domus.infrastructure.sqlite_inventory import SQLiteInventory +from domus.infrastructure.sqlite_restoration import SQLiteRestorations +from domus.infrastructure.sqlite_snapshots import SQLiteSnapshots +from domus.infrastructure.sqlite_tasks import SQLiteTasks + +BINDING = MaterialBinding("home", "binding", "soap", "litre", "utility-room", 1, 6, "Soap") +Q = MaterialQuantity +MATERIALS = (MaterialSelection(BINDING.reference_id, Q("2")),) + + +def _inventory(service, store): + return InventoryCommands(store, service.actor, service.clock, service.identifiers) + + +def _with_stock(service, store): + return replace( + service, + inventory_factory=lambda unit: InventorySettlement( + unit.inventory, service.clock, service.identifiers + ), + ) + + +def _commit(inventory, key, kind, quantity, occurrence=None): + receipt = inventory.commit_effect( + key, kind, BINDING.reference_id, Q(quantity), occurrence_id=occurrence + ) + return receipt.result.decode()["effect_id"] + + +def _stock(store): + with store.read() as unit: + balance = unit.inventory.balance("home", BINDING.reference_id) + reserved = unit.inventory.reserved("home", BINDING.reference_id) + with closing(sqlite3.connect(store.path)) as db: + movements = db.execute( + "SELECT movement_id,delta,corrects FROM inventory_movements ORDER BY position" + ).fetchall() + return balance, reserved, movements + + +def _effect(store, effect_id): + with store.read() as unit: + return unit.inventory.effect("home", effect_id) + + +@contextmanager +def _restore(store, root, tmp_path, snapshot): + archive = tmp_path / "archive" + target = tmp_path / "prepared" + SQLiteRestorations(store, archive, target, store.installation, Clock(), snapshot).prepare( + "restore" + ) + assert SQLiteActivation(root, store.installation, Clock(), target).activate().state == "active" + restored = open_storage(root, "edge") + try: + yield restored + finally: + restored.close() + + +def _fixed(tmp_path, replacement="FREQ=DAILY;COUNT=3;INTERVAL=2"): + creator, _, store, actor, ids = fixed_setup(tmp_path) + inventory = _inventory(creator, store) + inventory.receive("initial-stock", BINDING, Q("10")) + creator = _with_stock(creator, store) + start = NominalDate(date(2026, 3, 27)) + choice = fixed_request() + schedule = creator.create_fixed( + "fixed", + replace( + choice, + task=replace(choice.task, materials=MATERIALS), + pattern=parse_fixed_pattern("FREQ=DAILY;COUNT=3", start), + ), + ).result.decode()["schedule_id"] + scope = MaintenanceScope(store.installation, "home") + planner = RelativeRecurrencePlanner(creator.planner.times) + maintenance = FixedMaintenance(store, scope, creator.planner, creator.clock, ids) + old = tuple( + maintenance.step(schedule, NominalDate(date(2026, 3, 31))).occurrence_id for _ in range(3) + ) + review = RecurrenceReview( + store, store.installation, actor, actor.current, creator.clock, ids, planner + ) + selection = FixedReplacement( + schedule, + 1, + parse_fixed_pattern(replacement, NominalDate(date(2026, 3, 28))), + "Review linked Inventory commitments", + ) + return store, inventory, review, selection, old + + +def test_reviewed_batch_recovers_original_stock_reservations_and_demand(tmp_path): + root = tmp_path / "source" + root.mkdir(mode=0o700) + store, inventory, review, selection, (_, first, second) = _fixed(root) + identity_at(root, store.installation) + reservation = _commit(inventory, "hold", EffectKind.RESERVATION, "2", first) + demand = _commit(inventory, "need", EffectKind.DEMAND, "3", second) + extra = _commit(inventory, "manual", EffectKind.DEMAND, "1") + original_effects = {key: _effect(store, key) for key in (reservation, demand, extra)} + original_stock = _stock(store) + with store.read() as unit: + assert unit.inventory.effects("home", ()) == () + preview, change = reviewed(review, selection) + assert { + row["effect_id"] for row in preview.result.decode()["plan"]["source"]["inventory_effects"] + } == {reservation, demand} + accepted = review.apply("replace", change) + # The initial response is unavailable to the restarted reviewer. Recover by the original key. + restarted = replace(review, transactions=SQLiteDatabase(store.path, store.installation)) + recovered = restarted.original(ReviewAction.APPLY, "replace") + assert recovered == accepted == restarted.apply("replace", change) + result = recovered.result.decode() + assert set(result["replacements"]) == {first, second} + assert result["inventory_retained"] == [] + links = {item["id"]: (item["from"], item["to"]) for item in result["inventory_transferred"]} + assert links == { + reservation: (first, result["replacements"][first]), + demand: (second, result["replacements"][second]), + } + for effect_id, (_, replacement) in links.items(): + assert _effect(store, effect_id) == replace( + original_effects[effect_id], occurrence_id=replacement, revision=2 + ) + assert _effect(store, extra) == original_effects[extra] + assert original_stock[0:2] == (10_000_000, 2_000_000) + assert _stock(store) == original_stock + snapshot = SQLiteSnapshots(store, tmp_path / "archive", store.installation, Clock()).create( + "batch" + ) + with _restore(store, root, tmp_path, snapshot) as restored: + restored_review = replace(review, transactions=restored.database) + assert restored_review.apply("replace", change) == accepted + assert _effect(restored.database, reservation) == _effect(store, reservation) + assert _effect(restored.database, demand) == _effect(store, demand) + assert _effect(restored.database, extra) == original_effects[extra] + assert _stock(restored.database) == original_stock + + +def test_reviewed_batch_inventory_change_and_rollback_are_atomic(tmp_path, monkeypatch): + store, inventory, review, selection, (_, first, second) = _fixed( + tmp_path, replacement="FREQ=DAILY;COUNT=1" + ) + _, stale = reviewed(review, selection) + kept = _commit(inventory, "unpaired", EffectKind.DEMAND, "2", second) + moved = _commit(inventory, "paired", EffectKind.RESERVATION, "2", first) + before = [_effect(store, key) for key in (kept, moved)] + with pytest.raises(Conflict, match="recurrence_review_stale"): + review.apply("stale", stale) + _, current = reviewed(review, selection, "current-preview") + append = SQLiteAudit.append + + def fail(unit, entry): + append(unit, entry) + if entry.command.action == "recurrence.review.apply": + raise StorageFailure("after_inventory_transfer") + + with monkeypatch.context() as patch: + patch.setattr(SQLiteAudit, "append", fail) + with pytest.raises(StorageFailure, match="after_inventory_transfer"): + review.apply("replacement", current) + assert [_effect(store, key) for key in (kept, moved)] == before + with store.read() as unit: + assert unit.recurrence.schedule("home", selection.schedule_id).revision == 1 + assert unit.tasks.occurrence("home", first).state is OccurrenceState.AVAILABLE + result = review.apply("replacement", current).result.decode() + assert result["inventory_retained"] == [kept] + assert result["inventory_transferred"] == [ + {"id": moved, "from": first, "to": result["replacements"][first]} + ] + assert _effect(store, kept) == before[0] + + +def _relative(root): + creator, tasks, store, actor, ids = relative_setup(root) + inventory = _inventory(creator, store) + inventory.receive("initial-stock", BINDING, Q("10")) + tasks = _with_stock(tasks, store) + creator = _with_stock(creator, store) + selection = relative_request() + schedule = creator.create( + "relative", + replace( + selection, + task=replace( + selection.task, overrides=TaskOverrides(point_value_minor=125), materials=MATERIALS + ), + ), + ).result.decode()["schedule_id"] + scope = MaintenanceScope(store.installation, "home") + source = RecurrenceSourceObservations(store, scope) + lifecycle = RelativeLifecycle( + store, scope, RelativeRecurrencePlanner(creator.times), Clock(), ids + ) + parent = ( + RelativeMaintenance(store, scope, creator.times, Clock(), ids) + .initial(schedule) + .occurrence_id + ) + member = adult_id(store, tasks) + first = _perform(store, tasks, parent, member, "source", "0.25", 90) + (completed,) = source.ingest().items + successor = lifecycle.consume(schedule, completed.event.event_key).occurrence_id + return store, inventory, tasks, source, lifecycle, schedule, parent, first, successor, member + + +def _perform(store, tasks, occurrence, member, key, amount, at): + with store.read() as unit: + work = unit.tasks.occurrence("home", occurrence) + line = work.definition_snapshot.materials[0] + return tasks.complete( + key, + CompleteTask( + occurrence, work.revision, (member,), at, (MaterialUsage(line.line_id, Q(amount)),) + ), + ) + + +def test_source_reopening_keeps_completed_successor_and_real_stock_after_restore(tmp_path): + root = tmp_path / "source" + root.mkdir(mode=0o700) + store, inventory, tasks, source, lifecycle, rule, parent, first, successor, member = _relative( + root + ) + identity_at(root, store.installation) + reserved = _commit(inventory, "hold", EffectKind.RESERVATION, "2", successor) + downstream = _perform(store, tasks, successor, member, "successor", "1.125", 95) + points = consumer(store) + assert points.tick(running) == 2 + original_cycle, downstream_cycle = cycle_of(first), cycle_of(downstream) + (award,) = points.ledger("home", original_cycle) + (downstream_award,) = points.ledger("home", downstream_cycle) + assert award.shares == downstream_award.shares == ((member, 125),) + stock = _stock(store) + assert stock[:2] == (8_625_000, 875_000) + assert len(stock[2]) == 3 and stock[2][-1][1:] == (-1_125_000, None) + with store.read() as unit: + recorded = unit.task_materials.list("home", downstream_cycle)[0] + movement = unit.inventory.movement_by_id("home", recorded.posting.movement_id) + assert movement.posting == recorded.posting + assert stock[2][-1][0] == movement.movement_id + reopened = tasks.reopen("reopen", ReopenTask(parent, 2, original_cycle, "Review original work")) + close = next( + item.event for item in source.ingest().items if item.event.event_id == reopened.operation_id + ) + result = lifecycle.consume(rule, close.event_key) + assert result.status == "review" and lifecycle.consume(rule, close.event_key) == result + assert points.tick(running) == 1 and points.tick(running) == 0 + assert points.ledger("home", original_cycle) == ( + award, + award.reverse(reopened.operation_id, 100), + ) + assert points.ledger("home", downstream_cycle) == (downstream_award,) + assert _stock(store) == stock + with store.read() as unit: + assert unit.tasks.occurrence("home", successor).state is OccurrenceState.COMPLETED + snapshot = SQLiteSnapshots(store, tmp_path / "archive", store.installation, Clock()).create( + "downstream" + ) + with _restore(store, root, tmp_path, snapshot) as restored: + assert _stock(restored.database) == stock + assert _effect(restored.database, reserved).remaining == 875_000 + ledger = consumer(restored.database) + assert ledger.ledger("home", downstream_cycle) == (downstream_award,) + assert ledger.ledger("home", original_cycle) == points.ledger("home", original_cycle) + assert ledger.tick(running) == 0 + resumed = replace(lifecycle, transactions=restored.database) + assert resumed.consume(rule, close.event_key) == result + with restored.database.read() as unit: + assert unit.tasks.occurrence("home", successor).state is OccurrenceState.COMPLETED + + +def test_started_work_wins_independent_invalidation_and_preserves_inventory(tmp_path, monkeypatch): + root = tmp_path / "source" + root.mkdir(mode=0o700) + store, inventory, tasks, source, lifecycle, rule, parent, first, successor, member = _relative( + root + ) + identity_at(root, store.installation) + points = consumer(store) + cycle = cycle_of(first) + assert points.tick(running) == 1 + (award,) = points.ledger("home", cycle) + reserved = _commit(inventory, "hold", EffectKind.RESERVATION, "2", successor) + demand = _commit(inventory, "demand", EffectKind.DEMAND, "3", successor) + expected = [_effect(store, key) for key in (reserved, demand)] + stock = _stock(store) + assert stock[:2] == (9_750_000, 2_000_000) + tasks.assign("assign", AssignTask(successor, 1, (member,))) + reopened = tasks.reopen("reopen", ReopenTask(parent, 2, cycle, "Review original work")) + assert points.tick(running) == 1 + expected_points = (award, award.reverse(reopened.operation_id, 100)) + (reopening,) = source.ingest().items + started, racing = Event(), Event() + save = SQLiteTasks.save_occurrence + + def hold(self, work, revision): + save(self, work, revision) + if work.occurrence_id == successor and work.state is OccurrenceState.IN_PROGRESS: + started.set() + assert racing.wait(3) + + class Independent(SQLiteDatabase): + @contextmanager + def write(self): + racing.set() + with super().write() as unit: + yield unit + + monkeypatch.setattr(SQLiteTasks, "save_occurrence", hold) + invalidator = replace( + lifecycle, transactions=Independent(store.path, store.installation, busy_timeout=5) + ) + with ThreadPoolExecutor(max_workers=2) as pool: + start = pool.submit( + tasks.transition, "start", TransitionTask(successor, 2, OccurrenceState.IN_PROGRESS) + ) + assert started.wait(3) + close = pool.submit(invalidator.consume, rule, reopening.event.event_key) + start.result() + result = close.result() + assert ( + result.status == "review" and invalidator.consume(rule, reopening.event.event_key) == result + ) + with store.read() as unit: + points_position = unit.points.position("home") + assert unit.tasks.occurrence("home", successor).state is OccurrenceState.IN_PROGRESS + assert ( + sum(item.event_id == result.receipt.operation_id for item in unit.outbox.pending()) == 1 + ) + assert [_effect(store, key) for key in (reserved, demand)] == expected + assert _stock(store) == stock + assert points.tick(running) == 0 + assert points.ledger("home", cycle) == expected_points + snapshot = SQLiteSnapshots(store, tmp_path / "archive", store.installation, Clock()).create( + "started-and-reviewed" + ) + with _restore(store, root, tmp_path, snapshot) as restored: + database = restored.database + assert ( + replace(lifecycle, transactions=database).consume(rule, reopening.event.event_key) + == result + ) + assert _stock(database) == stock + assert [_effect(database, key) for key in (reserved, demand)] == expected + ledger = consumer(database) + assert ledger.tick(running) == 0 and ledger.ledger("home", cycle) == expected_points + with database.read() as unit: + assert unit.tasks.occurrence("home", successor).state is OccurrenceState.IN_PROGRESS + assert unit.points.position("home") == points_position + assert ( + sum( + entry.operation_id == result.receipt.operation_id + for entry in unit.audit.entries("home") + ) + == 1 + ) + + +def test_genuine_schema_16_inventory_migration_preserves_points_and_is_atomic( + tmp_path, monkeypatch +): + source = Path(__file__).parents[1] / "fixtures/sqlite/v16-inventory-source.sql" + assert ( + sha256(source.read_bytes()).hexdigest() + == "032954fc9be4ca2f96359c34df1e6e2a23e5562a481ddbc8fbcb9dcbbeebeb8b" + ) + database = tmp_path / "prior.sqlite3" + with closing(sqlite3.connect(database, autocommit=True)) as connection: + connection.executescript(source.read_text()) + assert connection.execute("PRAGMA user_version").fetchone() == (16,) + installation = Installation( + *connection.execute("SELECT instance_id,channel FROM installation").fetchone() + ) + before = connection.execute( + "SELECT * FROM points_task_receipts ORDER BY position" + ).fetchall() + saved = database.read_bytes() + store = SQLiteDatabase(database, installation) + with monkeypatch.context() as patch: + patch.setattr( + storage, "INVENTORY_STATEMENTS", (*storage.INVENTORY_STATEMENTS, "invalid SQL") + ) + with pytest.raises(StorageFailure): + store.initialize(require_existing=True) + assert database.read_bytes() == saved + store.initialize(require_existing=True) + with store.read() as unit: + eligible, pending = sorted(unit.tasks.cycles("home"), key=lambda cycle: cycle.verification) + assert unit.points.ledger("home", eligible.cycle_id)[0].shares[0][1] == 300 + assert unit.points.ledger("home", pending.cycle_id) == () + assert unit.inventory.material("home", BINDING.reference_id) is None + with closing(sqlite3.connect(database)) as connection: + assert ( + connection.execute("SELECT * FROM points_task_receipts ORDER BY position").fetchall() + == before + ) + assert connection.execute("PRAGMA user_version").fetchone() == (17,) + + +def test_real_task_material_posts_in_both_compositions_and_keeps_shortage_pending(api): + with api.store.read() as unit: + (admin,) = unit.members.list("home") + actor = Actor() + actor.human = HumanIdentity(admin.ha_user_id, True, True, False) + inventory = InventoryCommands(api.store, actor, Clock(), SecureIdentifiers()) + stock = inventory.receive("receive", BINDING, Q("1.125")) + assert inventory.receive("receive", BINDING, Q("1.125")) == stock + created = create(api, materials=[selection("0.25")]) + occurrence = created["result"]["occurrence_id"] + line = api.client.get(PREFIX + "/occurrences/" + occurrence).json()["work"][ + "definition_snapshot" + ]["materials"][0] + actual = {"material_usages": [{"line_id": line["line_id"], "quantity": "0.125001"}]} + response = complete(api, created, actual) + assert response.status_code == 200, response.text + outcome = response.json()["result"]["materials"][0] + assert outcome["state"] == "posted" + assert complete(api, created, actual).json() == response.json() + assert _stock(api.store) == ( + 999_999, + 0, + [ + (stock.result.decode()["movement_id"], 1_125_000, None), + (outcome["movement_id"], -125_001, None), + ], + ) + other = create(api, materials=[selection("1")], key="next-work") + other_id = other["result"]["occurrence_id"] + line = api.client.get(PREFIX + "/occurrences/" + other_id).json()["work"][ + "definition_snapshot" + ]["materials"][0] + result = complete( + api, other, {"material_usages": [{"line_id": line["line_id"], "quantity": "1"}]}, "shortage" + ) + assert result.status_code == 200, result.text + assert result.json()["result"]["materials"][0]["state"] == "pending_regularization" + assert len(_stock(api.store)[2]) == 2 + with pytest.raises(Forbidden, match="permission_denied"): + replace(inventory, household_id="another").receive( + "foreign", replace(BINDING, household_id="another"), Q("1") + ) + assert len(_stock(api.store)[2]) == 2 + + +def test_manager_commands_cannot_overbook_or_create_unbound_effects(tmp_path): + tasks, store, actor, _ = fixture(tmp_path) + inventory = _inventory(tasks, store) + with pytest.raises(InvalidInput, match="invalid_inventory_receipt"): + inventory.receive("zero", BINDING, Q("0")) + with pytest.raises(InvalidInput, match="invalid_material_reference"): + _commit(inventory, "unknown", EffectKind.DEMAND, "1") + inventory.receive("receive", BINDING, Q("999999999999.999999")) + with pytest.raises(Conflict, match="inventory_binding_changed"): + inventory.receive("different-unit", replace(BINDING, unit_id="piece"), Q("1")) + with pytest.raises(Conflict, match="inventory_stock_capacity"): + inventory.receive("over-capacity", BINDING, Q("0.000001")) + with pytest.raises(InvalidInput, match="invalid_inventory_effect"): + _commit(inventory, "no-occurrence", EffectKind.RESERVATION, "1") + with pytest.raises(InvalidInput, match="invalid_material_reference"): + _commit(inventory, "unknown-work", EffectKind.DEMAND, "1", "missing") + plain = tasks.create("plain", CreateTask(TaskContent("No materials"))).result.decode() + with pytest.raises(InvalidInput, match="invalid_material_reference"): + _commit(inventory, "unlinked-line", EffectKind.DEMAND, "1", plain["occurrence_id"]) + tasks = _with_stock(tasks, store) + linked = tasks.create( + "with-materials", CreateTask(TaskContent("Wash"), materials=MATERIALS) + ).result.decode()["occurrence_id"] + reservation = _commit(inventory, "hold", EffectKind.RESERVATION, "1", linked) + with pytest.raises(Conflict, match="inventory_insufficient_stock"): + _commit(inventory, "too-much", EffectKind.RESERVATION, "999999999999.999999", linked) + actor.human = HumanIdentity("ha_child", False, True, False) + with pytest.raises(Forbidden, match="permission_denied"): + _commit(inventory, "restricted", EffectKind.DEMAND, "1") + with store.read() as unit: + assert unit.inventory.effect("foreign", reservation) is None + with closing(sqlite3.connect(store.path)) as connection: + effects = connection.execute( + "SELECT effect_id,occurrence_id,kind,remaining FROM inventory_effects" + ).fetchall() + assert effects == [(reservation, linked, EffectKind.RESERVATION.value, 1_000_000)] + + +def _separate_material(tmp_path): + tasks, store, _, _ = fixture(tmp_path) + inventory = _inventory(tasks, store) + received = inventory.receive("receive", BINDING, Q("2")) + tasks = _with_stock(tasks, store) + receipt = tasks.create( + "task", + CreateTask( + TaskContent("Wash"), + overrides=TaskOverrides(material_recording=MaterialRecording.SEPARATE), + materials=MATERIALS, + ), + ) + oid = receipt.result.decode()["occurrence_id"] + hold = _commit(inventory, "hold", EffectKind.RESERVATION, "2", oid) + result = _perform(store, tasks, oid, adult_id(store, tasks), "perform", "1.125", 90) + cid = cycle_of(result) + with store.read() as unit: + pending = unit.task_materials.list("home", cid)[0] + return tasks, inventory, store, hold, pending, received.result.decode()["movement_id"] + + +def test_inventory_posts_and_corrects_one_exact_source_with_rollback_and_retry( + tmp_path, monkeypatch +): + tasks, inventory, store, hold, pending, _ = _separate_material(tmp_path) + before = _stock(store) + append = SQLiteInventory.append + + def fail(records, movement, balance): + append(records, movement, balance) + raise StorageFailure("after_stock") + + with monkeypatch.context() as patch: + patch.setattr(SQLiteInventory, "append", fail) + with pytest.raises(StorageFailure, match="after_stock"): + tasks.settle_material("post", settlement_request(pending)) + assert _stock(store) == before + assert _effect(store, hold).remaining == 2_000_000 + first = tasks.settle_material("post", settlement_request(pending)) + assert tasks.settle_material("post", settlement_request(pending)) == first + with store.write() as unit: + confirmed = unit.task_materials.get("home", pending.intent_id) + settlement = InventorySettlement(unit.inventory, tasks.clock, tasks.identifiers) + source = MaterialPostingRequest(pending, pending.recorded_by) + assert settlement.settle(source).posting == confirmed.posting + with pytest.raises(Conflict, match="inventory_effect_stale"): + unit.inventory.update_effect(unit.inventory.effect("home", hold), 1) + assert _stock(store)[:2] == (875_000, 875_000) + assert _effect(store, hold).revision == 2 + inventory.receive("restock", BINDING, Q("1")) + revised = tasks.settle_material( + "correct", + settlement_request(confirmed, MaterialAction.CORRECT, quantity="1", reason="Actual use"), + ) + assert revised.result.decode()["material"]["state"] == "corrected" + with store.read() as unit: + posted = unit.task_materials.get("home", pending.intent_id).posting + movement = unit.inventory.movement_by_id("home", posted.movement_id) + assert movement.corrects == confirmed.posting.movement_id + assert movement.reason == "Actual use" and movement.delta == 125_000 + assert _stock(store)[:2] == (2_000_000, 875_000) + SQLiteSnapshots(store, tmp_path / "verified", store.installation, Clock()).create("corrected") + with store.write() as unit: + missing = replace(confirmed.posting, movement_id="missing") + damaged = replace(confirmed.correct(Q("0.5"), "Check", 100), posting=missing) + settlement = InventorySettlement(unit.inventory, tasks.clock, tasks.identifiers) + with pytest.raises(StorageFailure, match="invalid_inventory_posting_source"): + settlement.settle(MaterialPostingRequest(damaged, pending.recorded_by)) + + +def test_bound_stock_cannot_be_spent_by_other_work_or_after_binding_changes(tmp_path): + tasks, _, store, hold, pending, _ = _separate_material(tmp_path) + other = tasks.create( + "other", + CreateTask( + TaskContent("Another wash"), + overrides=TaskOverrides(material_recording=MaterialRecording.REVIEW_ON_COMPLETION), + materials=MATERIALS, + ), + ) + result = _perform( + store, + tasks, + other.result.decode()["occurrence_id"], + adult_id(store, tasks), + "blocked", + "1", + 90, + ) + assert result.result.decode()["materials"][0]["pending_reason"] == "insufficient_stock" + assert _stock(store)[:2] == (2_000_000, 2_000_000) + assert _effect(store, hold).remaining == 2_000_000 + with closing(sqlite3.connect(store.path, autocommit=True)) as db: + db.execute("UPDATE inventory_materials SET unit_id='piece'") + result = tasks.settle_material("post", settlement_request(pending)) + assert result.result.decode()["material"]["pending_reason"] == "inventory_binding_changed" + assert len(_stock(store)[2]) == 1 + + +@pytest.mark.parametrize( + "damage", + [ + "posting-time", + "posting-delta", + "wrong-correction-source", + "physical-balance", + "reserve-overdrawn", + "negative-ledger", + ], +) +def test_snapshot_rejects_inconsistent_inventory_records(tmp_path, damage): + tasks, _, store, _, pending, receipt_id = _separate_material(tmp_path) + tasks.settle_material("post", settlement_request(pending)) + with store.read() as unit: + initial = unit.task_materials.get("home", pending.intent_id) + tasks.settle_material( + "correct", + settlement_request(initial, MaterialAction.CORRECT, quantity="1", reason="Adjusted"), + ) + with closing(sqlite3.connect(store.path, autocommit=True)) as db: + statements = { + "posting-time": ("UPDATE inventory_movements SET created_at=99 WHERE position=2", ()), + "posting-delta": ("UPDATE inventory_movements SET delta=-1 WHERE position=2", ()), + "wrong-correction-source": ( + "UPDATE inventory_movements SET corrects=? WHERE position=3", + (receipt_id,), + ), + "physical-balance": ("UPDATE inventory_materials SET balance=1", ()), + "reserve-overdrawn": ("UPDATE inventory_effects SET remaining=3000000", ()), + "negative-ledger": ("UPDATE inventory_movements SET delta=1 WHERE position=1", ()), + } + statement, arguments = statements[damage] + db.execute(statement, arguments) + with pytest.raises(DatabaseRejected, match="invalid_snapshot_records"): + SQLiteSnapshots(store, tmp_path / "corrupt", store.installation, Clock()).create("damaged") diff --git a/tests/backend/test_recurrence_frontier.py b/tests/backend/test_recurrence_frontier.py index 7a4c3f26..319ee65b 100644 --- a/tests/backend/test_recurrence_frontier.py +++ b/tests/backend/test_recurrence_frontier.py @@ -61,7 +61,7 @@ def test_frontier_commits_reopens_and_never_creates_task_or_business_evidence(tm SQLiteSnapshots(store, tmp_path / "checkpoint", store.installation, Clock()) .create("frontier") .schema_version - == 16 + == 17 ) diff --git a/tests/backend/test_recurrence_lifecycle_migration.py b/tests/backend/test_recurrence_lifecycle_migration.py index 9278b73f..4507dc55 100644 --- a/tests/backend/test_recurrence_lifecycle_migration.py +++ b/tests/backend/test_recurrence_lifecycle_migration.py @@ -57,7 +57,7 @@ def test_supported_schema9_keeps_fixed_work_pristine_relative_progress_and_priva assert private.routine_participation_summaries is False and private.revision == 2 assert facts(store.path, tables) == original with restarted._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == 16 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 17 with restarted.read() as unit: assert unit.recurrence.relative_inbox_after("home") == 0 @@ -81,7 +81,7 @@ def test_independent_snapshot_inspection_after_migration_preserves_every_origina store, archive, store.installation, SimpleNamespace(now=lambda: 1800000000000) ) checkpoint = snapshots.create("source-nine") - assert checkpoint.schema_version == 16 and snapshots.inspect() == checkpoint + assert checkpoint.schema_version == 17 and snapshots.inspect() == checkpoint assert facts(archive / "domus.sqlite3", tables) == original assert store.path.read_bytes() == before @@ -136,7 +136,7 @@ def test_genuine_schema11_horizon_migration_preserves_private_preferences_and_hi preference = unit.calendar_preferences.get("home", member.member_id) assert preference.week_start is WeekStart.SUNDAY and preference.revision == 2 with restarted._connection() as connection: - assert _verify_database(connection, restarted, previous=False) == 16 + assert _verify_database(connection, restarted, previous=False) == 17 assert facts(store.path, tables) == before diff --git a/tests/backend/test_restore_source.py b/tests/backend/test_restore_source.py index 590418eb..0c731a27 100644 --- a/tests/backend/test_restore_source.py +++ b/tests/backend/test_restore_source.py @@ -19,7 +19,7 @@ def test_bare_source_and_managed_generation_source_are_explicit_and_roundtrip(tm bare_root.mkdir(mode=0o700) adapter, store, _, _ = restoration_fixture(bare_root) result = adapter.prepare("restore-bare") - assert result.source == RestoreSource(store.installation, 16, None, None) + assert result.source == RestoreSource(store.installation, 17, None, None) assert result.document().decode()["format_version"] == 2 assert PreparedRestoration.from_value(result.document().decode()) == result root, slot, selection = generation_fixture(tmp_path) @@ -39,7 +39,7 @@ def test_bare_source_and_managed_generation_source_are_explicit_and_roundtrip(tm ).prepare("restore-generation") assert prepared.source.generation_id == selection.generation_id assert prepared.source.identity_sha256 == selection.document().fingerprint - assert prepared.source.schema_version == 16 + assert prepared.source.schema_version == 17 assert PreparedRestoration.from_value(prepared.document().decode()) == prepared finally: storage.close() diff --git a/tests/backend/test_sqlite_history.py b/tests/backend/test_sqlite_history.py index 84e13fee..f1ce20a6 100644 --- a/tests/backend/test_sqlite_history.py +++ b/tests/backend/test_sqlite_history.py @@ -81,7 +81,7 @@ def test_frozen_old_schema_migrates_without_losing_existing_evidence(tmp_path, v store = SQLiteDatabase(path, Installation("047cc6fb-dfb0-4fa4-b3c3-e0fe54d116b6", "edge")) store.initialize() with store._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 16 + assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 17 assert connection.execute("SELECT count(*) FROM retained_operations").fetchone()[0] == len( before.get("retained_operations", []) ) diff --git a/tests/backend/test_sqlite_identity.py b/tests/backend/test_sqlite_identity.py index 9edf7652..85bb0185 100644 --- a/tests/backend/test_sqlite_identity.py +++ b/tests/backend/test_sqlite_identity.py @@ -177,7 +177,7 @@ def test_v1_upgrade_preserves_household_receipts_audit_and_pending_outbox(tmp_pa unit.members.save(member(), 0) unit.policies.save(policy(), 0) with closing(sqlite3.connect(path)) as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == 16 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 17 assert connection.execute("PRAGMA foreign_key_check").fetchall() == [] diff --git a/tests/backend/test_sqlite_member_profiles.py b/tests/backend/test_sqlite_member_profiles.py index 60a1a315..91cead59 100644 --- a/tests/backend/test_sqlite_member_profiles.py +++ b/tests/backend/test_sqlite_member_profiles.py @@ -302,7 +302,7 @@ def test_real_historical_input_upgrade_preserves_every_original_table_and_adds_d current.household_id, current.member_id ) == MemberPreferences(current.member_id, current.household_id) with store._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == 16 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 17 assert connection.execute("PRAGMA foreign_key_check").fetchall() == [] @@ -350,7 +350,7 @@ def test_snapshot_independently_preserves_both_profiles_without_changing_member_ archive = tmp_path / "snapshot" snapshots = SQLiteSnapshots(store, archive, store.installation, Clock()) checkpoint = snapshots.create("original") - assert checkpoint.schema_version == 16 and snapshots.inspect() == checkpoint + assert checkpoint.schema_version == 17 and snapshots.inspect() == checkpoint with SQLiteDatabase(archive / "domus.sqlite3", store.installation).read() as unit: assert unit.presentations.get("home", "member_1") == public assert unit.preferences.get("home", "member_1") == private diff --git a/tests/backend/test_sqlite_recovery.py b/tests/backend/test_sqlite_recovery.py index 60b68f77..b03e867b 100644 --- a/tests/backend/test_sqlite_recovery.py +++ b/tests/backend/test_sqlite_recovery.py @@ -160,7 +160,7 @@ def test_compatible_migration_preserves_identity_history_and_adds_empty_recovery assert unit.outbox.pending()[0].event_id == "old-operation" assert unit.recoveries.pending("home", 3000) == () with closing(sqlite3.connect(path)) as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 16 + assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 17 def test_failed_v2_upgrade_rolls_back_all_new_schema_and_replay_data( diff --git a/tests/backend/test_sqlite_recurrence.py b/tests/backend/test_sqlite_recurrence.py index 3ced2124..fa637cc2 100644 --- a/tests/backend/test_sqlite_recurrence.py +++ b/tests/backend/test_sqlite_recurrence.py @@ -233,7 +233,7 @@ def test_normal_transactions_refuse_schema7_until_explicit_atomic_upgrade(tmp_pa with store.read() as unit: assert unit.recurrence.schedules("home") == () with store._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == 16 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 17 assert tuple(connection.execute("SELECT * FROM receipts ORDER BY operation_id")) == original assert connection.execute("PRAGMA foreign_key_check").fetchall() == [] diff --git a/tests/backend/test_sqlite_recurrence_integrity.py b/tests/backend/test_sqlite_recurrence_integrity.py index 9ec54fc8..ac60f77e 100644 --- a/tests/backend/test_sqlite_recurrence_integrity.py +++ b/tests/backend/test_sqlite_recurrence_integrity.py @@ -37,7 +37,7 @@ def test_checkpoint_verifies_and_reopens_real_rule_progress_slot_and_original_re snapshots = SQLiteSnapshots(store, tmp_path / "snapshot", store.installation, Clock()) before = store.path.read_bytes() checkpoint = snapshots.create("recurrence") - assert checkpoint.schema_version == 16 and snapshots.inspect() == checkpoint + assert checkpoint.schema_version == 17 and snapshots.inspect() == checkpoint assert store.path.read_bytes() == before reopened = SQLiteDatabase(tmp_path / "snapshot/domus.sqlite3", store.installation) with reopened.read() as unit: @@ -264,7 +264,7 @@ def test_pattern_edit_requires_matching_progress_and_preserves_existing_slot_sna SQLiteSnapshots(store, tmp_path / "edited", store.installation, Clock()) .create("edited") .schema_version - == 16 + == 17 ) diff --git a/tests/backend/test_sqlite_snapshots.py b/tests/backend/test_sqlite_snapshots.py index 70921fb7..01c3b3dc 100644 --- a/tests/backend/test_sqlite_snapshots.py +++ b/tests/backend/test_sqlite_snapshots.py @@ -37,7 +37,7 @@ def test_snapshot_contains_verified_private_identity_checkpoint_and_all_atomic_r before = store.path.read_bytes() result = snapshots.create("snapshot-1") assert ( - result.schema_version == 16 + result.schema_version == 17 and result.captured_at == 2000 and result.last_committed_at == 100 ) diff --git a/tests/backend/test_sqlite_task_integrity.py b/tests/backend/test_sqlite_task_integrity.py index 3fa5d7c8..0bc49c76 100644 --- a/tests/backend/test_sqlite_task_integrity.py +++ b/tests/backend/test_sqlite_task_integrity.py @@ -158,7 +158,7 @@ def test_actual_unit_snapshot_and_reopen_keep_task_cycles_and_one_atomic_receipt before = store.path.read_bytes() snapshots = SQLiteSnapshots(store, tmp_path / "snapshot", store.installation, Clock()) checkpoint = snapshots.create("tasks") - assert checkpoint.schema_version == 16 and snapshots.inspect() == checkpoint + assert checkpoint.schema_version == 17 and snapshots.inspect() == checkpoint assert store.path.read_bytes() == before copy = SQLiteDatabase(tmp_path / "snapshot/domus.sqlite3", store.installation) with copy.read() as unit: @@ -433,5 +433,5 @@ def test_schema4_upgrade_failure_preserves_the_exact_old_database_and_history( assert unit.tasks.policy("home") is None and unit.tasks.definitions("home") == () assert unit.receipts.get_operation("home", "human", "operation-a").historical with store._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == 16 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 17 assert connection.execute("SELECT count(*) FROM retained_operations").fetchone()[0] == 2 diff --git a/tests/backend/test_sqlite_task_materials.py b/tests/backend/test_sqlite_task_materials.py index 720637f3..52197efe 100644 --- a/tests/backend/test_sqlite_task_materials.py +++ b/tests/backend/test_sqlite_task_materials.py @@ -58,7 +58,7 @@ def test_original_schema5_migration_preserves_history_and_legacy_request_fingerp store = SQLiteDatabase(path, Installation("047cc6fb-dfb0-4fa4-b3c3-e0fe54d116b6", "edge")) store.initialize(require_existing=True) with store._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 16 + assert connection.execute("PRAGMA user_version").fetchone()[0] == SCHEMA_VERSION == 17 for table, rows in before.items(): assert [tuple(row) for row in connection.execute(f"SELECT * FROM {table}")] == rows with store.read() as unit: @@ -134,7 +134,7 @@ def test_real_file_material_cas_preserves_source_pending_and_confirmed_totals(tm checkpoint = SQLiteSnapshots(store, tmp_path / "snapshot", store.installation, Clock()).create( "materials" ) - assert checkpoint.schema_version == 16 + assert checkpoint.schema_version == 17 copy = SQLiteDatabase(tmp_path / "snapshot/domus.sqlite3", store.installation) with copy.read() as unit: assert unit.task_materials.get("home", "intent") == final @@ -441,7 +441,7 @@ def test_schema5_real_offline_activation_upgrades_only_target_and_keeps_original SQLiteSnapshots(selected.database, tmp_path / "new-snapshot", installation, Clock()) .create("new") .schema_version - == 16 + == 17 ) finally: selected.close() diff --git a/tests/backend/test_sqlite_task_reviews.py b/tests/backend/test_sqlite_task_reviews.py index b0cba453..bcf5a241 100644 --- a/tests/backend/test_sqlite_task_reviews.py +++ b/tests/backend/test_sqlite_task_reviews.py @@ -57,6 +57,9 @@ def test_original_schema6_migration_preserves_rows_and_projects_existing_cause(t "task_missed_occurrence_settings", "task_categories", "points_task_receipts", + "inventory_materials", + "inventory_effects", + "inventory_movements", } assert set(upgraded) == set(original) | added | { "member_presentations", @@ -70,7 +73,7 @@ def test_original_schema6_migration_preserves_rows_and_projects_existing_cause(t upgraded[table] == values for table, values in original.items() if table != "households" ) assert all(upgraded[table] == [] for table in added) - assert connection.execute("PRAGMA user_version").fetchone()[0] == 16 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 17 service = queries(store, HumanIdentity("ha_admin", True, True, False)) detail = service.occurrence("identity-15") assert detail.dependency_review_required and len(detail.dependency_reviews.items) == 1 @@ -340,7 +343,7 @@ def test_original_schema6_checkpoint_activation_migrates_only_the_prepared_targe SQLiteSnapshots(selected.database, tmp_path / "new-checkpoint", INSTALLATION, Clock()) .create("new") .schema_version - == 16 + == 17 ) finally: selected.close() diff --git a/tests/backend/test_task_categories.py b/tests/backend/test_task_categories.py index 1280084a..1bfafacc 100644 --- a/tests/backend/test_task_categories.py +++ b/tests/backend/test_task_categories.py @@ -57,7 +57,7 @@ def test_schema14_category_ddl_rolls_back_to_the_exact_original_bytes(tmp_path, assert definition.content.tags == ("Garden",) assert definition.content.category_id is None and definition.category_label is None with closing(sqlite3.connect(path)) as connection: - assert connection.execute("PRAGMA user_version").fetchone() == (16,) + assert connection.execute("PRAGMA user_version").fetchone() == (17,) def test_protected_category_commands_preserve_exact_history_and_calendar_counts(api): diff --git a/tests/backend/test_task_material_http.py b/tests/backend/test_task_material_http.py index 62371ec7..525094e4 100644 --- a/tests/backend/test_task_material_http.py +++ b/tests/backend/test_task_material_http.py @@ -1,13 +1,13 @@ """Actual native and standalone task routes use bounded material inputs and live scoped reads.""" from dataclasses import replace -from functools import partial import pytest from test_task_http import PREFIX, checked, create from test_task_material_commands import Inventory from test_task_runtime import api as api +from domus.application.task_material_ports import MissingTaskInventory from domus.composition import tasks from domus.domain.identity import Permission, PermissionRule from domus.domain.task_material_values import MaterialPendingReason @@ -17,9 +17,12 @@ def inventory(api, tmp_path, monkeypatch): value = Inventory(tmp_path / "fixture-http-inventory.sqlite3") value.bindings["binding"] = replace(value.bindings["binding"], precision=2) - monkeypatch.setattr( - tasks, "TaskCommands", partial(tasks.TaskCommands, inventory_factory=value.factory) - ) + command_factory = tasks.TaskCommands + + def commands(*args, **kwargs): + return command_factory(*args, **(kwargs | {"inventory_factory": value.factory})) + + monkeypatch.setattr(tasks, "TaskCommands", commands) return value @@ -164,13 +167,21 @@ def test_selection_identity_precision_and_bounds_cannot_be_forged(api, inventory assert not unit.tasks.definitions("home") and unit.tasks.policy("home") is None -def test_unavailable_inventory_linking_is_explicit_and_atomic(api): +@pytest.mark.parametrize( + ("available", "status", "code"), + [(False, 503, "inventory_unavailable"), (True, 422, "invalid_material_reference")], +) +def test_unresolved_inventory_linking_is_explicit_and_atomic( + api, monkeypatch, available, status, code +): + if not available: + monkeypatch.setattr(tasks, "InventorySettlement", lambda *_: MissingTaskInventory()) response = api.client.post( PREFIX + "/definitions", json={"title": "Work", "materials": [selection()]}, headers=api.headers("unavailable"), ) - assert response.status_code == 503 and response.json()["code"] == "inventory_unavailable" + assert response.status_code == status and response.json()["code"] == code with api.store.read() as unit: assert not unit.tasks.definitions("home") and unit.tasks.policy("home") is None diff --git a/tests/backend/test_task_restoration.py b/tests/backend/test_task_restoration.py index 7d9088ab..0ad26ef4 100644 --- a/tests/backend/test_task_restoration.py +++ b/tests/backend/test_task_restoration.py @@ -32,7 +32,7 @@ def test_restore_keeps_original_task_state_and_retains_later_completion_as_proce ) adapter = SQLiteRestorations(store, archive, target, store.installation, Clock(), checkpoint) prepared = adapter.prepare("restore-tasks") - assert prepared.source.schema_version == checkpoint.schema_version == 16 + assert prepared.source.schema_version == checkpoint.schema_version == 17 assert prepared.operation_count == 3 and prepared.current_operations == 2 assert adapter.inspect() == prepared and store.path.read_bytes() == source_bytes assert (archive / "domus.sqlite3").read_bytes() == checkpoint_bytes diff --git a/tests/containers/administration_rollback_fixture.py b/tests/containers/administration_rollback_fixture.py index 0a3b659e..cd9c584b 100644 --- a/tests/containers/administration_rollback_fixture.py +++ b/tests/containers/administration_rollback_fixture.py @@ -111,7 +111,7 @@ def main(): assert phase in ("initialize", "later", "refuse", "restored", "rollback") assert mode in ("native", "standalone") and delivery in ("pending", "acknowledged") assert os.getuid() == os.getgid() == 65532 - assert SCHEMA_VERSION == (16 if phase in ("later", "restored") else 9) + assert SCHEMA_VERSION == (17 if phase in ("later", "restored") else 9) if phase == "refuse": saved = json.loads(RECORD.read_text()) selected = ROOT / "generations" / saved["selected_generation"] / "domus.sqlite3" diff --git a/tests/containers/restore_fixture.py b/tests/containers/restore_fixture.py index 00886b1e..218af9a9 100644 --- a/tests/containers/restore_fixture.py +++ b/tests/containers/restore_fixture.py @@ -109,7 +109,7 @@ def terminate(source, target, **kwargs): else: raise AssertionError("Unknown fixture operation") with storage.database._connection() as connection: - assert connection.execute("PRAGMA user_version").fetchone()[0] == 16 + assert connection.execute("PRAGMA user_version").fetchone()[0] == 17 private_layout() print( json.dumps( diff --git a/tests/containers/test_administration_image.py b/tests/containers/test_administration_image.py index 5d936df8..2772f27a 100644 --- a/tests/containers/test_administration_image.py +++ b/tests/containers/test_administration_image.py @@ -42,7 +42,7 @@ def test_current_image_persists_independent_profiles_in_owned_runtime(image, mod from domus.infrastructure.sqlite import SQLiteDatabase, SCHEMA_VERSION from domus.infrastructure.sqlite_snapshots import SQLiteSnapshots -assert SCHEMA_VERSION == 16 +assert SCHEMA_VERSION == 17 class Human: user_id = 'fictional_profile_ha_user' def current(self): @@ -110,7 +110,7 @@ def factory(): unit.preferences.save(private, 1) checkpoint = SQLiteSnapshots(store, Path(directory) / 'snapshot', storage.installation, clock).create('profile-checkpoint') - assert checkpoint.schema_version == 16 + assert checkpoint.schema_version == 17 assert len(tuple((Path(directory) / 'snapshot').iterdir())) == 3 finally: runtime.close() @@ -363,7 +363,7 @@ def test_actual_compatible_application_data_and_generation_rollback( assert restored["ui"] == later["ui"] assert restored["generation_id"] == later["selected_generation"] assert restored["state"] == before["state"] - assert restored["schema"] == refusal["refused_schema"] == 16 + assert restored["schema"] == refusal["refused_schema"] == 17 assert restored["original_operations_preserved"] is True assert rolled_back["ui"] == before["ui"] assert rolled_back["state"] == before["state"] @@ -427,7 +427,7 @@ def runtime(): raise AssertionError('Old application accepted an unsupported schema') assert path.read_bytes() == original else: - assert SCHEMA_VERSION == (14 if phase == 'old' else 16) + assert SCHEMA_VERSION == (14 if phase == 'old' else 17) active = runtime() try: assert active.storage is not None diff --git a/tests/containers/test_app_compatibility.py b/tests/containers/test_app_compatibility.py index 1865374b..a6953a13 100644 --- a/tests/containers/test_app_compatibility.py +++ b/tests/containers/test_app_compatibility.py @@ -127,7 +127,7 @@ def test_actual_older_image_refuses_selected_generation_without_changing_any_fil indirect=["previous_image"], ) def test_real_older_image_upgrades_replays_and_restores_its_pre_upgrade_snapshot( - image, previous_image, data_volume, old_schema, expected_schema=16 + image, previous_image, data_volume, old_schema, expected_schema=17 ): old = "domus-upgrade-old-" + uuid.uuid4().hex new = "domus-upgrade-new-" + uuid.uuid4().hex diff --git a/tests/containers/test_app_image.py b/tests/containers/test_app_image.py index e2e6b64f..c134b54e 100644 --- a/tests/containers/test_app_image.py +++ b/tests/containers/test_app_image.py @@ -129,7 +129,7 @@ def data_volume(image: str): def test_real_nonroot_listener_rejects_forgery_and_retains_storage_and_replay_on_restart( image: str, data_volume: str, - expected_schema: int = 16, + expected_schema: int = 17, ) -> None: name = "domus-persistent-test-" + uuid.uuid4().hex try: @@ -535,7 +535,7 @@ def test_packaged_console_restore_restart_and_latest_history_rollback( ) ) assert activated["state"] == "active" - assert activated["activation"]["rollback_snapshot"]["schema_version"] == 16 + assert activated["activation"]["rollback_snapshot"]["schema_version"] == 17 assert docker("start", name).returncode == 0 ready(name, standalone=mode == "standalone") active = successful(packaged_fixture(image, volume, "active", delivery)) diff --git a/tests/containers/test_recurrence_image.py b/tests/containers/test_recurrence_image.py index a363c7a6..160223f7 100644 --- a/tests/containers/test_recurrence_image.py +++ b/tests/containers/test_recurrence_image.py @@ -56,7 +56,7 @@ def test_current_image_executes_recurrence_creation_planning_and_closed_record_c schedule_document, read_schedule, progress_document, read_progress, slot_document, read_slot, frontier_document, read_frontier, ) -assert SCHEMA_VERSION == 16 +assert SCHEMA_VERSION == 17 policy = TimePolicy('Europe/Madrid', TIMEZONE_DATA_IDENTITY) pattern = parse_fixed_pattern('FREQ=DAILY;COUNT=2', NominalTime(datetime(2026, 3, 29, 2, 30))) times = PinnedRecurrenceTime() diff --git a/tests/containers/test_relative_recurrence_image.py b/tests/containers/test_relative_recurrence_image.py index cd61855a..dac29b4a 100644 --- a/tests/containers/test_relative_recurrence_image.py +++ b/tests/containers/test_relative_recurrence_image.py @@ -43,7 +43,7 @@ def test_packaged_owned_worker_restarts_and_materializes_a_relative_successor(im MODE = sys.argv[1] ORIGIN = 'https://domus.fixture' -assert SCHEMA_VERSION == 16 +assert SCHEMA_VERSION == 17 class FixtureHuman: def current(self): diff --git a/tests/fixtures/sqlite/v16-inventory-source.sql b/tests/fixtures/sqlite/v16-inventory-source.sql new file mode 100644 index 00000000..522d1267 --- /dev/null +++ b/tests/fixtures/sqlite/v16-inventory-source.sql @@ -0,0 +1,101 @@ +PRAGMA foreign_keys=OFF; +BEGIN TRANSACTION; +CREATE TABLE audit(operation_id TEXT PRIMARY KEY, household_id TEXT NOT NULL REFERENCES households(household_id), actor_id TEXT NOT NULL, action TEXT NOT NULL, command_key TEXT NOT NULL, detail TEXT NOT NULL, created_at INTEGER NOT NULL); +INSERT INTO "audit" VALUES('identity-2','home','ha_admin','household.setup','setup','{"administrator_member_id":"identity-1","mapping_mode":"all_ha_administrators","transition":"household.configured"}',100); +INSERT INTO "audit" VALUES('identity-5','home','ha_admin','task.create','source-pending','{"request":{"content":{"description":"","priority":"normal","tags":[],"title":"Pending review"},"expected_revision":0,"overrides":{"adult_performer_may_approve":null,"claim_allowed":null,"dependency_gate":null,"eligible_roles":null,"material_recording":null,"point_value_minor":125,"task_scoped_material_consumption":null,"verification":null},"state":"active"},"result":{"assignee_ids":[],"definition_id":"identity-3","definition_revision":1,"occurrence_id":"identity-4","prerequisite_ids":[],"required_subtask_ids":[],"revision":1,"state":"available","state_reason":""},"transition":"task.created"}',100); +INSERT INTO "audit" VALUES('identity-8','home','ha_admin','task.create','source-eligible','{"request":{"content":{"description":"","priority":"normal","tags":[],"title":"Adult work"},"expected_revision":0,"overrides":{"adult_performer_may_approve":null,"claim_allowed":null,"dependency_gate":null,"eligible_roles":null,"material_recording":null,"point_value_minor":300,"task_scoped_material_consumption":null,"verification":null},"state":"active"},"result":{"assignee_ids":[],"definition_id":"identity-6","definition_revision":1,"occurrence_id":"identity-7","prerequisite_ids":[],"required_subtask_ids":[],"revision":1,"state":"available","state_reason":""},"transition":"task.created"}',100); +INSERT INTO "audit" VALUES('identity-10','home','ha_admin','task.complete','record-pending','{"request":{"expected_revision":1,"occurrence_id":"identity-4","performed_at":90,"performer_ids":["child"]},"result":{"assignee_ids":[],"consumer_delivery":"unconfirmed","cycle":{"closed_at":null,"cycle_id":"identity-9","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-4","performed_at":90,"performers":[{"member_id":"child","role":"restricted"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":125,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"pending","verification_reason":"","verified_at":null,"verified_by":null},"definition_id":"identity-3","definition_revision":1,"occurrence_id":"identity-4","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":""},"transition":"task.completed"}',100); +INSERT INTO "audit" VALUES('identity-12','home','ha_admin','task.complete','record-eligible','{"request":{"expected_revision":1,"occurrence_id":"identity-7","performed_at":91,"performer_ids":["identity-1"]},"result":{"assignee_ids":[],"consumer_delivery":"unconfirmed","cycle":{"closed_at":null,"cycle_id":"identity-11","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-7","performed_at":91,"performers":[{"member_id":"identity-1","role":"administrator"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":300,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"none","verification_reason":"","verified_at":null,"verified_by":null},"definition_id":"identity-6","definition_revision":1,"occurrence_id":"identity-7","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":""},"transition":"task.completed"}',100); +CREATE TABLE calendar_preferences(household_id TEXT NOT NULL, member_id TEXT NOT NULL, week_start TEXT NOT NULL DEFAULT 'monday' CHECK(week_start IN ('monday','sunday')), revision INTEGER NOT NULL DEFAULT 1 CHECK(typeof(revision)='integer' AND revision>=1), PRIMARY KEY(household_id,member_id), FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id)); +INSERT INTO "calendar_preferences" VALUES('home','identity-1','monday',1); +INSERT INTO "calendar_preferences" VALUES('home','child','monday',1); +INSERT INTO "calendar_preferences" VALUES('home','other','monday',1); +CREATE TABLE household_policy(household_id TEXT PRIMARY KEY REFERENCES households(household_id), mapping_mode TEXT NOT NULL, target_ha_user_id TEXT, revision INTEGER NOT NULL CHECK(revision>=1), adjustments TEXT NOT NULL, CHECK((mapping_mode='all_ha_administrators' AND target_ha_user_id IS NULL) OR (mapping_mode IN ('setup_administrator','selected_ha_user') AND target_ha_user_id IS NOT NULL))); +INSERT INTO "household_policy" VALUES('home','all_ha_administrators',NULL,1,'{"rules":[]}'); +CREATE TABLE households(household_id TEXT PRIMARY KEY, singleton INTEGER NOT NULL DEFAULT 1 UNIQUE CHECK(singleton=1), name TEXT NOT NULL, time_zone TEXT NOT NULL, revision INTEGER NOT NULL CHECK(revision>=1), materialization_horizon_days INTEGER NOT NULL DEFAULT 60 CHECK(typeof(materialization_horizon_days)='integer' AND materialization_horizon_days BETWEEN 7 AND 366), repeated_time TEXT NOT NULL DEFAULT 'first_instant' CHECK(repeated_time IN ('first_instant','second_instant'))); +INSERT INTO "households" VALUES('home',1,'Home','UTC',1,60,'first_instant'); +CREATE TABLE installation(singleton INTEGER PRIMARY KEY CHECK(singleton=1), instance_id TEXT NOT NULL, channel TEXT NOT NULL CHECK(channel IN ('stable','edge'))); +INSERT INTO "installation" VALUES(1,'047cc6fb-dfb0-4fa4-b3c3-e0fe54d116b6','edge'); +CREATE TABLE member_preferences(member_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL, locale TEXT CHECK(locale IS NULL OR locale IN ('en','es')), routine_participation_summaries INTEGER NOT NULL CHECK(typeof(routine_participation_summaries)='integer' AND routine_participation_summaries IN (0,1)), revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id)); +INSERT INTO "member_preferences" VALUES('identity-1','home',NULL,1,1); +INSERT INTO "member_preferences" VALUES('child','home',NULL,1,1); +INSERT INTO "member_preferences" VALUES('other','home',NULL,1,1); +CREATE TABLE member_presentations(member_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL, alias TEXT, revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), FOREIGN KEY(household_id,member_id) REFERENCES members(household_id,member_id), CHECK(alias IS NULL OR (typeof(alias)='text' AND length(alias) BETWEEN 1 AND 80))); +INSERT INTO "member_presentations" VALUES('identity-1','home',NULL,1); +INSERT INTO "member_presentations" VALUES('child','home',NULL,1); +INSERT INTO "member_presentations" VALUES('other','home',NULL,1); +CREATE TABLE members(member_id TEXT PRIMARY KEY, household_id TEXT NOT NULL REFERENCES households(household_id), ha_user_id TEXT NOT NULL, role TEXT NOT NULL CHECK(role IN ('administrator','adult','restricted','viewer')), status TEXT NOT NULL CHECK(status IN ('pending','active','suspended','archived')), revision INTEGER NOT NULL CHECK(revision>=1), exceptions TEXT NOT NULL, UNIQUE(household_id,ha_user_id)); +INSERT INTO "members" VALUES('identity-1','home','ha_admin','viewer','active',1,'{"rules":[]}'); +INSERT INTO "members" VALUES('child','home','ha_child','restricted','active',1,'{"rules":[]}'); +INSERT INTO "members" VALUES('other','home','ha_other','restricted','active',1,'{"rules":[]}'); +CREATE TABLE outbox(position INTEGER PRIMARY KEY AUTOINCREMENT, event_id TEXT NOT NULL UNIQUE, household_id TEXT NOT NULL REFERENCES households(household_id), event_type TEXT NOT NULL, payload TEXT NOT NULL, created_at INTEGER NOT NULL, delivered INTEGER NOT NULL DEFAULT 0 CHECK(delivered IN (0,1))); +INSERT INTO "outbox" VALUES(1,'identity-2','home','household.setup','{"household_id":"home","revision":1}',100,0); +INSERT INTO "outbox" VALUES(2,'identity-5','home','task.create','{"assignee_ids":[],"definition_id":"identity-3","definition_revision":1,"kind":"task.created","occurrence_id":"identity-4","prerequisite_ids":[],"required_subtask_ids":[],"revision":1,"state":"available","state_reason":"","version":1}',100,0); +INSERT INTO "outbox" VALUES(3,'identity-8','home','task.create','{"assignee_ids":[],"definition_id":"identity-6","definition_revision":1,"kind":"task.created","occurrence_id":"identity-7","prerequisite_ids":[],"required_subtask_ids":[],"revision":1,"state":"available","state_reason":"","version":1}',100,0); +INSERT INTO "outbox" VALUES(4,'identity-10','home','task.complete','{"assignee_ids":[],"consumer_delivery":"unconfirmed","cycle":{"closed_at":null,"cycle_id":"identity-9","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-4","performed_at":90,"performers":[{"member_id":"child","role":"restricted"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":125,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"pending","verification_reason":"","verified_at":null,"verified_by":null},"definition_id":"identity-3","definition_revision":1,"kind":"task.completed","occurrence_id":"identity-4","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":"","version":1}',100,0); +INSERT INTO "outbox" VALUES(5,'identity-12','home','task.complete','{"assignee_ids":[],"consumer_delivery":"unconfirmed","cycle":{"closed_at":null,"cycle_id":"identity-11","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-7","performed_at":91,"performers":[{"member_id":"identity-1","role":"administrator"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":300,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"none","verification_reason":"","verified_at":null,"verified_by":null},"definition_id":"identity-6","definition_revision":1,"kind":"task.completed","occurrence_id":"identity-7","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":"","version":1}',100,0); +CREATE TABLE points_task_receipts(household_id TEXT NOT NULL REFERENCES households,event_id TEXT NOT NULL REFERENCES receipts(operation_id), position INTEGER NOT NULL REFERENCES outbox(position), cycle_id TEXT NOT NULL REFERENCES task_cycles, definition_id TEXT NOT NULL, fingerprint TEXT NOT NULL CHECK(length(fingerprint)=64 AND fingerprint NOT GLOB '*[^0-9a-f]*'), effect INTEGER NOT NULL CHECK(effect IN (0,1,2)), document TEXT, PRIMARY KEY(household_id,event_id), UNIQUE(household_id,position), CHECK((effect=0 AND document IS NULL) OR (effect>0 AND document IS NOT NULL AND json_valid(document))), FOREIGN KEY(household_id,definition_id) REFERENCES task_definitions(household_id,definition_id)); +INSERT INTO "points_task_receipts" VALUES('home','identity-10',4,'identity-9','identity-3','abc9a169b89c7fdbefb7718f508b183d507d39321880077eb8b8f6954514c5e2',0,NULL); +INSERT INTO "points_task_receipts" VALUES('home','identity-12',5,'identity-11','identity-6','5d06254a55931990e2418f15da2aa984202336d66d29f6015d2c52b38621509d',1,'{"cycle_id":"identity-11","definition_id":"identity-6","event_id":"identity-12","next_recipient":null,"performed_at":91,"policy_version":"conserve_total.v1","posted_at":100,"precision":0,"reverses":null,"shares":[["identity-1",300]]}'); +CREATE TABLE receipts(household_id TEXT NOT NULL REFERENCES households(household_id), actor_id TEXT NOT NULL, action TEXT NOT NULL, command_key TEXT NOT NULL, payload_fingerprint TEXT NOT NULL, operation_id TEXT NOT NULL UNIQUE, result TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY(household_id,actor_id,action,command_key)); +INSERT INTO "receipts" VALUES('home','ha_admin','household.setup','setup','fd81d9a903eff49c605ff960bfae80f61f684b2f1f12ff15fb363cd7bdea3c51','identity-2','{"administrator_member_id":"identity-1","household_id":"home","mapping_mode":"all_ha_administrators","member_id":"identity-1","policy_revision":1,"revision":1,"state":"configured"}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','task.create','source-pending','62ed466eefc838234a191596d1d5cc84003a63ddbd1a15d3d1d3cca1f4560e9f','identity-5','{"assignee_ids":[],"definition_id":"identity-3","definition_revision":1,"occurrence_id":"identity-4","prerequisite_ids":[],"required_subtask_ids":[],"revision":1,"state":"available","state_reason":""}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','task.create','source-eligible','f6cae6691fe9f493463e12027c471dec8c7b7478d8d18f8bf824a5903b0b849a','identity-8','{"assignee_ids":[],"definition_id":"identity-6","definition_revision":1,"occurrence_id":"identity-7","prerequisite_ids":[],"required_subtask_ids":[],"revision":1,"state":"available","state_reason":""}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','task.complete','record-pending','37a581f8edd1be68cb4b95734d35147ed347c1a34832647b2f97804c05b0fbb9','identity-10','{"assignee_ids":[],"consumer_delivery":"unconfirmed","cycle":{"closed_at":null,"cycle_id":"identity-9","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-4","performed_at":90,"performers":[{"member_id":"child","role":"restricted"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":125,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"pending","verification_reason":"","verified_at":null,"verified_by":null},"definition_id":"identity-3","definition_revision":1,"occurrence_id":"identity-4","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":""}',100); +INSERT INTO "receipts" VALUES('home','ha_admin','task.complete','record-eligible','fcc2cee588638e85051a2f90b740595c25c6a9fbe989bc89676b9f3212d0b634','identity-12','{"assignee_ids":[],"consumer_delivery":"unconfirmed","cycle":{"closed_at":null,"cycle_id":"identity-11","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-7","performed_at":91,"performers":[{"member_id":"identity-1","role":"administrator"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":300,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"none","verification_reason":"","verified_at":null,"verified_by":null},"definition_id":"identity-6","definition_revision":1,"occurrence_id":"identity-7","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":""}',100); +CREATE TABLE recovery_requests(request_id TEXT PRIMARY KEY, household_id TEXT NOT NULL REFERENCES households(household_id), target_ha_user_id TEXT NOT NULL, revision INTEGER NOT NULL CHECK(revision>=1), state TEXT NOT NULL CHECK(state IN ('pending','approved','consumed','canceled')), created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, detail TEXT NOT NULL); +CREATE TABLE recurrence_frontiers(household_id TEXT PRIMARY KEY NOT NULL REFERENCES households(household_id), after_schedule_id TEXT, revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), selected_at INTEGER NOT NULL CHECK(typeof(selected_at)='integer' AND selected_at>=0), document TEXT NOT NULL); +CREATE TABLE recurrence_progress(schedule_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL, pattern_revision INTEGER NOT NULL CHECK(typeof(pattern_revision)='integer' AND pattern_revision>=1), revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), timing_kind TEXT NOT NULL CHECK(timing_kind IN ('fixed_calendar','completion_relative')), document TEXT NOT NULL, UNIQUE(household_id,schedule_id,pattern_revision,timing_kind), FOREIGN KEY(household_id,schedule_id,pattern_revision,timing_kind) REFERENCES recurrence_rules(household_id,schedule_id,pattern_revision,timing_kind) DEFERRABLE INITIALLY DEFERRED); +CREATE TABLE recurrence_progress_evidence(household_id TEXT NOT NULL, schedule_id TEXT NOT NULL, progress_revision INTEGER NOT NULL CHECK(typeof(progress_revision)='integer' AND progress_revision>=1), operation_id TEXT NOT NULL, evidence_fingerprint TEXT NOT NULL, PRIMARY KEY(household_id,schedule_id), FOREIGN KEY(household_id,schedule_id,progress_revision) REFERENCES recurrence_progress(household_id,schedule_id,revision) DEFERRABLE INITIALLY DEFERRED); +CREATE TABLE recurrence_relative_closures(household_id TEXT NOT NULL, closure_key TEXT NOT NULL, operation_id TEXT NOT NULL UNIQUE, document TEXT NOT NULL, PRIMARY KEY(household_id,closure_key)); +CREATE TABLE recurrence_relative_inbox(household_id TEXT NOT NULL REFERENCES households(household_id), position INTEGER NOT NULL CHECK(typeof(position)='integer' AND position>=1), event_key TEXT NOT NULL, operation_id TEXT NOT NULL UNIQUE, actor_id TEXT NOT NULL, cycle_key TEXT NOT NULL, source_schedule_id TEXT, source_terminal INTEGER NOT NULL CHECK(typeof(source_terminal)='integer' AND source_terminal IN (0,1)), outcome_status TEXT, outcome_schedule_id TEXT, outcome_operation_id TEXT, outcome_occurrence_id TEXT, CHECK((outcome_status IS NULL)=(outcome_schedule_id IS NULL) AND (outcome_status IS NOT NULL OR (outcome_operation_id IS NULL AND outcome_occurrence_id IS NULL))), PRIMARY KEY(household_id,position), UNIQUE(household_id,event_key), FOREIGN KEY(household_id,source_schedule_id) REFERENCES recurrence_rules(household_id,schedule_id)); +CREATE TABLE recurrence_relative_slots(household_id TEXT NOT NULL, slot_key TEXT NOT NULL, schedule_id TEXT NOT NULL, definition_id TEXT NOT NULL, pattern_revision INTEGER NOT NULL CHECK(typeof(pattern_revision)='integer' AND pattern_revision>=1), occurrence_id TEXT NOT NULL, source_occurrence_id TEXT, source_cycle_id TEXT, created_at INTEGER NOT NULL CHECK(typeof(created_at)='integer' AND created_at>=0), receipt_actor TEXT NOT NULL CHECK(receipt_actor='system:recurrence'), receipt_action TEXT NOT NULL CHECK(receipt_action='recurrence.materialize'), timing_kind TEXT NOT NULL CHECK(timing_kind='completion_relative'), document TEXT NOT NULL, PRIMARY KEY(household_id,slot_key), UNIQUE(household_id,occurrence_id), CHECK((source_occurrence_id IS NULL)=(source_cycle_id IS NULL)), FOREIGN KEY(household_id,schedule_id,definition_id,timing_kind) REFERENCES recurrence_rules(household_id,schedule_id,definition_id,timing_kind), FOREIGN KEY(household_id,definition_id,occurrence_id) REFERENCES task_occurrences(household_id,definition_id,occurrence_id), FOREIGN KEY(household_id,source_occurrence_id,source_cycle_id) REFERENCES task_cycles(household_id,occurrence_id,cycle_id), FOREIGN KEY(household_id,receipt_actor,receipt_action,slot_key) REFERENCES receipts(household_id,actor_id,action,command_key) DEFERRABLE INITIALLY DEFERRED); +CREATE TABLE recurrence_rules(schedule_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL, definition_id TEXT NOT NULL, revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), pattern_revision INTEGER NOT NULL CHECK(typeof(pattern_revision)='integer' AND pattern_revision>=1 AND pattern_revision<=revision), state TEXT NOT NULL CHECK(state IN ('active','paused','retired')), timing_kind TEXT NOT NULL CHECK(timing_kind IN ('fixed_calendar','completion_relative')), document TEXT NOT NULL, UNIQUE(household_id,schedule_id), UNIQUE(household_id,schedule_id,definition_id), UNIQUE(household_id,schedule_id,pattern_revision,timing_kind), UNIQUE(household_id,schedule_id,definition_id,timing_kind), FOREIGN KEY(household_id,definition_id) REFERENCES task_definitions(household_id,definition_id), FOREIGN KEY(household_id,schedule_id,pattern_revision,timing_kind) REFERENCES recurrence_progress(household_id,schedule_id,pattern_revision,timing_kind) DEFERRABLE INITIALLY DEFERRED); +CREATE TABLE recurrence_slots(household_id TEXT NOT NULL, slot_key TEXT NOT NULL, schedule_id TEXT NOT NULL, definition_id TEXT NOT NULL, pattern_revision INTEGER NOT NULL CHECK(typeof(pattern_revision)='integer' AND pattern_revision>=1), occurrence_id TEXT NOT NULL, nominal_kind TEXT NOT NULL CHECK(nominal_kind IN ('date','time')), nominal_value TEXT NOT NULL, resolved_at INTEGER, created_at INTEGER NOT NULL CHECK(typeof(created_at)='integer' AND created_at>=0), receipt_actor TEXT NOT NULL CHECK(receipt_actor='system:recurrence'), receipt_action TEXT NOT NULL CHECK(receipt_action='recurrence.materialize'), timing_kind TEXT NOT NULL CHECK(timing_kind='fixed_calendar'), document TEXT NOT NULL, PRIMARY KEY(household_id,slot_key), UNIQUE(household_id,occurrence_id), CHECK((nominal_kind='date' AND resolved_at IS NULL) OR (nominal_kind='time' AND typeof(resolved_at)='integer' AND resolved_at>=0)), FOREIGN KEY(household_id,schedule_id,definition_id,timing_kind) REFERENCES recurrence_rules(household_id,schedule_id,definition_id,timing_kind), FOREIGN KEY(household_id,definition_id,occurrence_id) REFERENCES task_occurrences(household_id,definition_id,occurrence_id), FOREIGN KEY(household_id,receipt_actor,receipt_action,slot_key) REFERENCES receipts(household_id,actor_id,action,command_key) DEFERRABLE INITIALLY DEFERRED); +CREATE TABLE retained_operations(household_id TEXT NOT NULL, actor_id TEXT NOT NULL, action TEXT NOT NULL, command_key TEXT NOT NULL, operation_id TEXT NOT NULL UNIQUE, position INTEGER NOT NULL UNIQUE CHECK(position>=1), current INTEGER NOT NULL CHECK(current IN (0,1)), archived_by TEXT, document TEXT NOT NULL, closed_recovery_id TEXT, PRIMARY KEY(household_id,actor_id,action,command_key)); +CREATE TABLE task_categories(category_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL REFERENCES households(household_id), label TEXT NOT NULL, label_key TEXT NOT NULL, revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), archived INTEGER NOT NULL CHECK(archived IN (0,1))); +CREATE TABLE task_cycles(cycle_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL REFERENCES households(household_id), occurrence_id TEXT NOT NULL, active_occurrence_id TEXT, recorded_by TEXT NOT NULL, verified_by TEXT, revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), closed_at INTEGER CHECK(closed_at IS NULL OR (typeof(closed_at)='integer' AND closed_at>=0)), document TEXT NOT NULL, UNIQUE(household_id,active_occurrence_id,cycle_id,revision), CHECK((closed_at IS NULL AND active_occurrence_id IS occurrence_id) OR (closed_at IS NOT NULL AND active_occurrence_id IS NULL)), FOREIGN KEY(household_id,occurrence_id) REFERENCES task_occurrences(household_id,occurrence_id) DEFERRABLE INITIALLY DEFERRED, FOREIGN KEY(household_id,recorded_by) REFERENCES members(household_id,member_id), FOREIGN KEY(household_id,verified_by) REFERENCES members(household_id,member_id), FOREIGN KEY(household_id,active_occurrence_id,cycle_id,revision) REFERENCES task_occurrences(household_id,occurrence_id,current_cycle_id,current_cycle_revision) DEFERRABLE INITIALLY DEFERRED); +INSERT INTO "task_cycles" VALUES('identity-9','home','identity-4','identity-4','identity-1',NULL,1,NULL,'{"closed_at":null,"cycle_id":"identity-9","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-4","performed_at":90,"performers":[{"member_id":"child","role":"restricted"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":125,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"pending","verification_reason":"","verified_at":null,"verified_by":null,"version":1}'); +INSERT INTO "task_cycles" VALUES('identity-11','home','identity-7','identity-7','identity-1',NULL,1,NULL,'{"closed_at":null,"cycle_id":"identity-11","definition_revision":1,"household_id":"home","identity_policy_revision":1,"occurrence_id":"identity-7","performed_at":91,"performers":[{"member_id":"identity-1","role":"administrator"}],"recorded_at":100,"recorded_by":"identity-1","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":300,"task_scoped_material_consumption":true,"verification":"role_default"},"task_policy_revision":1,"verification":"none","verification_reason":"","verified_at":null,"verified_by":null,"version":1}'); +CREATE TABLE task_definitions(definition_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL REFERENCES task_policy(household_id), revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), state TEXT NOT NULL CHECK(state IN ('draft','active','paused','archived')), document TEXT NOT NULL, UNIQUE(household_id,definition_id)); +INSERT INTO "task_definitions" VALUES('identity-3','home',1,'active','{"content":{"description":"","priority":"normal","tags":[],"title":"Pending review"},"created_at":100,"definition_id":"identity-3","household_id":"home","materials":[],"overrides":{"adult_performer_may_approve":null,"claim_allowed":null,"dependency_gate":null,"eligible_roles":null,"material_recording":null,"point_value_minor":125,"task_scoped_material_consumption":null,"verification":null},"revision":1,"state":"active","version":2}'); +INSERT INTO "task_definitions" VALUES('identity-6','home',1,'active','{"content":{"description":"","priority":"normal","tags":[],"title":"Adult work"},"created_at":100,"definition_id":"identity-6","household_id":"home","materials":[],"overrides":{"adult_performer_may_approve":null,"claim_allowed":null,"dependency_gate":null,"eligible_roles":null,"material_recording":null,"point_value_minor":300,"task_scoped_material_consumption":null,"verification":null},"revision":1,"state":"active","version":2}'); +CREATE TABLE task_material_intents(intent_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL, occurrence_id TEXT NOT NULL, cycle_id TEXT NOT NULL, line_id TEXT NOT NULL, recorded_by TEXT NOT NULL, revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), state TEXT NOT NULL CHECK(state IN ('pending_recording','pending_authorization','pending_regularization','pending_processing','not_used','posted','corrected','dismissed')), document TEXT NOT NULL, UNIQUE(household_id,cycle_id,line_id), FOREIGN KEY(household_id,occurrence_id,cycle_id) REFERENCES task_cycles(household_id,occurrence_id,cycle_id), FOREIGN KEY(household_id,recorded_by) REFERENCES members(household_id,member_id)); +CREATE TABLE task_missed_occurrence_settings(household_id TEXT NOT NULL, definition_id TEXT NOT NULL, policy TEXT NOT NULL CHECK(policy IN ('keep_visible','skip_after_review')), revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), PRIMARY KEY(household_id,definition_id), FOREIGN KEY(household_id,definition_id) REFERENCES task_definitions(household_id,definition_id)); +CREATE TABLE task_occurrences(occurrence_id TEXT PRIMARY KEY NOT NULL, household_id TEXT NOT NULL REFERENCES households(household_id), definition_id TEXT NOT NULL, revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), state TEXT NOT NULL CHECK(state IN ('draft','available','assigned','in_progress','blocked','completed','cancelled','skipped')), current_cycle_id TEXT, current_cycle_revision INTEGER CHECK(current_cycle_revision IS NULL OR (typeof(current_cycle_revision)='integer' AND current_cycle_revision>=1)), document TEXT NOT NULL, UNIQUE(household_id,occurrence_id), UNIQUE(household_id,occurrence_id,current_cycle_id,current_cycle_revision), CHECK((state='completed' AND current_cycle_id IS NOT NULL AND current_cycle_revision IS NOT NULL) OR (state!='completed' AND current_cycle_id IS NULL AND current_cycle_revision IS NULL)), FOREIGN KEY(household_id,definition_id) REFERENCES task_definitions(household_id,definition_id), FOREIGN KEY(household_id,occurrence_id,current_cycle_id,current_cycle_revision) REFERENCES task_cycles(household_id,active_occurrence_id,cycle_id,revision) DEFERRABLE INITIALLY DEFERRED); +INSERT INTO "task_occurrences" VALUES('identity-4','home','identity-3',2,'completed','identity-9',1,'{"assignee_ids":[],"created_at":100,"current_cycle_id":"identity-9","current_cycle_revision":1,"definition_snapshot":{"content":{"description":"","priority":"normal","tags":[],"title":"Pending review"},"created_at":100,"definition_id":"identity-3","household_id":"home","materials":[],"overrides":{"adult_performer_may_approve":null,"claim_allowed":null,"dependency_gate":null,"eligible_roles":null,"material_recording":null,"point_value_minor":125,"task_scoped_material_consumption":null,"verification":null},"revision":1,"state":"active","version":2},"due_at":null,"household_id":"home","occurrence_id":"identity-4","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":"","version":2}'); +INSERT INTO "task_occurrences" VALUES('identity-7','home','identity-6',2,'completed','identity-11',1,'{"assignee_ids":[],"created_at":100,"current_cycle_id":"identity-11","current_cycle_revision":1,"definition_snapshot":{"content":{"description":"","priority":"normal","tags":[],"title":"Adult work"},"created_at":100,"definition_id":"identity-6","household_id":"home","materials":[],"overrides":{"adult_performer_may_approve":null,"claim_allowed":null,"dependency_gate":null,"eligible_roles":null,"material_recording":null,"point_value_minor":300,"task_scoped_material_consumption":null,"verification":null},"revision":1,"state":"active","version":2},"due_at":null,"household_id":"home","occurrence_id":"identity-7","prerequisite_ids":[],"required_subtask_ids":[],"revision":2,"state":"completed","state_reason":"","version":2}'); +CREATE TABLE task_policy(household_id TEXT PRIMARY KEY NOT NULL REFERENCES households(household_id), revision INTEGER NOT NULL CHECK(typeof(revision)='integer' AND revision>=1), document TEXT NOT NULL); +INSERT INTO "task_policy" VALUES('home',1,'{"household_id":"home","revision":1,"rules":{"adult_performer_may_approve":true,"claim_allowed":true,"dependency_gate":"performed","eligible_roles":["administrator","adult","restricted"],"material_recording":"review_on_completion","point_value_minor":0,"task_scoped_material_consumption":true,"verification":"role_default"},"version":1}'); +CREATE INDEX outbox_pending ON outbox(delivered,position); +CREATE INDEX recovery_pending ON recovery_requests(household_id,state,expires_at); +CREATE INDEX retained_recovery ON retained_operations(household_id,closed_recovery_id) WHERE current=0 AND closed_recovery_id IS NOT NULL; +CREATE UNIQUE INDEX task_member_scope ON members(household_id,member_id); +CREATE INDEX task_definitions_page ON task_definitions(household_id,state,definition_id); +CREATE INDEX task_occurrences_page ON task_occurrences(household_id,state,occurrence_id); +CREATE INDEX task_occurrences_definition ON task_occurrences(household_id,definition_id,occurrence_id); +CREATE INDEX task_cycles_page ON task_cycles(household_id,occurrence_id,cycle_id); +CREATE UNIQUE INDEX task_one_open_cycle ON task_cycles(household_id,occurrence_id) WHERE closed_at IS NULL; +CREATE UNIQUE INDEX task_cycle_material_scope ON task_cycles(household_id,occurrence_id,cycle_id); +CREATE INDEX task_material_cycle_page ON task_material_intents(household_id,cycle_id,intent_id); +CREATE INDEX task_cycle_event_page ON outbox(json_extract(payload,'$.cycle.cycle_id'),position); +CREATE INDEX task_occurrence_event_page ON outbox(json_extract(payload,'$.occurrence_id'),position); +CREATE INDEX task_dependency_ack_page ON outbox(json_extract(payload,'$.review.cause.dependent_cycle_id'),json_extract(payload,'$.review.cause.source_operation_id'),position); +CREATE UNIQUE INDEX recurrence_occurrence_scope ON task_occurrences(household_id,definition_id,occurrence_id); +CREATE UNIQUE INDEX recurrence_cycle_scope ON task_cycles(household_id,occurrence_id,cycle_id); +CREATE UNIQUE INDEX recurrence_progress_revision ON recurrence_progress(household_id,schedule_id,revision); +CREATE UNIQUE INDEX recurrence_current_definition ON recurrence_rules(household_id,definition_id) WHERE state!='retired'; +CREATE INDEX recurrence_rules_page ON recurrence_rules(household_id,state,schedule_id); +CREATE INDEX recurrence_slots_page ON recurrence_slots(household_id,schedule_id,slot_key); +CREATE INDEX recurrence_relative_slots_page ON recurrence_relative_slots(household_id,schedule_id,slot_key); +CREATE INDEX recurrence_relative_pending ON recurrence_relative_inbox(household_id,position) WHERE outcome_status IS NULL; +CREATE INDEX recurrence_relative_pending_rule ON recurrence_relative_inbox(household_id,source_schedule_id,source_terminal DESC,position) WHERE outcome_status IS NULL; +CREATE UNIQUE INDEX task_categories_active_label ON task_categories(household_id,label_key) WHERE archived=0; +CREATE UNIQUE INDEX points_one_effect_per_cycle ON points_task_receipts(household_id,cycle_id,effect) WHERE effect>0; +CREATE INDEX points_definition_rotation ON points_task_receipts(household_id,definition_id,position) WHERE effect=1; +CREATE INDEX points_restored_award_closure ON retained_operations(household_id,json_extract(document,'$.event_payload.cycle.cycle_id'),position) WHERE current=0 AND (action='task.reopen' OR (action='task.verify' AND json_extract(document,'$.event_payload.cycle.verification')='rejected')); +DELETE FROM "sqlite_sequence"; +INSERT INTO "sqlite_sequence" VALUES('outbox',5); +COMMIT; +PRAGMA application_id=1146047829; +PRAGMA user_version=16;