Fas 2 steg 2: Inventory Trust Engine - decay-profiler och cache-jobb

This commit is contained in:
Sven (AAMOS AI)
2026-08-06 23:25:32 +07:00
parent 8ae4bf6ec3
commit bcf932d2ff
17 changed files with 18296 additions and 61 deletions
+16
View File
@@ -2,6 +2,7 @@ import { createHash, randomBytes, randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import type { Database } from "@app/database";
import { schema } from "@app/database";
import type { DecayProfile } from "@app/inventory-engine";
import type { EventType } from "@app/shared-types";
import type { NewDomainEvent } from "@app/events";
import { errors } from "./errors.js";
@@ -145,3 +146,18 @@ export async function audit(
export function newCorrelationId(): string {
return randomUUID();
}
/** Hämta den aktiva trust-decay-profilen. Cachas i praktiken av databasen;
* funktionen returnerar alltid en giltig profil (default fallback). */
export async function getActiveDecayProfile(db: Database): Promise<DecayProfile> {
const [profile] = await db
.select({ halfLifeDays: schema.inventoryDecayProfiles.halfLifeDays, staleAfterDays: schema.inventoryDecayProfiles.staleAfterDays })
.from(schema.inventoryDecayProfiles)
.where(eq(schema.inventoryDecayProfiles.active, true))
.orderBy(schema.inventoryDecayProfiles.createdAt)
.limit(1);
return {
halfLifeDays: profile?.halfLifeDays ?? 7,
staleAfterDays: profile?.staleAfterDays ?? 30,
};
}
+37 -6
View File
@@ -10,7 +10,7 @@ import {
} from "@app/validation";
import { classifyExpiry, findDuplicateCandidates, normalizeDelta, computeTrust } from "@app/inventory-engine";
import { errors, parse } from "../lib/errors.js";
import { emitEvent, requireActiveHousehold, requireMembership } from "../lib/helpers.js";
import { emitEvent, getActiveDecayProfile, requireActiveHousehold, requireMembership } from "../lib/helpers.js";
/**
* Food Twin lagret (spec §8). Transaktionsbaserat: varje förändring skrivs
@@ -22,6 +22,7 @@ export async function inventoryRoutes(app: FastifyInstance) {
app.get("/v1/inventory", auth, async (req) => {
const query = parse(inventoryQuerySchema, req.query);
const householdId = await requireActiveHousehold(app.db, req.userId);
const decayProfile = await getActiveDecayProfile(app.db);
const conditions = [
eq(schema.inventoryItems.householdId, householdId),
@@ -73,11 +74,24 @@ export async function inventoryRoutes(app: FastifyInstance) {
storageLocationType: r.locationType,
shelfLifeGuidance: r.shelfLife,
});
const trust = computeTrust(
{
confidence: r.item.confidence,
verifiedByUser: r.item.verifiedByUser,
lastVerifiedAt: r.item.lastVerifiedAt,
quantity: r.item.quantity,
updatedAt: r.item.updatedAt,
},
new Date(),
decayProfile,
);
return {
...r.item,
locationName: r.locationName,
locationType: r.locationType,
expiry,
trustState: trust.state,
trustScore: trust.score,
};
});
@@ -90,6 +104,7 @@ export async function inventoryRoutes(app: FastifyInstance) {
/** Varor som bör användas snart driver "använd först" (spec §4.4, §40). */
app.get("/v1/inventory/expiring", auth, async (req) => {
const householdId = await requireActiveHousehold(app.db, req.userId);
const decayProfile = await getActiveDecayProfile(app.db);
const rows = await app.db
.select({
item: schema.inventoryItems,
@@ -114,9 +129,8 @@ export async function inventoryRoutes(app: FastifyInstance) {
);
const withExpiry = rows
.map((r) => ({
...r.item,
expiry: classifyExpiry({
.map((r) => {
const expiry = classifyExpiry({
bestBeforeDate: r.item.bestBeforeDate,
useByDate: r.item.useByDate,
openedAt: r.item.openedAt,
@@ -125,8 +139,25 @@ export async function inventoryRoutes(app: FastifyInstance) {
purchasedAt: r.item.purchasedAt,
storageLocationType: r.locationType,
shelfLifeGuidance: r.shelfLife,
}),
}))
});
const trust = computeTrust(
{
confidence: r.item.confidence,
verifiedByUser: r.item.verifiedByUser,
lastVerifiedAt: r.item.lastVerifiedAt,
quantity: r.item.quantity,
updatedAt: r.item.updatedAt,
},
new Date(),
decayProfile,
);
return {
...r.item,
expiry,
trustState: trust.state,
trustScore: trust.score,
};
})
.filter(
(i) =>
i.expiry.status === "expiring" ||
+108
View File
@@ -0,0 +1,108 @@
import "./setup-env.js";
import { describe, expect, it, beforeAll, afterAll } from "vitest";
import { eq, inArray } from "drizzle-orm";
import { buildServer } from "../src/server.js";
import { loadConfig } from "../src/config.js";
import { createDatabase, closeDatabase, schema } from "@app/database";
describe("inventory trust read-time computation", () => {
const testDb = createDatabase(process.env.TEST_DATABASE_URL!);
const config = loadConfig();
let app: Awaited<ReturnType<typeof buildServer>>;
let accessToken: string;
let householdId: string;
let locationId: string;
const userEmail = "trust-read@example.invalid";
async function cleanup() {
const existing = await testDb.db
.select({ id: schema.users.id })
.from(schema.users)
.where(inArray(schema.users.email, [userEmail]));
for (const u of existing) {
await testDb.db.delete(schema.inventoryTransactions).where(eq(schema.inventoryTransactions.actorUserId, u.id));
const owned = await testDb.db
.select({ id: schema.households.id })
.from(schema.households)
.innerJoin(schema.householdMembers, eq(schema.householdMembers.householdId, schema.households.id))
.where(eq(schema.householdMembers.userId, u.id));
for (const h of owned) {
await testDb.db.delete(schema.inventoryItems).where(eq(schema.inventoryItems.householdId, h.id));
await testDb.db.delete(schema.storageLocations).where(eq(schema.storageLocations.householdId, h.id));
await testDb.db.delete(schema.households).where(eq(schema.households.id, h.id));
}
await testDb.db.delete(schema.householdMembers).where(eq(schema.householdMembers.userId, u.id));
await testDb.db.delete(schema.userPreferences).where(eq(schema.userPreferences.userId, u.id));
await testDb.db.delete(schema.users).where(eq(schema.users.id, u.id));
}
}
beforeAll(async () => {
await cleanup();
app = await buildServer(config);
await app.ready();
const res = await app.inject({
method: "POST",
url: "/v1/auth/register",
payload: { email: userEmail, password: "Password123!", displayName: "Trust" },
});
const body = JSON.parse(res.body) as { accessToken: string };
accessToken = body.accessToken;
const quick = await app.inject({
method: "POST",
url: "/v1/onboarding/quick-start",
headers: { authorization: `Bearer ${accessToken}` },
payload: { goals: ["cook_more"], precisionMode: "simple" },
});
const quickBody = JSON.parse(quick.body) as { householdId: string };
householdId = quickBody.householdId;
const [location] = await testDb.db
.select()
.from(schema.storageLocations)
.where(eq(schema.storageLocations.householdId, householdId))
.limit(1);
locationId = location!.id;
});
afterAll(async () => {
await cleanup();
await closeDatabase();
await app.close();
});
it("reports decaying/stale for items with old lastVerifiedAt without a write", async () => {
const fortyDaysAgo = new Date(Date.now() - 40 * 86_400_000);
const [item] = await testDb.db
.insert(schema.inventoryItems)
.values({
householdId,
displayName: "Gammal mjölk",
quantity: 1,
unit: "LITER",
storageLocationId: locationId,
source: "manual_search",
confidence: 0.6,
verifiedByUser: true,
lastVerifiedAt: fortyDaysAgo,
updatedAt: fortyDaysAgo,
})
.returning();
const res = await app.inject({
method: "GET",
url: "/v1/inventory",
headers: { authorization: `Bearer ${accessToken}` },
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body) as { items: Array<{ id: string; trustState: string; trustScore: number }> };
const found = body.items.find((i) => i.id === item!.id);
expect(found).toBeTruthy();
expect(["decaying", "stale"]).toContain(found!.trustState);
expect(found!.trustScore).toBeLessThan(60);
});
});
+12
View File
@@ -16,6 +16,7 @@ import {
processStoreNotification,
processSubscriptionSweep,
processTrainingExport,
processTrustDecay,
} from "./processors/maintenance.js";
import {
@@ -110,6 +111,12 @@ const worker = new Worker(
return;
}
case "UPDATE_TRUST_STATES": {
const updated = await processTrustDecay(ctx);
if (updated > 0) log(`Trust decay: ${updated} items uppdaterade`);
return;
}
// Deterministiska/planerade jobb som inte kräver egen processor ännu
case "NORMALIZE_PRODUCTS":
case "DEDUPLICATE_INVENTORY":
@@ -201,6 +208,11 @@ async function registerRepeatableJobs() {
{ every: 30_000 },
{ name: "PUBLISH_OUTBOX", data: { jobType: "PUBLISH_OUTBOX" }, opts: baseOpts },
);
await queue.upsertJobScheduler(
"scheduler-trust",
{ every: 300_000 },
{ name: "UPDATE_TRUST_STATES", data: { jobType: "UPDATE_TRUST_STATES" }, opts: baseOpts },
);
await queue.upsertJobScheduler(
"scheduler-expiry",
{ pattern: "0 7 * * *", tz: "Europe/Stockholm" },
+53 -1
View File
@@ -1,6 +1,6 @@
import { and, eq, gt, inArray, isNull, lte, sql } from "drizzle-orm";
import { schema } from "@app/database";
import { classifyExpiry } from "@app/inventory-engine";
import { classifyExpiry, computeTrust } from "@app/inventory-engine";
import { deriveMemoryUpdates } from "@app/memory-client";
import { getLocaleContext } from "../locale.js";
import type { WorkerContext } from "../context.js";
@@ -31,6 +31,58 @@ export async function processOutbox(ctx: WorkerContext): Promise<number> {
return pending.length;
}
/**
* UPDATE_TRUST_STATES (Fas 2 §5.2): uppdatera cache-kolumnen inventory_items.trust_state
* utifrån aktiv decay-profil. Körs periodiskt. Decay påverkar endast förtroende,
* aldrig ätbarhet (mjölkprincipen D-035).
*/
export async function processTrustDecay(ctx: WorkerContext): Promise<number> {
const [profile] = await ctx.db
.select({
halfLifeDays: schema.inventoryDecayProfiles.halfLifeDays,
staleAfterDays: schema.inventoryDecayProfiles.staleAfterDays,
})
.from(schema.inventoryDecayProfiles)
.where(eq(schema.inventoryDecayProfiles.active, true))
.orderBy(schema.inventoryDecayProfiles.createdAt)
.limit(1);
const decayProfile = {
halfLifeDays: profile?.halfLifeDays ?? 7,
staleAfterDays: profile?.staleAfterDays ?? 30,
};
const now = new Date();
const rows = await ctx.db
.select()
.from(schema.inventoryItems)
.where(and(isNull(schema.inventoryItems.depletedAt), gt(schema.inventoryItems.quantity, 0)))
.limit(500);
let updated = 0;
for (const item of rows) {
const { state } = computeTrust(
{
confidence: item.confidence,
verifiedByUser: item.verifiedByUser,
lastVerifiedAt: item.lastVerifiedAt,
quantity: item.quantity,
updatedAt: item.updatedAt,
},
now,
decayProfile,
);
if (state !== item.trustState) {
await ctx.db
.update(schema.inventoryItems)
.set({ trustState: state, updatedAt: now })
.where(eq(schema.inventoryItems.id, item.id));
updated++;
}
}
return updated;
}
/** SEND_EXPIRY_NOTIFICATION (spec §54): skapa notiser för varor som snart går ut. */
export async function processExpiryNotifications(ctx: WorkerContext): Promise<number> {
const households = await ctx.db.select({ id: schema.households.id }).from(schema.households);