feat(coach): lay down the reasoning, trail and memory contract

Add the shared contract the reasoning release builds on, with no change
to how a turn runs today.

- Schema: operator reasoning controls on app_settings (0376), the
  encrypted trail text on coach_messages (0377), and source,
  last_used_at and source_message_id on coach_facts (0378).
- Provider contract: CompletionParams.reasoning and onReasoning,
  CompletionResult.reasoning and providerState, AiMessage.providerState.
- Reasoning levels, thinking budgets and the background-job table in
  src/lib/ai/reasoning/levels.ts; coachPrefsJson.reasoning, absent
  meaning medium, salvaged field by field like every other pref.
- Stream: activity, memoryNote and planProposal frames, done.stop and
  done.withheldResults, result.interim, a compare chart kind, eight
  table refs, three more clarification kinds with an assumed choice,
  the change_assumption chip, and assumptions, activity, stop,
  memoryNote and planProposal on the provenance. Zod mirror, type
  parity and the native-client key rule cover every new frame.
- Chat request: memoryDecision and planDecision, parsed and not yet
  acted on.
- Stub contracts for the memory functions and the activity recorder,
  inert until their implementations land.
- Backup, restore and rotation carry the new columns; a fact's message
  reference is resolved against the restored messages like its
  conversation reference.
- Message keys for the trail, memory, plans, assumptions, replies,
  interim tables, comparison charts and reasoning settings in all seven
  locales, each reachable from a catalog and checked both ways.
This commit is contained in:
Marc-André Bombeck committed 2026-10-06 18:39:50 +02:00
1 parent f269100b01
commit 210becb28b
38 files changed
+3308 -57

No files matched your search

