Merge release/v1.39.0 into feat/ai-routes-insights-coach

Brings in the jobs, stored-text and consent package and the extraction
routes. Conflicts resolved:

- The digest keeps its capability-driven reaction line and check-in,
  now through the shared `aiCapabilityForRecord`; the local copy of it
  is removed.
- The route inventories classify the extraction routes (documents,
  labs OCR, medication text, fenced chat and attachments) as actions;
  a capability call counts as the gate for the module inventory.
- With every caller moved, `requireAssistantSurface` and
  `AssistantDisabledError` are deleted. The `assistant.disabled.*`
  codes stay on the capability refusal, and the guard now asserts the
  retired gate is gone.
- `aiCapabilityToServe` answers whether stored model text may be shown
  from the record's own state, apart from who is reading.

Refs #975
This commit is contained in:
Marc-André Bombeck committed 2026-09-24 10:16:53 +02:00
commit c509afeb2e
256 files changed
+13048 -4642

No files matched your search

@@ -22,10 +22,8 @@ vi.mock("@/lib/logging/context", () => ({
import { prisma } from "@/lib/db";
import {
ASSISTANT_FLAGS_DEFAULT,
AssistantDisabledError,
getAssistantFlags,
loadAssistantSwitches,
requireAssistantSurface,
resolveAssistantFlags,
} from "../index";
@@ -139,52 +137,6 @@ describe("loadAssistantSwitches", () => {
});
});
describe("requireAssistantSurface", () => {
it("returns the resolved flag set when the surface is enabled", async () => {
FIND.mockResolvedValue({
assistantEnabled: true,
assistantCoachEnabled: true,
assistantBriefingEnabled: true,
assistantInsightStatusEnabled: true,
assistantDocumentAiEnabled: true,
});
const flags = await requireAssistantSurface("coach");
expect(flags.coach).toBe(true);
});
it("throws AssistantDisabledError when the sub-flag is off", async () => {
FIND.mockResolvedValue({
assistantEnabled: true,
assistantCoachEnabled: false,
assistantBriefingEnabled: true,
assistantInsightStatusEnabled: true,
assistantDocumentAiEnabled: true,
});
await expect(requireAssistantSurface("coach")).rejects.toThrow(
AssistantDisabledError,
);
});
it("throws AssistantDisabledError when the master kills the surface", async () => {
FIND.mockResolvedValue({
assistantEnabled: false,
assistantCoachEnabled: true,
assistantBriefingEnabled: true,
assistantInsightStatusEnabled: true,
assistantDocumentAiEnabled: true,
});
await expect(requireAssistantSurface("briefing")).rejects.toThrow(
AssistantDisabledError,
);
});
it("AssistantDisabledError carries the surface-tagged errorCode", () => {
const err = new AssistantDisabledError("insightStatus");
expect(err.surface).toBe("insightStatus");
expect(err.errorCode).toBe("assistant.disabled.insightStatus");
});
});
describe("per-request memoisation", () => {
// v1.4.33 — When the same request opens the Coach drawer, five gated
// routes (`/api/insights/chat`, the rail list, each `<metric>-status`
@@ -1,6 +1,6 @@
/**
* Every assistant switch an operator can flip has to move something, a
* switch that was retired stays retired, and the retired gate only shrinks.
* switch that was retired stays retired, and the retired gate stays gone.
*
* `healthScoreExplainer` did not move anything. It gated a caption beside the
* Health-Score delta; the caption's component went when the health score was
@@ -21,19 +21,18 @@
* it. A switch whose reader lands with the routes it covers is named in
* `AWAITING_READER` with the reason, and the entry fails the moment a
* reader appears, so it cannot outlive its reason.
* 3. `requireAssistantSurface` is the retired gate. It answers only the
* operator layer; `requireAiCapability` answers every layer. The routes
* that still call it are frozen below, in both directions: a new caller
* fails, and a caller that moved to the capability gate fails until its
* entry is removed. When the list is empty the function and
* `AssistantDisabledError` are deleted and this guard asserts zero.
* 3. `requireAssistantSurface` and `AssistantDisabledError` are gone. They
* answered only the operator layer; `requireAiCapability` answers every
* layer with the same `assistant.disabled.<switch>` code for the operator
* case. Nothing may define or call them again.
* 4. The matchers find what they are meant to judge (non-zero counts), so a
* matcher that stopped matching cannot agree with an empty world.
*
* Mutation checks: adding `await requireAssistantSurface("coach")` to any
* route outside the frozen list turns guard 3 red by file name; removing the
* `documentAi` entry from `AWAITING_READER` turns guard 2 red; putting
* `assistantCorrelationsEnabled` back on the schema turns guard 1 red.
* route turns guard 3 red by file name; deleting the
* `requireAiCapability("documentAi"` calls from the document routes (the only
* reader of that switch's capabilities in the route tree) turns guard 2 red;
* putting `assistantCorrelationsEnabled` back on the schema turns guard 1 red.
*/
import { readdirSync, readFileSync, statSync } from "node:fs";
import path from "node:path";
@@ -99,18 +98,7 @@ const PLUMBING = [
* Switches with no reader yet, and why that is correct for now. An entry is
* a claim with an expiry: the test below fails as soon as a reader appears.
*/
const AWAITING_READER: Record<string, string> = {
documentAi:
"The capabilities it covers (documentAi, labsOcr, medicationExtract) are " +
"resolved and published, but the document, lab-scan and medication " +
"extraction routes move onto requireAiCapability in the same release; " +
"until then the master switch is what stops them.",
};
/**
* Every file that still calls the retired gate. Only ever shrinks.
*/
const RETIRED_GATE_CALLERS = ["src/app/api/medications/extract/route.ts"];
const AWAITING_READER: Record<string, string> = {};
function sourceFiles(dir: string, acc: string[] = []): string[] {
for (const entry of readdirSync(dir)) {
@@ -223,7 +211,6 @@ describe("no assistant sub-switch is a dead switch", () => {
.join("\n");
function hasReader(toggle: string): boolean {
if (corpus.includes(`requireAssistantSurface("${toggle}")`)) return true;
if (new RegExp(`flags\\.${toggle}\\b`).test(corpus)) return true;
const capabilities = AI_CAPABILITY_KEYS.filter(
(key) => AI_CAPABILITIES[key].operatorSwitch === toggle,
@@ -257,37 +244,28 @@ describe("no assistant sub-switch is a dead switch", () => {
});
});
describe("the retired gate only shrinks", () => {
const CALL = /(?:await|return|=)\s*requireAssistantSurface\s*\(/;
const callers = SOURCES.filter(
(file) =>
rel(file) !== "src/lib/feature-flags/index.ts" && CALL.test(code(file)),
)
.map(rel)
.sort();
describe("the retired gate stays gone", () => {
const NAMES = /\b(?:requireAssistantSurface|AssistantDisabledError)\b/;
it("finds the callers it is meant to judge", () => {
// A matcher that stopped matching would agree with an empty list.
expect(callers.length).toBe(RETIRED_GATE_CALLERS.length);
});
it("gains no new caller", () => {
const added = callers.filter(
(file) => !RETIRED_GATE_CALLERS.includes(file),
);
it("is neither defined nor called anywhere in the source tree", () => {
// The matcher is proven able to match before its empty answer counts.
expect(NAMES.test('await requireAssistantSurface("coach")')).toBe(true);
expect(NAMES.test("new AssistantDisabledError(s)")).toBe(true);
expect(SOURCES.length).toBeGreaterThan(100);
const offenders = SOURCES.filter((file) => NAMES.test(code(file))).map(rel);
expect(
added,
"a new route calls requireAssistantSurface; use requireAiCapability",
offenders,
"the retired operator-only gate is back; use requireAiCapability",
).toEqual([]);
});
it("forgets a caller once it has moved to the capability gate", () => {
const moved = RETIRED_GATE_CALLERS.filter(
(file) => !callers.includes(file),
it("keeps the operator code family on the capability refusal", async () => {
const { aiRefusal } = await import("@/lib/ai/capabilities/refusal");
expect(aiRefusal("coach", "operator_disabled").meta.errorCode).toBe(
"assistant.disabled.coach",
);
expect(aiRefusal("statusText", "operator_disabled").meta.errorCode).toBe(
"assistant.disabled.insightStatus",
);
expect(
moved,
"these no longer call requireAssistantSurface; remove them from the list",
).toEqual([]);
});
});
-41
View File
@@ -21,9 +21,6 @@ import type {
* a route that serves or calls a model asks the resolver, not this file.
*/
/** A sub-switch name. Also the last segment of `assistant.disabled.<switch>`. */
export type AssistantSurface = AiOperatorSwitch;
/** The resolved switch set, master applied. */
export type AssistantFlagSet = AiOperatorSwitchSet;
@@ -104,41 +101,3 @@ export function resolveAssistantFlags(raw: AssistantFlagSet): AssistantFlagSet {
if (!raw.enabled) return { ...ASSISTANT_FLAGS_OFF };
return { ...raw };
}
/**
* The operator-switch-only refusal, `403 { meta: { errorCode:
* "assistant.disabled.<switch>" } }`.
*
* Being retired. It answers only the operator layer, so a route gated on it
* refuses when a switch is off and says nothing about modules, consent or the
* provider; `requireAiCapability` (`src/lib/ai/capabilities/gate.ts`) answers
* all of them with the same code for the operator case. The routes that still
* call `requireAssistantSurface` are frozen by
* `src/lib/feature-flags/__tests__/no-dead-assistant-flag.test.ts`: the list
* may only shrink, and this class goes with its last caller.
*/
export class AssistantDisabledError extends Error {
readonly surface: AssistantSurface;
readonly errorCode: string;
constructor(surface: AssistantSurface) {
super(`Assistant surface "${surface}" is disabled on this server`);
this.name = "AssistantDisabledError";
this.surface = surface;
this.errorCode = `assistant.disabled.${surface}`;
}
}
/**
* Throws `AssistantDisabledError` when the switch (or the master) is off.
* Retired in favour of `requireAiCapability`; see the class above.
*/
export async function requireAssistantSurface(
surface: AssistantSurface,
): Promise<AssistantFlagSet> {
const flags = await getAssistantFlags();
if (!flags[surface]) {
throw new AssistantDisabledError(surface);
}
return flags;
}