wave 2 (platform stream): settings storage & plumbing foundation (P2)

- src/core/settings.ts: versioned DELTA record schema + sanitizer (unknown keys preserved)
  — general/chat/agent{models,tools,prompts}/appearance/graph sections
- src/core/settings-resolution.ts: pure resolveSettings (factory defaults → user delta),
  extraction/graph-context channel predicates
- src/store/settings.ts + prompt-overrides.ts: SettingsStore/PromptOverrideStore adapters
  wired through stores.ts (effectiveSettings() fresh per call); lazy migration of
  default-settings.json into record.chat
- app/api/settings/** routes (record, section bodies, prompt overrides per segment)
- chat-handler: graph gates at trigger call-sites + toolToggles injection seam
- config.ts: SETTINGS_FILE + PROMPTS_OVERRIDE_DIR paths

587/587 tests; typecheck/lint/build clean
This commit is contained in:
amosblomqvist
2026-09-19 18:05:30 +03:00
parent 36c5d19437
commit cb4fe25c89
24 changed files with 2096 additions and 101 deletions
+86
View File
@@ -0,0 +1,86 @@
/**
* PUT /api/settings/[section] — section-scoped record writes
* (settings-storage wave, 2026-09-19). One PUT replaces ONE section
* replace-whole (absent fields = absent overrides — the house settings
* discipline, same as the per-chat and defaults routes); sections are
* independent, so partial writes can never clobber each other.
*
* section ∈ general | chat | agent | appearance | graph (else 404).
* Body: the complete desired section object. Parse + validate strictly
* (server/settings-body.ts): a bad shape/type is a 400 carrying the
* supported list where one exists, never a silent clamp. The chat
* section additionally passes the catalog gate (validateChatSettings —
* unknown provider/model or unsupported thinking level = 400), same as
* the defaults route. The agent section additionally validates prompt
* switches: an ON switch must reference a CURRENT source segment with an
* existing override file (an OFF switch may reference anything — users
* cleaning up orphans must not be blocked).
*
* The static siblings (defaults, prompts) take precedence over this
* dynamic segment — Next resolves static routes first, so "prompts" never
* lands here.
*/
import type { AgentSettings, ChatSettings } from "@/src/core";
import {
SETTINGS_SECTIONS,
allSegmentPaths,
promptOverrides,
readSettingsRecord,
validateChatSettings,
writeSettingsRecord,
type SettingsBodyResult,
} from "@/src/server";
export const dynamic = "force-dynamic";
/** One parser, result type erased to the common envelope. */
type AnySectionParser = (body: unknown) => SettingsBodyResult<unknown>;
export async function PUT(request: Request, ctx: { params: Promise<{ section: string }> }) {
const { section } = await ctx.params;
const parser = (SETTINGS_SECTIONS as Record<string, AnySectionParser>)[section];
if (!parser) {
return Response.json(
{ error: `unknown settings section "${section}"`, supported: Object.keys(SETTINGS_SECTIONS) },
{ status: 404 },
);
}
const body = await request.json().catch(() => null);
const parsed = parser(body);
if (!parsed.ok) {
return Response.json({ error: parsed.error }, { status: 400 });
}
// Section-specific cross-validation (against the catalog / the prompt
// store) — the parsers only see shapes.
if (section === "chat") {
const verdict = validateChatSettings(parsed.settings as ChatSettings);
if (!verdict.ok) {
return Response.json({ error: verdict.error, supported: verdict.supported }, { status: 400 });
}
}
if (section === "agent") {
const agent = parsed.settings as AgentSettings;
const segments = new Set(allSegmentPaths());
for (const [path, on] of Object.entries(agent.prompts ?? {})) {
if (on && (!segments.has(path) || promptOverrides.readOverride(path) === null)) {
return Response.json(
{
error: `prompt switch for "${path}" cannot be on: ${
segments.has(path) ? "no override file exists" : "not a current source segment"
}`,
},
{ status: 400 },
);
}
}
}
// Read-modify-write ONE section of the record; everything else rides
// along untouched (other sections, unknown keys — sanitize preserves).
const record = readSettingsRecord() ?? { version: 1 };
const next = { ...record, [section]: parsed.settings };
writeSettingsRecord(next);
return Response.json({ settings: next });
}
@@ -0,0 +1,54 @@
/**
* PUT/DELETE /api/settings/prompts/[...segment] — the override TEXT for
* one prompt segment (settings-storage wave, 2026-09-19).
*
* PUT body {text} → writes data/prompts/<segment path mirror>. 200.
* The segment must be a CURRENT source segment (allSegmentPaths
* — derived from src/agent/prompts at runtime): overriding a
* segment that doesn't compose is a typo or a vanished fragment,
* a 400, never a silent orphan.
* DELETE → removes the override file (idempotent). Switches are NOT
* touched — an on-switch with no file composes the source
* default (inert by design), so the user's switch state survives
* a delete/re-write cycle.
*
* The ON/OFF switch itself lives in the record's agent.prompts map
* (PUT /api/settings/agent) — file presence alone is never the override.
*/
import { allSegmentPaths, isValidSegmentPath, promptOverrides } from "@/src/server";
export const dynamic = "force-dynamic";
/** Re-join the catch-all segments into the mirror-layout path; null when
* the shape is invalid (traversal, wrong layout — the store re-guards). */
function segmentPathFrom(segments: string[]): string | null {
const joined = segments.map(decodeURIComponent).join("/");
return isValidSegmentPath(joined) ? joined : null;
}
export async function PUT(request: Request, ctx: { params: Promise<{ segment: string[] }> }) {
const { segment } = await ctx.params;
const path = segmentPathFrom(segment);
if (!path) return Response.json({ error: "invalid segment path" }, { status: 400 });
const body = (await request.json().catch(() => null)) as { text?: unknown } | null;
if (!body || typeof body.text !== "string") {
return Response.json({ error: "body must be {text: string}" }, { status: 400 });
}
if (!new Set(allSegmentPaths()).has(path)) {
return Response.json(
{ error: `"${path}" is not a current source segment`, supported: allSegmentPaths() },
{ status: 400 },
);
}
promptOverrides.writeOverride(path, body.text);
return Response.json({ path, text: body.text });
}
export async function DELETE(_request: Request, ctx: { params: Promise<{ segment: string[] }> }) {
const { segment } = await ctx.params;
const path = segmentPathFrom(segment);
if (!path) return Response.json({ error: "invalid segment path" }, { status: 400 });
promptOverrides.deleteOverride(path);
return Response.json({ path, deleted: true });
}
+29
View File
@@ -0,0 +1,29 @@
/**
* GET /api/settings/prompts — the system-prompt segment view
* (settings-storage wave, 2026-09-19): the effective prompt segments for
* BOTH agents, derived from SOURCE at runtime (src/agent/prompts — the
* list adapts when the code ships/renames/removes fragments), each with
* its source text, override text (if a file exists), and effective switch
* state (settings record's agent.prompts map AND file presence).
*
* GET → 200 {prober: SegmentInfo[], teacher: SegmentInfo[]}
* SegmentInfo = {path, sourceText, overrideText, enabled, shared}
*
* The shared base appears in BOTH lists under the SAME path
* ("system-prompt.md") — the prompt-editor's "what's constant between the
* two agents" is discoverable by path equality. Writes: the switches go
* through PUT /api/settings/agent; the TEXT goes through
* PUT/DELETE /api/settings/prompts/[...segment].
*/
import { effectivePromptSegments, readSettingsRecord } from "@/src/server";
export const dynamic = "force-dynamic";
export async function GET() {
const switches = readSettingsRecord()?.agent?.prompts ?? {};
return Response.json({
prober: effectivePromptSegments("prober", switches),
teacher: effectivePromptSegments("teacher", switches),
});
}
+23
View File
@@ -0,0 +1,23 @@
/**
* GET /api/settings — THE user settings record (settings-storage wave,
* 2026-09-19): the whole delta record at data/settings.json (config.
* SETTINGS_FILE, via the SettingsStore port). Non-secret by construction —
* secrets live in auth.json / .env.local and never enter this record.
*
* GET → 200 {settings} (the sanitized delta record — absent keys mean
* "factory default", never guessed server-side) or 200
* {settings: null} on first boot.
*
* Section writes go through PUT /api/settings/[section]; the chat defaults
* also remain writable via the legacy /api/settings/defaults alias.
* Resolution to concrete values is the client's/core's job
* (core/settings-resolution.ts resolveSettings — browser-safe).
*/
import { settingsStore } from "@/src/server";
export const dynamic = "force-dynamic";
export async function GET() {
return Response.json({ settings: settingsStore.readSettings() });
}