@@ -698,4 +698,21 @@ describe("a Coach turn's stored tables are bounded on restore", () => {
const sealed = "A".repeat(300 * 1024);
expect(parseWithResults({ resultsEncrypted: sealed }).success).toBe(false);
});
it("bounds the trail's text the same way, at its own 16 KB", () => {
const fits = JSON.stringify({
entries: [{ id: "a1", text: "x".repeat(15 * 1024) }],
});
expect(parseWithResults({ trailJson: fits }).success).toBe(true);
expect(
parseWithResults({ trailEncrypted: "A".repeat(30 * 1024) }).success,
).toBe(true);
const tooLong = JSON.stringify({
entries: [{ id: "a1", text: "x".repeat(17 * 1024) }],
});
expect(parseWithResults({ trailJson: tooLong }).success).toBe(false);
expect(
parseWithResults({ trailEncrypted: "A".repeat(40 * 1024) }).success,
).toBe(false);
});
});
@@ -4,6 +4,7 @@ import {
DEFAULT_COACH_CLUSTERS,
DEFAULT_COACH_PREFS,
coachPrefsSchema,
coachReasoningLevel,
parseCoachPrefs,
} from "../coach-prefs";
@@ -220,3 +221,39 @@ describe("parseCoachPrefs", () => {
);
});
});
describe("reasoning (v1.41)", () => {
it("is absent on a legacy blob and reads as medium", () => {
const prefs = parseCoachPrefs({ tone: "neutral" });
expect(prefs).not.toHaveProperty("reasoning");
expect(coachReasoningLevel(prefs)).toBe("medium");
expect(coachReasoningLevel(DEFAULT_COACH_PREFS)).toBe("medium");
});
it.each(["off", "low", "medium", "high"] as const)(
"round-trips %s",
(level) => {
const prefs = parseCoachPrefs({ reasoning: level });
expect(prefs.reasoning).toBe(level);
expect(coachReasoningLevel(prefs)).toBe(level);
},
);
it("rejects an unknown level on write", () => {
expect(coachPrefsSchema.safeParse({ reasoning: "max" }).success).toBe(
false,
);
});
it("drops an unknown stored level alone and keeps every other field", () => {
const prefs = parseCoachPrefs({
reasoning: "xhigh",
tone: "concise",
excludeMetrics: ["weight"],
});
expect(prefs.reasoning).toBeUndefined();
expect(coachReasoningLevel(prefs)).toBe("medium");
expect(prefs.tone).toBe("concise");
expect(prefs.excludeMetrics).toEqual(["weight"]);
});
});
+28
View File
@@ -21,6 +21,8 @@
*/
import { z } from "zod/v4";
import { RESULTS_MAX_BYTES } from "@/lib/ai/coach/results/refs";
import { TRAIL_MAX_BYTES } from "@/lib/ai/coach/activity/contract";
import { REASONING_MAX_EFFORTS } from "@/lib/ai/reasoning/levels";
import {
AllergyCategory,
AllergySeverity,
@@ -1056,6 +1058,9 @@ const appSettingsBackupSchema = z
// was retired still carries that key; `passthrough` keeps it harmless and
// the restore writes nothing for it.
assistantDocumentAiEnabled: z.boolean().optional(),
// v1.41 — optional for the same reason.
aiReasoningEnabled: z.boolean().optional(),
aiReasoningMaxEffort: z.enum(REASONING_MAX_EFFORTS).optional(),
moduleAvailabilityJson: z.unknown().nullable(),
documentMaxFileBytes: z.number().int(),
documentQuotaBytes: z.string().regex(/^\d+$/),
@@ -1478,6 +1483,21 @@ const coachResultsSealedSchema = base64BytesSchema.refine(
{ message: "Coach result tables exceed the stored size" },
);
/** The trail's model text, bounded at restore like the tables above. */
const COACH_TRAIL_SEALED_MAX_CHARS = 2 * TRAIL_MAX_BYTES;
const coachTrailJsonSchema = z
.string()
.refine(
(value) => new TextEncoder().encode(value).byteLength <= TRAIL_MAX_BYTES,
{ message: `Coach trail exceeds ${TRAIL_MAX_BYTES} bytes` },
);
const coachTrailSealedSchema = base64BytesSchema.refine(
(value) => value.length <= COACH_TRAIL_SEALED_MAX_CHARS,
{ message: "Coach trail exceeds the stored size" },
);
/**
* One Coach turn.
*
@@ -1502,6 +1522,9 @@ const coachMessageBackupSchema = z
// readable JSON on a portable one, absent on every file written before.
resultsEncrypted: coachResultsSealedSchema.nullable().optional(),
resultsJson: coachResultsJsonSchema.nullable().optional(),
// v1.41 — the trail's model text, the same two ends as the tables.
trailEncrypted: coachTrailSealedSchema.nullable().optional(),
trailJson: coachTrailJsonSchema.nullable().optional(),
createdAt: isoDateTime,
})
.passthrough();
@@ -1549,6 +1572,11 @@ const coachFactBackupSchema = z
category: z.string().min(1),
confidence: z.number().int().min(0).max(100).optional(),
sourceConversationId: z.string().nullable().optional(),
// v1.41 — absent on every file written before; restored at the column
// defaults then.
source: z.string().min(1).max(32).optional(),
lastUsedAt: isoDateTime.nullable().optional(),
sourceMessageId: z.string().nullable().optional(),
createdAt: isoDateTime,
updatedAt: isoDateTime,
deletedAt: isoDateTime.nullable().optional(),
+21
View File
@@ -14,6 +14,12 @@
*/
import { z } from "zod/v4";
import {
DEFAULT_REASONING_LEVEL,
REASONING_LEVELS,
type ReasoningLevel,
} from "@/lib/ai/reasoning/levels";
/**
* Tone presets the Coach system-prompt prefix toggles between. v1.4.22
* landed `warm` as the default; `neutral` strips the warmth language
@@ -196,6 +202,16 @@ export const coachPrefsSchema = z.object({
.describe(
"v1.39.4 — offer up to three follow-up chips under the Coach's latest answer. Absent means on; only `false` switches them off.",
),
// v1.41 — how hard the Coach thinks before it answers. No schema default,
// like the two keys above, so a legacy blob and `parse({})` stay
// byte-identical; an absent key reads as `medium` (`coachReasoningLevel`).
// The operator's switch and cap apply on top, server-side.
reasoning: z
.enum(REASONING_LEVELS)
.optional()
.describe(
"v1.41 — how hard the Coach thinks before it answers: `off`, `low`, `medium` or `high`. Absent means `medium`. The operator may switch reasoning off or cap the level; the resolved value is published on `GET /api/auth/me` as `coachReasoning`.",
),
});
export type CoachPrefs = z.infer<typeof coachPrefsSchema>;
@@ -214,6 +230,11 @@ export const DEFAULT_COACH_PREFS: CoachPrefs = {
defaultWindow: "allTime",
};
/** The person's reasoning level; an absent key is the default, `medium`. */
export function coachReasoningLevel(prefs: CoachPrefs): ReasoningLevel {
return prefs.reasoning ?? DEFAULT_REASONING_LEVEL;
}
/**
* Parse a row's `coachPrefsJson` Json blob into a typed `CoachPrefs`,
* falling back to defaults when the row is null. Keeps the call sites at