Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(core,server,web): agent config kernel version with smart update (#263)

Yaowei Zhengca72a5d7f62b
diff --git a/packages/core/src/state/default-config.ts b/packages/core/src/state/default-config.ts
index 07d25179..295a118f 100644
--- a/packages/core/src/state/default-config.ts
+++ b/packages/core/src/state/default-config.ts
@@ -19,6 +19,7 @@
*/
import type { MCPServerConfig, ThinkingLevelName, ToolDefinitionConfig } from "../interfaces.js";
import type { CompactionMode } from "../omnimessage/types.js";
+import { KERNEL_VERSION } from "./kernel-history.js";
/** Docs: /docs/configuration § "System prompt placeholders". */
export const AGENTS_MD_PLACEHOLDER = "{{AGENTS_MD}}";
@@ -329,6 +330,15 @@ export interface SystemConfig {
description?: string;
/** Agent State version number: a natural number, 1 on creation, incremented on successful optimization; a missing field is treated as 1. */
version?: number;
+ /**
+ * Kernel version: which generation of the built-in defaults this config is based on, as a
+ * date string (`KERNEL_VERSION` at materialization time — creation, restore-defaults, or a
+ * kernel update). Unrelated to `version` (the optimization counter): user edits change
+ * neither the defaults generation nor this stamp — only the three materialization paths
+ * write it. A missing field means the config predates the kernel-version mechanism and is
+ * treated as outdated. See kernel-history.ts / kernel-update.ts.
+ */
+ kernel_version?: string;
/** System-level Prompt (relatively stable; should not be modified frequently). */
system_prompt: string;
/**
@@ -854,6 +864,10 @@ export function agentStateVersion(config: Pick<SystemConfig, "version">): number
export function defaultSystemConfig(): SystemConfig {
return {
version: 1,
+ // Newly materialized configs are stamped with the current defaults generation; the stamp
+ // rides along in resetSystemConfigToDefaults too (it spreads this object), so a restore
+ // also re-stamps.
+ kernel_version: KERNEL_VERSION,
system_prompt: DEFAULT_SYSTEM_PROMPT,
// -1 = unlimited (same sentinel as compaction.max_session_turns): an agent run is never
// cut off by a turn cap unless the user configures a positive limit themselves.
diff --git a/packages/core/src/state/index.ts b/packages/core/src/state/index.ts
index 64bedf97..d58dc008 100644
--- a/packages/core/src/state/index.ts
+++ b/packages/core/src/state/index.ts
@@ -5,6 +5,8 @@
*/
export * from "./paths.js";
export * from "./default-config.js";
+export * from "./kernel-history.js";
+export * from "./kernel-update.js";
export * from "./builtin-agents.js";
export * from "./model-catalog.js";
export * from "./project-config.js";
diff --git a/packages/core/src/state/kernel-history.ts b/packages/core/src/state/kernel-history.ts
new file mode 100644
index 00000000..e41ecc02
--- /dev/null
+++ b/packages/core/src/state/kernel-history.ts
@@ -0,0 +1,229 @@
+/**
+ * Agent config kernel versions: which generation of the built-in defaults a stored
+ * `system_config.yaml` is based on, and the per-leaf hash history that lets the kernel
+ * update (see kernel-update.ts) tell "still the old default" apart from "customized by
+ * the user".
+ *
+ * A kernel version is a date string (`YYYY-MM-DD`). It advances **manually** and only when
+ * the built-in defaults change substantively: the pinned-hash test in
+ * `core/test/kernel-version.test.ts` recomputes every default leaf hash and fails the build
+ * whenever `defaultSystemConfig()` drifts from the latest history entry — the failure message
+ * tells the developer to bump `KERNEL_VERSION` and append a new entry here. Several changes
+ * on the same day may revise that day's entry in place instead of appending (the entry is
+ * only frozen once a later generation exists).
+ *
+ * The user's own edits never move a config between generations: matching is purely by value
+ * hash, and a value that matches no recorded generation is conservatively treated as a user
+ * customization (see kernel-update.ts).
+ */
+import { createHash } from "node:crypto";
+import type { SystemConfig } from "./default-config.js";
+
+/**
+ * The current kernel version — the generation stamp `defaultSystemConfig()` carries in
+ * `kernel_version`, so newly created (and default-restored) configs record which generation
+ * of defaults they materialized. Must equal the newest key of `KERNEL_HASH_HISTORY`; the
+ * pinned-hash test enforces both directions (bump without new hashes, or changed defaults
+ * without a bump, both fail).
+ */
+export const KERNEL_VERSION = "2026-08-11";
+
+/**
+ * Identity / user-data fields excluded from kernel management: never hashed, never written
+ * by a kernel update. `version` is the Agent State optimization counter (unrelated to the
+ * kernel version); `kernel_version` is the stamp itself.
+ */
+const EXCLUDED_TOP_LEVEL_KEYS = new Set(["name", "description", "version", "kernel_version"]);
+
+/** One kernel-managed leaf of the default config: a dotted path and the value at it. */
+export interface KernelLeaf {
+ path: string;
+ value: unknown;
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+
+/**
+ * The kernel-managed leaves of a config, in stable traversal order: scalars and arrays are
+ * atomic leaves; plain objects recurse. Two special cases:
+ *
+ * - `tools.builtin` is broken up **per tool name** (`tools.builtin.<name>`, each entry an
+ * atomic leaf), so a user who customized one tool keeps only that one while the rest
+ * follow a kernel update. Tool names allow no `.` (see assertValidId's character set), so
+ * the dotted path stays unambiguous.
+ * - `tools.mcpServers` is user data (like name/description/version) and is skipped entirely.
+ */
+export function kernelLeafEntries(config: SystemConfig): KernelLeaf[] {
+ const leaves: KernelLeaf[] = [];
+ const visit = (value: unknown, path: string[]): void => {
+ if (value === undefined) return;
+ if (path.length === 1 && EXCLUDED_TOP_LEVEL_KEYS.has(path[0]!)) return;
+ if (path.length === 2 && path[0] === "tools") {
+ if (path[1] === "mcpServers") return;
+ if (path[1] === "builtin" && Array.isArray(value)) {
+ for (const entry of value) {
+ if (isPlainObject(entry) && typeof entry["name"] === "string") {
+ leaves.push({ path: `tools.builtin.${entry["name"]}`, value: entry });
+ }
+ }
+ return;
+ }
+ }
+ if (isPlainObject(value)) {
+ for (const key of Object.keys(value)) visit(value[key], [...path, key]);
+ return;
+ }
+ leaves.push({ path: path.join("."), value });
+ };
+ for (const key of Object.keys(config)) {
+ visit((config as unknown as Record<string, unknown>)[key], [key]);
+ }
+ return leaves;
+}
+
+/**
+ * Canonical JSON: object keys sorted recursively (arrays keep order, `undefined` properties
+ * dropped), so the hash is insensitive to key order — a YAML round-trip or a hand edit that
+ * only reorders keys still counts as the same value.
+ */
+function canonicalJson(value: unknown): string {
+ if (Array.isArray(value)) return `[${value.map((v) => canonicalJson(v)).join(",")}]`;
+ if (isPlainObject(value)) {
+ const parts = Object.keys(value)
+ .sort()
+ .filter((key) => value[key] !== undefined)
+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`);
+ return `{${parts.join(",")}}`;
+ }
+ return JSON.stringify(value) ?? "null";
+}
+
+/** sha256 hex of a value's canonical JSON — the unit of comparison for kernel matching. */
+export function hashKernelValue(value: unknown): string {
+ return createHash("sha256").update(canonicalJson(value), "utf8").digest("hex");
+}
+
+/** `{ leafPath: sha256 }` over a config's kernel-managed leaves (see kernelLeafEntries). */
+export function computeKernelHashes(config: SystemConfig): Record<string, string> {
+ const hashes: Record<string, string> = {};
+ for (const { path, value } of kernelLeafEntries(config)) {
+ hashes[path] = hashKernelValue(value);
+ }
+ return hashes;
+}
+
+/**
+ * Whether a stored kernel stamp is behind the current one: a missing stamp (every config
+ * from before the mechanism) always counts as outdated; date strings compare
+ * lexicographically, so a stamp from a *newer* build (e.g. after a downgrade) does not.
+ */
+export function isKernelOutdated(kernelVersion: string | null | undefined): boolean {
+ return typeof kernelVersion !== "string" || kernelVersion < KERNEL_VERSION;
+}
+
+/**
+ * Per-generation pinned hashes of the built-in defaults: `{ kernelVersion: { leafPath:
+ * sha256 } }`, oldest first. These are **literals, frozen once a later generation exists**
+ * (only the newest entry may still be revised, on a same-day change) — they must keep
+ * matching what old `system_config.yaml` files actually contain even as the current defaults
+ * evolve, exactly like the LEGACY_* template constants in default-config.ts.
+ *
+ * Seeded generations:
+ *
+ * - `"2026-08-10"` — the generation *before* the prompt-injection toggles (PR #257): no
+ * `vault` / `skills` / `schedules` sections, and the default template carried the hardcoded
+ * legacy # Vault / # Skills sections instead of the `{{VAULT}}` / `{{SKILLS}}` /
+ * `{{SCHEDULES}}` placeholders. The date is a retroactive label (configs of that era carry
+ * no stamp, so the key never has to match anything on disk; matching is purely by hash).
+ * The test suite proves these hashes equal a byte-exact reconstruction of that era's
+ * defaults from the frozen LEGACY_* constants.
+ * - `"2026-08-11"` (current) — the toggles generation, pinned by the guard test.
+ *
+ * Generations older than the seeded ones cannot be fully reconstructed; their values match
+ * no recorded hash and are conservatively kept by a kernel update (restore-default-config is
+ * the recourse for a full refresh).
+ */
+export const KERNEL_HASH_HISTORY: Readonly<Record<string, Readonly<Record<string, string>>>> = {
+ "2026-08-10": {
+ system_prompt: "7c0dce1e6b4a7b94aaec5f09d4c7bc9bf104c46c9167fdca9543306b9e1ba595",
+ max_turns: "1bad6b8cf97131fceab8543e81f7757195fbb1d36b376ee994ad1cf17699c464",
+ "model.max_tokens": "492f431bae35265f2e5f4ed49bd8c58dda912431be561504846988d00d05d117",
+ "model.thinking_level": "60d4c90eee5e731df8d3ef2891de541d2e755ff8ee9db358e26bdec49f6e0db9",
+ "model.timeoutMs": "4f9f73b34c5b89879aad65a48025f3187dd9ce6dc3d4e88eecb2fc79227350f1",
+ "compaction.max_context_length":
+ "8eda794b86cb709202a0023fd5273e3de6d24117b7e36b9bdb53c0238dac4785",
+ "compaction.max_session_turns":
+ "1bad6b8cf97131fceab8543e81f7757195fbb1d36b376ee994ad1cf17699c464",
+ "compaction.mode": "e58fac0b4b9c0f29b3d224da119dff5f6517a40d139faf92e309705b98bd410a",
+ "compaction.prompt": "8ed55781e8071083f8246ed70d9e063ee729d3872d5bc6a2bedfa9c99aed6ae5",
+ "memory.enabled": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b",
+ "memory.prompt": "9380e2382e5dd3d37a6470b0bc0d27c9ed113fa9a54ff78122784c57a16b992c",
+ "memory.workspace_prompt": "76c5a8e18a568f471593ef1da6d75d2596f27619cb877703b2dd28bb0554e0d5",
+ "tools.builtin.read_file": "858f128945421043f5f373c908a0ee081e93e9413debaa49c8c7af1c1c76db3c",
+ "tools.builtin.edit_file": "165a3e2dabe3d13200a1670f3c23ed2d6561c508439db1972db066719f3549ef",
+ "tools.builtin.write_file": "c98253bd5a3b6ff021accda91af016a809a9b50ce56f38a3ed60eeb673c0b130",
+ "tools.builtin.exec_command":
+ "16b327e5c3617b7c4d21505c9d1a72dd33a74de97cd5c60d6c4538b8ec408421",
+ "tools.builtin.input_command":
+ "4c907500cda145161a9481803cfb57ed814b6793e762fd6284510187e9d781c8",
+ "tools.builtin.run_subagent":
+ "c3f93add8da3032850fb2e1f484e2d6ddf97e57d73639d887549494ce9f15fb2",
+ "tools.builtin.input_subagent":
+ "22cc4648d773e8422e80a12a7a095b00b7f7eb01ab5a9ea080858dcd7517b4e3",
+ "tools.builtin.read_image": "05b797a88df1e6a90fb3da67ec654b206f8d81291f89d160a505620afcea38bb",
+ "tools.builtin.describe_image":
+ "fad6d0cdd483eb53b5d243c0508024ab3b708ce6d3c81933acd291f05d4a265f",
+ },
+ "2026-08-11": {
+ system_prompt: "de8952daede04db17400c5cd59b279eccf523cf2d8a0ecedfa37a96de7925b44",
+ max_turns: "1bad6b8cf97131fceab8543e81f7757195fbb1d36b376ee994ad1cf17699c464",
+ "model.max_tokens": "492f431bae35265f2e5f4ed49bd8c58dda912431be561504846988d00d05d117",
+ "model.thinking_level": "60d4c90eee5e731df8d3ef2891de541d2e755ff8ee9db358e26bdec49f6e0db9",
+ "model.timeoutMs": "4f9f73b34c5b89879aad65a48025f3187dd9ce6dc3d4e88eecb2fc79227350f1",
+ "compaction.max_context_length":
+ "8eda794b86cb709202a0023fd5273e3de6d24117b7e36b9bdb53c0238dac4785",
+ "compaction.max_session_turns":
+ "1bad6b8cf97131fceab8543e81f7757195fbb1d36b376ee994ad1cf17699c464",
+ "compaction.mode": "e58fac0b4b9c0f29b3d224da119dff5f6517a40d139faf92e309705b98bd410a",
+ "compaction.prompt": "8ed55781e8071083f8246ed70d9e063ee729d3872d5bc6a2bedfa9c99aed6ae5",
+ "memory.enabled": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b",
+ "memory.prompt": "9380e2382e5dd3d37a6470b0bc0d27c9ed113fa9a54ff78122784c57a16b992c",
+ "memory.workspace_prompt": "76c5a8e18a568f471593ef1da6d75d2596f27619cb877703b2dd28bb0554e0d5",
+ "vault.enabled": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b",
+ "vault.prompt": "66e607aa4e205413f1816a677bed31af2d8c24218e71b55adba54aff5aa094ce",
+ "skills.enabled": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b",
+ "skills.prompt": "42934d17f5dd9c02dfa7c1d37f255dea92bd36905c96a54775c65ef7db713bd9",
+ "schedules.enabled": "b5bea41b6c623f7c09f1bf24dcae58ebab3c0cdd90ad966bc43a45b44867e12b",
+ "schedules.prompt": "3c690ff9bb3e4d423b2d5dfce74f5890d52bf8ae159cfe135a671ac3d46da75a",
+ "tools.builtin.read_file": "858f128945421043f5f373c908a0ee081e93e9413debaa49c8c7af1c1c76db3c",
+ "tools.builtin.edit_file": "165a3e2dabe3d13200a1670f3c23ed2d6561c508439db1972db066719f3549ef",
+ "tools.builtin.write_file": "c98253bd5a3b6ff021accda91af016a809a9b50ce56f38a3ed60eeb673c0b130",
+ "tools.builtin.exec_command":
+ "16b327e5c3617b7c4d21505c9d1a72dd33a74de97cd5c60d6c4538b8ec408421",
+ "tools.builtin.input_command":
+ "4c907500cda145161a9481803cfb57ed814b6793e762fd6284510187e9d781c8",
+ "tools.builtin.run_subagent":
+ "c3f93add8da3032850fb2e1f484e2d6ddf97e57d73639d887549494ce9f15fb2",
+ "tools.builtin.input_subagent":
+ "22cc4648d773e8422e80a12a7a095b00b7f7eb01ab5a9ea080858dcd7517b4e3",
+ "tools.builtin.read_image": "05b797a88df1e6a90fb3da67ec654b206f8d81291f89d160a505620afcea38bb",
+ "tools.builtin.describe_image":
+ "fad6d0cdd483eb53b5d243c0508024ab3b708ce6d3c81933acd291f05d4a265f",
+ },
+};
+
+/**
+ * Every hash any recorded generation gives for a leaf path — the "known default, any era"
+ * test set of the kernel update. A path absent from an old generation (e.g. `vault.*` before
+ * #257) simply contributes nothing there.
+ */
+export function historicalHashesFor(path: string): Set<string> {
+ const hashes = new Set<string>();
+ for (const generation of Object.values(KERNEL_HASH_HISTORY)) {
+ const hash = generation[path];
+ if (hash !== undefined) hashes.add(hash);
+ }
+ return hashes;
+}
diff --git a/packages/core/src/state/kernel-update.ts b/packages/core/src/state/kernel-update.ts
new file mode 100644
index 00000000..a0866fb3
--- /dev/null
+++ b/packages/core/src/state/kernel-update.ts
@@ -0,0 +1,214 @@
+/**
+ * Kernel update: advance a stored `system_config.yaml` to the current built-in defaults
+ * **without losing user customizations** — the smart-merge counterpart of
+ * `resetSystemConfigToDefaults` (which overwrites everything; the two actions sit side by
+ * side in the Web App).
+ *
+ * Per kernel-managed leaf of the current defaults (see kernelLeafEntries):
+ *
+ * - stored value missing → the effective value was already the built-in fallback, so the new
+ * default is materialized (reported `advanced`);
+ * - stored value equal to the new default → untouched, not reported;
+ * - stored value hash-matching **any recorded defaults generation** (KERNEL_HASH_HISTORY) →
+ * it is an old default the user never edited: replaced by the new default (`advanced`);
+ * - anything else → a user customization or an unrecorded generation: conservatively kept
+ * (`kept`). Old generations beyond the seeded ones cannot be reconstructed, so their
+ * values also land here — restore-default-config remains the full-refresh recourse.
+ *
+ * `tools.builtin` merges per tool name: entries the user edited are kept individually while
+ * the rest advance; entries the user added (names outside the defaults) are always kept and
+ * never reported; a default-named entry the user *removed* from a present array stays
+ * removed (`kept`) unless the tool is new in the latest generation — only then is it
+ * genuinely new to this config and appended (`advanced`). If a default tool is ever removed
+ * from the defaults, stale copies are conservatively kept the same way (they fall outside
+ * the traversal base).
+ *
+ * Never touched: `name`, `description`, `version` (the optimization counter) and
+ * `tools.mcpServers` — identity and user-owned data. The file is edited via yaml
+ * `parseDocument`, so comments and untouched content survive (same mechanism as the config
+ * PUT); finally the config is stamped `kernel_version: KERNEL_VERSION`.
+ */
+import fs from "node:fs/promises";
+import { parseDocument, parse as parseYaml } from "yaml";
+import { defaultSystemConfig } from "./default-config.js";
+import {
+ KERNEL_HASH_HISTORY,
+ KERNEL_VERSION,
+ hashKernelValue,
+ kernelLeafEntries,
+} from "./kernel-history.js";
+import { assertValidId } from "./agent-state.js";
+import { systemConfigPath } from "./paths.js";
+
+/** Outcome of a kernel update, path lists in defaults-traversal order (dotted leaf paths, `tools.builtin.<name>` per tool). */
+export interface KernelUpdateResult {
+ /** Leaves written to the new default (previously missing, or an untouched old default). */
+ advanced: string[];
+ /** Leaves left alone because the stored value matches no recorded defaults generation (user customizations — and unrecorded old generations, kept conservatively). */
+ kept: string[];
+ /** The stamp written: always the current KERNEL_VERSION. */
+ kernelVersion: string;
+}
+
+/** Test seam: an alternate hash history (same shape as KERNEL_HASH_HISTORY). Production callers never pass it. */
+export interface KernelUpdateOptions {
+ history?: Readonly<Record<string, Readonly<Record<string, string>>>>;
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+
+/** The stored value at a dotted-path's segments, or undefined when any segment is missing. */
+function getAtPath(root: unknown, segments: string[]): unknown {
+ let current: unknown = root;
+ for (const segment of segments) {
+ if (!isPlainObject(current)) return undefined;
+ current = current[segment];
+ }
+ return current;
+}
+
+export async function applyKernelUpdate(
+ root: string,
+ projectId: string,
+ agentId: string,
+ options?: KernelUpdateOptions,
+): Promise<KernelUpdateResult> {
+ // Validate before building paths, to prevent path traversal.
+ assertValidId("project_id", projectId);
+ assertValidId("agent_id", agentId);
+ const configPath = systemConfigPath(root, projectId, agentId);
+ let raw: string;
+ try {
+ raw = await fs.readFile(configPath, "utf8");
+ } catch {
+ throw new Error(`Agent State config not found: ${configPath} (the Agent does not exist).`);
+ }
+ const parsed = parseYaml(raw) as unknown;
+ const stored = isPlainObject(parsed) ? parsed : {};
+ const doc = parseDocument(raw);
+
+ const history = options?.history ?? KERNEL_HASH_HISTORY;
+ const latestGeneration = Object.keys(history).sort().at(-1);
+ /** Hashes any recorded generation gives for a leaf path (an old generation without the path contributes nothing). */
+ const historicalHashes = (path: string): Set<string> => {
+ const hashes = new Set<string>();
+ for (const generation of Object.values(history)) {
+ const hash = generation[path];
+ if (hash !== undefined) hashes.add(hash);
+ }
+ return hashes;
+ };
+ /** Whether a path is recorded only by the latest generation — i.e. new to the defaults in this generation. */
+ const newInLatestGeneration = (path: string): boolean =>
+ Object.entries(history).every(
+ ([generation, hashes]) => generation === latestGeneration || hashes[path] === undefined,
+ );
+
+ const advanced: string[] = [];
+ const kept: string[] = [];
+
+ /**
+ * setIn that tolerates an invalid intermediate node — a hand-edited dangling `tools:` key
+ * parses as null, and `doc.setIn(["tools", …])` would throw "Expected YAML collection" on
+ * it. Such a section is effectively missing on the read side (every leaf under it reads
+ * undefined and gets materialized), so it is replaced by a map first — once, tracked so a
+ * later leaf of the same section does not wipe the earlier one's write.
+ */
+ const replacedSections = new Set<string>();
+ const setDeep = (segments: string[], value: unknown): void => {
+ for (let i = 1; i < segments.length; i++) {
+ const ancestor = segments.slice(0, i);
+ const key = ancestor.join(".");
+ if (replacedSections.has(key)) continue;
+ const existing = getAtPath(stored, ancestor);
+ if (existing !== undefined && !isPlainObject(existing)) {
+ // createNode: a bare `{}` would be stored verbatim as a JS object, not a YAMLMap,
+ // and the child setIn below would still throw.
+ doc.setIn(ancestor, doc.createNode({}));
+ replacedSections.add(key);
+ }
+ }
+ doc.setIn(segments, value);
+ };
+
+ const defaults = defaultSystemConfig();
+ const defaultTools = defaults.tools?.builtin ?? [];
+ /** The merged tools.builtin array, built only when the stored config carries one (else the whole default array is materialized). */
+ let mergedTools: unknown[] | null = null;
+ let toolsChanged = false;
+ const storedTools = getAtPath(stored, ["tools", "builtin"]);
+ if (Array.isArray(storedTools)) {
+ mergedTools = [...storedTools];
+ }
+
+ for (const { path, value: defaultValue } of kernelLeafEntries(defaults)) {
+ const segments = path.split(".");
+ const defaultHash = hashKernelValue(defaultValue);
+
+ // Per-tool merge over a stored builtin array (a missing array falls through to the
+ // scalar branch below via the `tools.builtin` group write).
+ if (segments[0] === "tools" && segments[1] === "builtin" && mergedTools !== null) {
+ const name = segments[2]!;
+ const index = mergedTools.findIndex(
+ (entry) => isPlainObject(entry) && entry["name"] === name,
+ );
+ if (index === -1) {
+ // Absent from a present array: a deliberate removal is preserved; only a tool that
+ // is new in the latest generation (so this config could never have carried it) is
+ // appended.
+ if (newInLatestGeneration(path)) {
+ mergedTools.push(defaultValue);
+ toolsChanged = true;
+ advanced.push(path);
+ } else {
+ kept.push(path);
+ }
+ continue;
+ }
+ const storedHash = hashKernelValue(mergedTools[index]);
+ if (storedHash === defaultHash) continue;
+ if (historicalHashes(path).has(storedHash)) {
+ mergedTools[index] = defaultValue;
+ toolsChanged = true;
+ advanced.push(path);
+ } else {
+ kept.push(path);
+ }
+ continue;
+ }
+
+ const storedValue =
+ segments[0] === "tools" && segments[1] === "builtin"
+ ? undefined // no stored array: every default tool is materialized below
+ : getAtPath(stored, segments);
+ if (storedValue === undefined) {
+ if (segments[0] === "tools" && segments[1] === "builtin") {
+ // Materialize the whole default array once (per-tool reporting keeps the result
+ // granular); repeated leaves only report, the single setIn happens after the loop.
+ toolsChanged = true;
+ advanced.push(path);
+ continue;
+ }
+ setDeep(segments, defaultValue);
+ advanced.push(path);
+ continue;
+ }
+ const storedHash = hashKernelValue(storedValue);
+ if (storedHash === defaultHash) continue;
+ if (historicalHashes(path).has(storedHash)) {
+ setDeep(segments, defaultValue);
+ advanced.push(path);
+ } else {
+ kept.push(path);
+ }
+ }
+
+ if (toolsChanged) {
+ setDeep(["tools", "builtin"], mergedTools ?? defaultTools);
+ }
+ doc.setIn(["kernel_version"], KERNEL_VERSION);
+ await fs.writeFile(configPath, doc.toString(), "utf8");
+ return { advanced, kept, kernelVersion: KERNEL_VERSION };
+}
diff --git a/packages/core/test/kernel-version.test.ts b/packages/core/test/kernel-version.test.ts
new file mode 100644
index 00000000..5e88d2a9
--- /dev/null
+++ b/packages/core/test/kernel-version.test.ts
@@ -0,0 +1,376 @@
+/**
+ * Agent config kernel versions: the pinned-hash guard (the mechanical definition of "the
+ * defaults changed substantively, bump the kernel version"), the seeded pre-#257 generation's
+ * reconstruction proof, and the smart-merge semantics of applyKernelUpdate (untouched old
+ * defaults advance, customizations and unknown generations are kept, identity fields and
+ * user data are never touched, YAML comments survive, the config is re-stamped).
+ */
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
+import {
+ DEFAULT_AGENT_ID,
+ DEFAULT_PROJECT_ID,
+ KERNEL_HASH_HISTORY,
+ KERNEL_VERSION,
+ LEGACY_SKILLS_SECTION,
+ LEGACY_VAULT_SECTION,
+ SCHEDULES_PLACEHOLDER,
+ SKILLS_PLACEHOLDER,
+ VAULT_PLACEHOLDER,
+ applyKernelUpdate,
+ computeKernelHashes,
+ defaultSystemConfig,
+ isKernelOutdated,
+ kernelLeafEntries,
+ loadOrInitAgentState,
+ resetSystemConfigToDefaults,
+ systemConfigPath,
+ type SystemConfig,
+} from "../src/index.js";
+
+/** The two seeded generations (see KERNEL_HASH_HISTORY's doc comment). */
+const PRE_TOGGLES_GENERATION = "2026-08-10";
+const TOGGLES_GENERATION = "2026-08-11";
+
+/** A mutable plain-object clone of a config, for seeding on-disk scenarios. */
+function mutableConfig(config: SystemConfig): Record<string, unknown> {
+ return structuredClone(config) as unknown as Record<string, unknown>;
+}
+
+/**
+ * Reconstructs the pre-#257 (pre-toggles) default config from the current one: the frozen
+ * LEGACY_* sections swapped back into the template in place of the section placeholders, no
+ * `{{SCHEDULES}}` line, and no vault/skills/schedules config sections — exactly what a
+ * `system_config.yaml` of that era carries (the same recipe prompt-sections.test.ts proves
+ * byte-exact for the template).
+ */
+function preTogglesDefaultConfig(): SystemConfig {
+ const current = defaultSystemConfig();
+ const {
+ vault: _vault,
+ skills: _skills,
+ schedules: _schedules,
+ kernel_version: _stamp,
+ ...rest
+ } = current;
+ return {
+ ...rest,
+ system_prompt: current.system_prompt
+ .split(VAULT_PLACEHOLDER)
+ .join(LEGACY_VAULT_SECTION)
+ .split(SKILLS_PLACEHOLDER)
+ .join(LEGACY_SKILLS_SECTION)
+ .split(`${SCHEDULES_PLACEHOLDER}\n\n`)
+ .join(""),
+ };
+}
+
+describe("kernel hash history (pinned-hash guard)", () => {
+ it("KERNEL_VERSION is a date and the newest history key", () => {
+ expect(KERNEL_VERSION).toMatch(/^\d{4}-\d{2}-\d{2}$/);
+ const keys = Object.keys(KERNEL_HASH_HISTORY);
+ expect(keys.length).toBeGreaterThanOrEqual(2);
+ for (const key of keys) expect(key).toMatch(/^\d{4}-\d{2}-\d{2}$/);
+ expect([...keys].sort().at(-1)).toBe(KERNEL_VERSION);
+ });
+
+ // THE guard: this failing means the built-in defaults changed substantively without a
+ // kernel bump (or vice versa). It is the mechanical definition of "substantive change".
+ it("the current defaults hash exactly to the latest history entry — bump KERNEL_VERSION when this fails", () => {
+ const recomputed = computeKernelHashes(defaultSystemConfig());
+ const pinned = KERNEL_HASH_HISTORY[KERNEL_VERSION] ?? {};
+ const paths = new Set([...Object.keys(recomputed), ...Object.keys(pinned)]);
+ const mismatches = [...paths].filter((p) => recomputed[p] !== pinned[p]).sort();
+ expect(
+ mismatches,
+ "The built-in default config changed substantively (the listed leaf paths no longer " +
+ "hash to the latest KERNEL_HASH_HISTORY entry). Advance the kernel: set " +
+ "KERNEL_VERSION in core/src/state/kernel-history.ts to today's date and append a new " +
+ "history entry with the recomputed hashes (computeKernelHashes(defaultSystemConfig())). " +
+ "Several changes on the same day may revise that day's entry in place instead; never " +
+ "edit an older generation's entry — those are frozen.",
+ ).toEqual([]);
+ });
+
+ // Anchored to the first shipped generation: the reconstruction recipe reads the *current*
+ // defaults, so it only reproduces the pre-toggles era while the current generation is
+ // still the toggles one. Once the defaults evolve past it this proof self-retires — the
+ // pinned hashes remain the frozen source of truth on their own.
+ it.runIf(KERNEL_VERSION === TOGGLES_GENERATION)(
+ "the pre-toggles generation's pinned hashes equal the LEGACY_* reconstruction",
+ () => {
+ expect(computeKernelHashes(preTogglesDefaultConfig())).toEqual(
+ KERNEL_HASH_HISTORY[PRE_TOGGLES_GENERATION],
+ );
+ },
+ );
+
+ it("excludes identity fields and mcpServers from the managed leaves", () => {
+ const paths = kernelLeafEntries({
+ ...defaultSystemConfig(),
+ name: "n",
+ description: "d",
+ tools: { builtin: [], mcpServers: [{ name: "m", config: {} }] },
+ }).map((leaf) => leaf.path);
+ for (const excluded of ["name", "description", "version", "kernel_version"]) {
+ expect(paths).not.toContain(excluded);
+ }
+ expect(paths.some((p) => p.startsWith("tools.mcpServers"))).toBe(false);
+ });
+});
+
+describe("isKernelOutdated", () => {
+ it("missing stamp = outdated; older date = outdated; current and newer are not", () => {
+ expect(isKernelOutdated(null)).toBe(true);
+ expect(isKernelOutdated(undefined)).toBe(true);
+ expect(isKernelOutdated("2026-01-01")).toBe(true);
+ expect(isKernelOutdated(KERNEL_VERSION)).toBe(false);
+ expect(isKernelOutdated("2999-12-31")).toBe(false);
+ });
+});
+
+describe("applyKernelUpdate", () => {
+ let root: string;
+
+ beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-kernel-"));
+ });
+
+ afterEach(async () => {
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ const configPath = () => systemConfigPath(root, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);
+
+ /** Creates the default agent, then rewrites its config file with the given object. */
+ async function seedConfig(config: Record<string, unknown>): Promise<void> {
+ await loadOrInitAgentState({ root });
+ await fs.writeFile(configPath(), stringifyYaml(config), "utf8");
+ }
+
+ async function readConfig(): Promise<SystemConfig> {
+ return parseYaml(await fs.readFile(configPath(), "utf8")) as SystemConfig;
+ }
+
+ const update = () => applyKernelUpdate(root, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);
+
+ it("throws for a nonexistent agent (never initializes one)", async () => {
+ await expect(applyKernelUpdate(root, DEFAULT_PROJECT_ID, "ghost_agent")).rejects.toThrow(
+ /not found/,
+ );
+ });
+
+ it("is a stamped no-op on a freshly created config", async () => {
+ await loadOrInitAgentState({ root });
+ const before = await readConfig();
+ const result = await update();
+ expect(result).toEqual({ advanced: [], kept: [], kernelVersion: KERNEL_VERSION });
+ expect(await readConfig()).toEqual(before);
+ });
+
+ it("advances an untouched pre-toggles config wholesale: template migrated, sections materialized, stamp written", async () => {
+ await seedConfig(mutableConfig(preTogglesDefaultConfig()));
+ const result = await update();
+ expect(result.kept).toEqual([]);
+ expect(result.advanced).toEqual([
+ "system_prompt",
+ "vault.enabled",
+ "vault.prompt",
+ "skills.enabled",
+ "skills.prompt",
+ "schedules.enabled",
+ "schedules.prompt",
+ ]);
+ const defaults = defaultSystemConfig();
+ const written = await readConfig();
+ expect(written.system_prompt).toBe(defaults.system_prompt);
+ expect(written.vault).toEqual(defaults.vault);
+ expect(written.skills).toEqual(defaults.skills);
+ expect(written.schedules).toEqual(defaults.schedules);
+ expect(written.kernel_version).toBe(KERNEL_VERSION);
+ // A second run finds everything current: fully idempotent.
+ expect(await update()).toEqual({ advanced: [], kept: [], kernelVersion: KERNEL_VERSION });
+ });
+
+ it("keeps customized fields (reported) while still stamping", async () => {
+ const config = mutableConfig(preTogglesDefaultConfig());
+ config.system_prompt = "MY CUSTOM PROMPT";
+ (config.memory as Record<string, unknown>).prompt = "my memory prompt";
+ await seedConfig(config);
+ const result = await update();
+ expect(result.kept).toEqual(["system_prompt", "memory.prompt"]);
+ const written = await readConfig();
+ expect(written.system_prompt).toBe("MY CUSTOM PROMPT");
+ expect(written.memory?.prompt).toBe("my memory prompt");
+ // Untouched siblings of a kept leaf still advance independently.
+ expect(written.vault).toEqual(defaultSystemConfig().vault);
+ expect(written.kernel_version).toBe(KERNEL_VERSION);
+ });
+
+ it("keeps values from unknown (unseeded) generations conservatively", async () => {
+ const config = mutableConfig(defaultSystemConfig());
+ delete config.kernel_version;
+ // An ancient default wording we cannot reconstruct: it matches no recorded hash.
+ config.compaction = { mode: "summarize", prompt: "Ancient compaction wording." };
+ await seedConfig(config);
+ const result = await update();
+ expect(result.kept).toContain("compaction.prompt");
+ // The section's *missing* leaves are materialized to the defaults alongside.
+ expect(result.advanced).toContain("compaction.max_context_length");
+ const written = await readConfig();
+ expect(written.compaction?.prompt).toBe("Ancient compaction wording.");
+ expect(written.compaction?.max_context_length).toBe(128000);
+ });
+
+ it("never touches name, description, version or mcpServers", async () => {
+ const config = mutableConfig(preTogglesDefaultConfig());
+ config.name = "Custom Name";
+ config.description = "Custom description";
+ config.version = 7;
+ (config.tools as Record<string, unknown>).mcpServers = [
+ { name: "custom-mcp", config: { command: "custom-server" } },
+ ];
+ await seedConfig(config);
+ const result = await update();
+ expect(result.advanced).not.toContain("name");
+ expect(result.kept).not.toContain("name");
+ const written = await readConfig();
+ expect(written.name).toBe("Custom Name");
+ expect(written.description).toBe("Custom description");
+ expect(written.version).toBe(7);
+ expect(written.tools?.mcpServers).toEqual([
+ { name: "custom-mcp", config: { command: "custom-server" } },
+ ]);
+ });
+
+ it("merges tools.builtin per tool name: the edited one is kept, user-added entries survive, removals stay removed", async () => {
+ const config = mutableConfig(defaultSystemConfig());
+ delete config.kernel_version;
+ const tools = config.tools as { builtin: Array<Record<string, unknown>> };
+ // Customize one default tool, remove another, append a user-defined one.
+ const readFile = tools.builtin.find((t) => t.name === "read_file")!;
+ readFile.description = "my own description";
+ tools.builtin = tools.builtin.filter((t) => t.name !== "edit_file");
+ tools.builtin.push({ name: "my_tool", description: "user-added", permission: "r" });
+ await seedConfig(config);
+
+ const result = await update();
+ expect(result.kept).toEqual(["tools.builtin.read_file", "tools.builtin.edit_file"]);
+ expect(result.advanced).toEqual([]);
+
+ const written = await readConfig();
+ const names = (written.tools?.builtin ?? []).map((t) => t.name);
+ expect(names).not.toContain("edit_file"); // a deliberate removal is preserved
+ expect(names).toContain("my_tool"); // user-added entries survive, unreported
+ const writtenReadFile = written.tools?.builtin?.find((t) => t.name === "read_file");
+ expect(writtenReadFile?.description).toBe("my own description");
+ // The untouched rest still equals the defaults.
+ const writtenExec = written.tools?.builtin?.find((t) => t.name === "exec_command");
+ expect(writtenExec).toEqual(
+ defaultSystemConfig().tools?.builtin?.find((t) => t.name === "exec_command"),
+ );
+ });
+
+ it("materializes the whole default toolset when tools.builtin is missing", async () => {
+ const config = mutableConfig(defaultSystemConfig());
+ delete config.kernel_version;
+ delete config.tools;
+ await seedConfig(config);
+ const result = await update();
+ const defaults = defaultSystemConfig();
+ expect(result.advanced).toEqual(
+ (defaults.tools?.builtin ?? []).map((t) => `tools.builtin.${t.name}`),
+ );
+ expect((await readConfig()).tools?.builtin).toEqual(defaults.tools?.builtin);
+ });
+
+ it("appends a tool only when it is new in the latest generation (history seam)", async () => {
+ const defaults = defaultSystemConfig();
+ const current = computeKernelHashes(defaults);
+ // A fabricated older generation that already knew read_file but never edit_file: a
+ // present array missing read_file is then a deliberate removal (kept), while the same
+ // absence of edit_file means the config simply predates the tool (appended).
+ const history = {
+ "2000-01-01": { "tools.builtin.read_file": current["tools.builtin.read_file"]! },
+ [KERNEL_VERSION]: current,
+ };
+ const config = mutableConfig(defaults);
+ delete config.kernel_version;
+ const tools = config.tools as { builtin: Array<Record<string, unknown>> };
+ tools.builtin = tools.builtin.filter((t) => t.name !== "read_file" && t.name !== "edit_file");
+ await seedConfig(config);
+
+ const result = await applyKernelUpdate(root, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID, {
+ history,
+ });
+ expect(result.kept).toContain("tools.builtin.read_file");
+ expect(result.advanced).toContain("tools.builtin.edit_file");
+ const names = ((await readConfig()).tools?.builtin ?? []).map((t) => t.name);
+ expect(names).not.toContain("read_file");
+ expect(names).toContain("edit_file");
+ });
+
+ it("tolerates dangling/invalid section keys (a hand-edited `tools:` with no value parses as null)", async () => {
+ await loadOrInitAgentState({ root });
+ await fs.writeFile(
+ configPath(),
+ // model is an invalid scalar, tools a dangling key: both sections read as missing and
+ // must be materialized to the defaults instead of crashing setIn.
+ "system_prompt: custom\nmodel: 3\ntools:\n",
+ "utf8",
+ );
+ const result = await update();
+ expect(result.kept).toEqual(["system_prompt"]);
+ const defaults = defaultSystemConfig();
+ const written = await readConfig();
+ expect(written.model).toEqual(defaults.model);
+ expect(written.tools?.builtin).toEqual(defaults.tools?.builtin);
+ expect(written.system_prompt).toBe("custom");
+ expect(written.kernel_version).toBe(KERNEL_VERSION);
+ });
+
+ it("preserves YAML comments on untouched content", async () => {
+ await loadOrInitAgentState({ root });
+ const raw = await fs.readFile(configPath(), "utf8");
+ await fs.writeFile(
+ configPath(),
+ `# my precious comment\n${raw.replace("max_turns: -1", "max_turns: 5")}`,
+ "utf8",
+ );
+ const result = await update();
+ // max_turns 5 is a customization (no generation ever defaulted to 5) — kept.
+ expect(result.kept).toEqual(["max_turns"]);
+ const after = await fs.readFile(configPath(), "utf8");
+ expect(after).toContain("# my precious comment");
+ expect((await readConfig()).max_turns).toBe(5);
+ });
+});
+
+describe("kernel stamping on the materialization paths", () => {
+ let root: string;
+
+ beforeEach(async () => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-kernel-stamp-"));
+ });
+
+ afterEach(async () => {
+ await fs.rm(root, { recursive: true, force: true });
+ });
+
+ it("a newly created agent is stamped with the current kernel version", async () => {
+ const state = await loadOrInitAgentState({ root });
+ expect(state.systemConfig.kernel_version).toBe(KERNEL_VERSION);
+ });
+
+ it("restore-defaults re-stamps a config that predates the mechanism", async () => {
+ await loadOrInitAgentState({ root });
+ const configPath = systemConfigPath(root, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);
+ await fs.writeFile(configPath, "system_prompt: old\nversion: 3\n", "utf8");
+ const written = await resetSystemConfigToDefaults(root, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);
+ expect(written.kernel_version).toBe(KERNEL_VERSION);
+ expect(written.version).toBe(3);
+ });
+});
diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.md
index 9310b7e2..bad904e7 100644
--- a/packages/docs/content/configuration.en.md
+++ b/packages/docs/content/configuration.en.md
@@ -97,6 +97,7 @@ Edit this file via the CLI (`penguin config model …`) or the Web Models page
| `name` | — | Agent display name (falls back to the id) |
| `description` | — | Agent description |
| `version` | `1` | Agent State version (a natural number), incremented on each successful optimization |
+| `kernel_version` | current kernel version | Config kernel version (a date string): which generation of the built-in defaults this config is based on, stamped at creation, restore-defaults and kernel update; unrelated to `version`, never changed by user edits; missing = predates the mechanism (i.e. outdated) |
| `system_prompt` | built-in template | Required; the only template with placeholder substitution |
| `max_turns` | `-1` | Maximum LLM turns per Task (`-1` = unlimited; a positive integer caps the Task) |
| `model.max_tokens` | `32000` | Output Token ceiling per Request (-1 = no cap, provider default); each request clamps the effective value to the model's `context_window` minus the estimated input, so a small-window model never gets asked for more than fits |
@@ -149,7 +150,12 @@ compaction:
# parameters JSON Schema) for every tool you keep — see Tools & Approval.
```
-An existing Agent always runs with its on-disk config verbatim — newer code defaults are never merged in automatically. To adopt the current defaults (for example an updated built-in system prompt), use the settings page's **Restore default configuration** action: like a skill update it overwrites the existing configuration — custom system prompt, tool list, model/compaction settings and MCP Servers — keeping only `name`, `description` and `version`.
+An existing Agent always runs with its on-disk config verbatim — newer code defaults are never merged in automatically. When the built-in defaults change substantively, the config's `kernel_version` falls behind the current kernel and the settings page and agents list show an update hint. Two paths adopt the current defaults (side by side on the settings overview):
+
+- **Update kernel**: a lossless merge. Field by field: a missing field, or one still equal to a *recorded* generation's built-in default, follows the current default; a user-edited field stays unchanged and is listed in the result. `tools.builtin` merges per tool name — only the edited tool is kept, the rest follow, and user-added entries are untouched; `name`, `description`, `version` and `tools.mcpServers` are never touched. The config is then stamped with the current `kernel_version`. Matching is **conservative**: only values whose hash hits a recorded generation count as old defaults — generations too old to reconstruct are kept as if customized.
+- **Restore default configuration**: like a skill update, overwrites the existing configuration with the current defaults — custom system prompt, tool list, model/compaction settings and MCP Servers — keeping only `name`, `description` and `version`. The full-refresh fallback when the kernel update's conservative matching leaves fields behind.
+
+For developers: `kernel_version` advances manually, and only on a substantive change to the built-in defaults (using that day's date). The pinned-hash test in CI (`core/test/kernel-version.test.ts`) recomputes every default leaf hash against the latest `kernel-history.ts` entry and fails on drift, telling you to bump `KERNEL_VERSION` and append a new entry; several changes on the same day may revise that day's entry, while older entries are frozen forever — they are what identifies "still the old default".
### System prompt placeholders
diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.md
index fdfe559f..b9ba82c9 100644
--- a/packages/docs/content/configuration.zh.md
+++ b/packages/docs/content/configuration.zh.md
@@ -97,6 +97,7 @@ output = 0.857143
| `name` | — | Agent 展示名(缺省回退到 id) |
| `description` | — | Agent 描述 |
| `version` | `1` | Agent State 版本号(自然数),每次成功优化自增 |
+| `kernel_version` | 当前内核版本 | 配置内核版本(日期字符串):记录该配置基于哪一代内置默认,创建、还原默认与更新内核时盖章;与 `version` 无关,用户编辑不改变它,缺失视为早于内核版本机制(即过期) |
| `system_prompt` | 内置模板 | 必填;唯一进行占位符替换的模板 |
| `max_turns` | `-1` | 单个 Task 的最大 LLM 轮数(`-1` 不限制,正整数为上限) |
| `model.max_tokens` | `32000` | 单次输出 Token 天花板(-1 不设上限,用服务商默认);每次请求会把实际值收敛到模型 `context_window` 减估算输入以内,小窗口模型不会被索要放不下的输出 |
@@ -149,7 +150,12 @@ compaction:
# 参见「工具与审批」页。
```
-既有 Agent 始终按其磁盘上的配置原样运行——更新后的代码默认值不会自动合并。要采用当前默认值(例如更新后的内置系统提示词),可使用设置页的**还原为默认配置**操作:与 Skill 更新同语义,会用当前默认值覆盖现有配置——自定义系统提示词、工具列表、模型/压缩参数与 MCP Server——仅保留 `name`、`description` 与 `version`。
+既有 Agent 始终按其磁盘上的配置原样运行——更新后的代码默认值不会自动合并。内置默认发生实质变化时,配置的 `kernel_version` 落后于当前内核版本,详情页与智能体列表会给出更新提示。采用当前默认值有两条路径(同在设置页概览、相邻放置):
+
+- **更新内核**:无损合并。逐字段比对:字段缺失、或仍等于某一代已记录的内置默认,跟进当前默认;被用户改过的保持不变并在结果中列出。`tools.builtin` 按工具名逐个比对——只保留改过的那一个,其余照常跟进,用户自加的条目不受影响;`name`、`description`、`version` 与 `tools.mcpServers` 永不触碰。完成后盖章 `kernel_version`。比对是**保守**的:只有哈希命中已记录代际的值才被视为旧默认,太老而无法识别的代际一律按自定义保留。
+- **还原为默认配置**:与 Skill 更新同语义,用当前默认值覆盖现有配置——自定义系统提示词、工具列表、模型/压缩参数与 MCP Server——仅保留 `name`、`description` 与 `version`。更新内核因保守保留而没跟上时,这是全量刷新的兜底。
+
+面向开发者:`kernel_version` 只在对内置默认做出实质修改时手动前进(取当日日期)。CI 的 pinned-hash 测试(`core/test/kernel-version.test.ts`)重算全部默认字段哈希并与 `kernel-history.ts` 最新条目比对,不一致即失败并提示更新 `KERNEL_VERSION`、追加新条目;同日多次变更可修订当日条目,历史条目一经冻结不再改动——它们就是「仍是旧默认」的识别依据。
### 系统提示词占位符
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index fb9bbd5b..82516f42 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -502,6 +502,8 @@ export interface AgentSummary {
toolCount: number;
/** Agent State version number (the `version` in system_config.yaml; treated as 1 if missing). */
version: number;
+ /** Whether the config's kernel stamp is behind the current defaults generation (a missing stamp counts as outdated) — drives the list card's update hint. */
+ kernelOutdated: boolean;
/** Vault key count (number of keys in agent_state/.vault.toml). */
vaultKeyCount: number;
/** Schedule count (number of .toml files under agent_state/schedule/, including invalid ones). */
@@ -594,6 +596,12 @@ export interface AgentConfigDto {
description?: string;
/** Agent State version number (treated as 1 if missing; shown in the settings page overview). */
version: number;
+ /** The stored kernel stamp (`kernel_version`): which defaults generation the config is based on; null when the config predates the kernel-version mechanism. */
+ kernelVersion: string | null;
+ /** The current defaults generation (core's KERNEL_VERSION) — what a kernel update would stamp. */
+ kernelLatest: string;
+ /** Whether the stamp is behind kernelLatest (a missing stamp counts as outdated). */
+ kernelOutdated: boolean;
systemPrompt: string;
maxTurns?: number;
model?: AgentModelConfigDto;
@@ -616,6 +624,20 @@ export interface AgentConfigResponse {
activeSessionCount: number;
}
+/**
+ * POST …/config/kernel-update result: the smart merge's outcome (core's applyKernelUpdate).
+ * Paths are dotted config leaves (`system_prompt`, `memory.prompt`, `tools.builtin.<name>`…)
+ * in defaults-traversal order; the client maps them to display names.
+ */
+export interface AgentKernelUpdateResponse {
+ /** Leaves advanced to the new default (previously missing, or an untouched old default). */
+ advanced: string[];
+ /** Leaves kept because the stored value matches no recorded defaults generation (user customizations, kept conservatively). */
+ kept: string[];
+ /** The kernel stamp written (the current defaults generation). */
+ kernelVersion: string;
+}
+
/** POST …/config/mcp-test result: reachability of one MCP Server entry. */
export interface McpServerTestResponse {
ok: boolean;
diff --git a/packages/server/src/http/routes/agent-config.ts b/packages/server/src/http/routes/agent-config.ts
index 5d4716d5..a5025c09 100644
--- a/packages/server/src/http/routes/agent-config.ts
+++ b/packages/server/src/http/routes/agent-config.ts
@@ -2,8 +2,9 @@
* Agent config routes (reads/writes system_config.yaml and AGENTS.md):
* GET|PUT /api/projects/:p/agents/:a/config, plus POST …/config/reset to adopt the
* current default config (keeps only name/description/version — the config-side
- * analogue of a skill update) and POST …/config/mcp-test to probe one MCP Server
- * entry's reachability. Members can read and write (unrestricted).
+ * analogue of a skill update), POST …/config/kernel-update to smart-merge up to the
+ * current defaults generation (customizations kept), and POST …/config/mcp-test to
+ * probe one MCP Server entry's reachability. Members can read and write (unrestricted).
*/
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
@@ -14,6 +15,7 @@ import type { MCPServerConfig } from "@prismshadow/penguin-core";
import type {
AgentConfigResponse,
AgentConfigUpdateRequest,
+ AgentKernelUpdateResponse,
McpServerTestResponse,
} from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
@@ -125,6 +127,18 @@ export function agentConfigRoutes(deps: AppDeps): Hono<AppEnv> {
}
});
+ // Smart-merge the config up to the current defaults generation (see
+ // AgentConfigService.kernelUpdate): non-destructive sibling of /reset, same member-level
+ // authorization as /reset and PUT. Responds with the merge report (advanced / kept paths +
+ // the new stamp); the client re-GETs the config for the fresh values.
+ app.post("/kernel-update", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const agentId = requireValidId(c, "agentId");
+ deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ const result = await deps.agentConfigService.kernelUpdate(projectId, agentId);
+ return c.json(result satisfies AgentKernelUpdateResponse);
+ });
+
// Overwrite system_config.yaml with the current defaults (see AgentConfigService.resetConfig
// for the exact semantics); same authorization as PUT, and responds like GET/PUT with the
// fresh config so the client can refresh in place.
diff --git a/packages/server/src/services/agent-config-service.ts b/packages/server/src/services/agent-config-service.ts
index 7a9fe64f..407f44ef 100644
--- a/packages/server/src/services/agent-config-service.ts
+++ b/packages/server/src/services/agent-config-service.ts
@@ -15,9 +15,12 @@ import {
DEFAULT_SCHEDULES_PROMPT,
DEFAULT_SKILLS_PROMPT,
DEFAULT_VAULT_PROMPT,
+ KERNEL_VERSION,
LEGACY_SKILLS_SECTION,
LEGACY_VAULT_SECTION,
agentsMdPath,
+ applyKernelUpdate,
+ isKernelOutdated,
agentStateDir,
agentStateVersion,
hasSchedulesPlaceholder,
@@ -42,6 +45,7 @@ import type {
import type {
AgentConfigDto,
AgentConfigUpdateRequest,
+ AgentKernelUpdateResponse,
AgentModelConfigDto,
AgentCompactionConfigDto,
AgentMemoryConfigDto,
@@ -105,7 +109,13 @@ export class AgentConfigService {
async readCardMeta(
projectId: string,
agentId: string,
- ): Promise<{ name?: string; description?: string; toolCount: number; version: number }> {
+ ): Promise<{
+ name?: string;
+ description?: string;
+ toolCount: number;
+ version: number;
+ kernelOutdated: boolean;
+ }> {
try {
const raw = await fs.readFile(systemConfigPath(this.root, projectId, agentId), "utf8");
const parsed = asRecord(parseYaml(raw));
@@ -116,9 +126,13 @@ export class AgentConfigService {
...(typeof parsed.description === "string" ? { description: parsed.description } : {}),
toolCount: countOf(tools.builtin) + countOf(tools.mcpServers),
version: agentStateVersion({ version: parsed.version as number | undefined }),
+ kernelOutdated: isKernelOutdated(
+ typeof parsed.kernel_version === "string" ? parsed.kernel_version : null,
+ ),
};
} catch {
- return { toolCount: 0, version: 1 };
+ // A corrupt config carries no readable stamp either: reported outdated, like a pre-stamp one.
+ return { toolCount: 0, version: 1, kernelOutdated: true };
}
}
@@ -197,10 +211,17 @@ export class AgentConfigService {
prompt: typeof schedules.prompt === "string" ? schedules.prompt : DEFAULT_SCHEDULES_PROMPT,
templateHasPlaceholder: hasSchedulesPlaceholder(systemPrompt),
};
+ // Kernel stamp: reported literally (null = predates the mechanism), with the current
+ // generation and the outdated verdict beside it, so the client renders the update hint
+ // without knowing core's KERNEL_VERSION.
+ const kernelVersion = typeof parsed.kernel_version === "string" ? parsed.kernel_version : null;
const config: AgentConfigDto = {
...(typeof parsed.name === "string" ? { name: parsed.name } : {}),
...(typeof parsed.description === "string" ? { description: parsed.description } : {}),
version: agentStateVersion({ version: parsed.version as number | undefined }),
+ kernelVersion,
+ kernelLatest: KERNEL_VERSION,
+ kernelOutdated: isKernelOutdated(kernelVersion),
systemPrompt,
...(typeof parsed.max_turns === "number" ? { maxTurns: parsed.max_turns } : {}),
...(Object.keys(modelDto).length > 0 ? { model: modelDto } : {}),
@@ -254,6 +275,17 @@ export class AgentConfigService {
await resetSystemConfigToDefaults(this.root, projectId, agentId);
}
+ /**
+ * Smart-merges the config up to the current defaults generation (core's applyKernelUpdate):
+ * leaves still carrying a recorded generation's default follow the new defaults, user
+ * customizations are kept and reported; the config is stamped with the new kernel version.
+ * The destructive full-refresh alternative stays resetConfig.
+ */
+ async kernelUpdate(projectId: string, agentId: string): Promise<AgentKernelUpdateResponse> {
+ await this.requireExists(projectId, agentId);
+ return applyKernelUpdate(this.root, projectId, agentId);
+ }
+
private async applyConfigUpdate(
projectId: string,
agentId: string,
diff --git a/packages/server/src/services/agent-service.ts b/packages/server/src/services/agent-service.ts
index 855754bb..0eda5d46 100644
--- a/packages/server/src/services/agent-service.ts
+++ b/packages/server/src/services/agent-service.ts
@@ -42,6 +42,8 @@ export interface AgentListItem {
toolCount: number;
/** Agent State version number (missing field treated as 1). */
version: number;
+ /** Whether the config's kernel stamp is behind the current defaults generation (missing stamp = outdated) — the list card's update hint. */
+ kernelOutdated: boolean;
/** Number of vault keys. */
vaultKeyCount: number;
/** Number of scheduled tasks (count of .toml files under schedule/, including invalid ones). */
@@ -278,6 +280,7 @@ export class AgentService {
updatedAt: createdAt,
toolCount: meta.toolCount,
version: meta.version,
+ kernelOutdated: meta.kernelOutdated,
vaultKeyCount: 0,
scheduleCount: 0,
// Read the real count: coreCreateAgent seeds the default skill set for default_agent.
diff --git a/packages/server/test/agent-kernel-update.test.ts b/packages/server/test/agent-kernel-update.test.ts
new file mode 100644
index 00000000..17f0bce7
--- /dev/null
+++ b/packages/server/test/agent-kernel-update.test.ts
@@ -0,0 +1,130 @@
+/**
+ * POST /api/projects/:projectId/agents/:agentId/config/kernel-update — smart-merges
+ * system_config.yaml up to the current defaults generation: untouched old defaults advance,
+ * customizations are kept and reported, the config is stamped. Also covers the kernel fields
+ * of the config DTO and the agents-list kernelOutdated flag. Same member-level authorization
+ * as /reset; a non-member gets 404 without a write.
+ */
+import fs from "node:fs/promises";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
+import {
+ KERNEL_VERSION,
+ LEGACY_SKILLS_SECTION,
+ LEGACY_VAULT_SECTION,
+ SCHEDULES_PLACEHOLDER,
+ SKILLS_PLACEHOLDER,
+ VAULT_PLACEHOLDER,
+ defaultSystemConfig,
+ systemConfigPath,
+} from "@prismshadow/penguin-core";
+import type {
+ AgentConfigResponse,
+ AgentKernelUpdateResponse,
+ AgentsResponse,
+ ProjectCreateResponse,
+} from "../src/api/types.js";
+import { apiClient, createTestApp, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+describe("POST agent config kernel-update", () => {
+ let t: TestApp;
+ let alice: ReturnType<typeof apiClient>;
+ let projectId: string;
+ const configUrl = () => `/api/projects/${projectId}/agents/default_agent/config`;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ const a = await provisionUser(t.app, "alice");
+ alice = apiClient(t.app, a.cookie);
+ const created = (await (
+ await alice.post("/api/projects", { projectId: "alice-kernel", name: "Kernel project" })
+ ).json()) as ProjectCreateResponse;
+ projectId = created.project.projectId;
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ /**
+ * Rewrites default_agent's config on disk into a pre-toggles-era shape with one user
+ * customization: no kernel stamp, the legacy default template (LEGACY_* sections instead
+ * of the section placeholders, no {{SCHEDULES}}), no vault/skills/schedules sections, and
+ * a customized memory.prompt.
+ */
+ async function agePersistedConfig(): Promise<void> {
+ const configPath = systemConfigPath(t.root, projectId, "default_agent");
+ const config = parseYaml(await fs.readFile(configPath, "utf8")) as Record<string, unknown>;
+ delete config.kernel_version;
+ delete config.vault;
+ delete config.skills;
+ delete config.schedules;
+ config.system_prompt = defaultSystemConfig()
+ .system_prompt.split(VAULT_PLACEHOLDER)
+ .join(LEGACY_VAULT_SECTION)
+ .split(SKILLS_PLACEHOLDER)
+ .join(LEGACY_SKILLS_SECTION)
+ .split(`${SCHEDULES_PLACEHOLDER}\n\n`)
+ .join("");
+ config.memory = { ...(config.memory as object), prompt: "my memory prompt" };
+ await fs.writeFile(configPath, stringifyYaml(config), "utf8");
+ }
+
+ it("reports a fresh agent as stamped and current (config DTO + agents list)", async () => {
+ const got = (await (await alice.get(configUrl())).json()) as AgentConfigResponse;
+ expect(got.config.kernelVersion).toBe(KERNEL_VERSION);
+ expect(got.config.kernelLatest).toBe(KERNEL_VERSION);
+ expect(got.config.kernelOutdated).toBe(false);
+ const list = (await (
+ await alice.get(`/api/projects/${projectId}/agents`)
+ ).json()) as AgentsResponse;
+ expect(list.agents.find((a) => a.agentId === "default_agent")?.kernelOutdated).toBe(false);
+ });
+
+ it("flags a pre-stamp config as outdated, then advances it while keeping the customization", async () => {
+ await agePersistedConfig();
+
+ const before = (await (await alice.get(configUrl())).json()) as AgentConfigResponse;
+ expect(before.config.kernelVersion).toBeNull();
+ expect(before.config.kernelOutdated).toBe(true);
+ const listBefore = (await (
+ await alice.get(`/api/projects/${projectId}/agents`)
+ ).json()) as AgentsResponse;
+ expect(listBefore.agents.find((a) => a.agentId === "default_agent")?.kernelOutdated).toBe(true);
+
+ const res = await alice.post(`${configUrl()}/kernel-update`);
+ expect(res.status).toBe(200);
+ const body = (await res.json()) as AgentKernelUpdateResponse;
+ expect(body.kernelVersion).toBe(KERNEL_VERSION);
+ expect(body.advanced).toContain("system_prompt");
+ expect(body.advanced).toContain("vault.prompt");
+ expect(body.kept).toEqual(["memory.prompt"]);
+
+ // Persisted: the template advanced, the customization survived, the stamp is current.
+ const after = (await (await alice.get(configUrl())).json()) as AgentConfigResponse;
+ expect(after.config.systemPrompt).toBe(defaultSystemConfig().system_prompt);
+ expect(after.config.memory.prompt).toBe("my memory prompt");
+ expect(after.config.kernelVersion).toBe(KERNEL_VERSION);
+ expect(after.config.kernelOutdated).toBe(false);
+ const listAfter = (await (
+ await alice.get(`/api/projects/${projectId}/agents`)
+ ).json()) as AgentsResponse;
+ expect(listAfter.agents.find((a) => a.agentId === "default_agent")?.kernelOutdated).toBe(false);
+ });
+
+ it("404 for a nonexistent agent (no initialization side effect)", async () => {
+ const res = await alice.post(`/api/projects/${projectId}/agents/ghost/config/kernel-update`);
+ expect(res.status).toBe(404);
+ });
+
+ it("404 for a non-member; the config is not modified", async () => {
+ await agePersistedConfig();
+ const before = (await (await alice.get(configUrl())).json()) as AgentConfigResponse;
+ const m = await provisionUser(t.app, "mallory");
+ const mallory = apiClient(t.app, m.cookie);
+ const res = await mallory.post(`${configUrl()}/kernel-update`);
+ expect(res.status).toBe(404);
+ const after = (await (await alice.get(configUrl())).json()) as AgentConfigResponse;
+ expect(after.systemConfigYaml).toBe(before.systemConfigYaml);
+ });
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 965596ef..ff24994b 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -15,6 +15,7 @@ import type {
AgentCreateResponse,
AgentImportRequest,
AgentImportResponse,
+ AgentKernelUpdateResponse,
AgentSchedulesConfigDto,
AgentSkillsConfigDto,
AgentSkillsResponse,
@@ -311,6 +312,13 @@ export const resetAgentConfig = (projectId: string, agentId: string) =>
{ method: "POST" },
);
+/** Smart-merge the config up to the current defaults generation (customizations kept and reported); non-destructive sibling of resetAgentConfig. */
+export const kernelUpdateAgentConfig = (projectId: string, agentId: string) =>
+ apiFetch<AgentKernelUpdateResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/config/kernel-update`,
+ { method: "POST" },
+ );
+
/**
* Optional paging (absent = the legacy full date-grouped response): pages Session groups
* newest-first; a paged response answers with `sessions` (titles + category/workspace),
diff --git a/packages/web/src/features/agents/agent-settings-page.tsx b/packages/web/src/features/agents/agent-settings-page.tsx
index e8be5def..31845c6b 100644
--- a/packages/web/src/features/agents/agent-settings-page.tsx
+++ b/packages/web/src/features/agents/agent-settings-page.tsx
@@ -1,7 +1,8 @@
/**
* Agent settings page: eight tabs —
- * Overview (name/description/State path/active count/State version + snapshot
- * export-import + restore default configuration), Prompt (AGENTS.md and system_prompt editors + placeholder
+ * Overview (name/description/State path/active count/State version + a kernel card grouping
+ * the defaults generation with its update / restore-defaults actions + snapshot
+ * export-import), Prompt (AGENTS.md and system_prompt editors + placeholder
* reference), Memory (memory-tab.tsx), Runtime (max_turns, model.*, compaction.*), Tools (editable built-in
* tools table + the MCP Server form, mcp-servers-section.tsx), Skills (skills-tab.tsx),
* Vault (vault-tab.tsx), Schedule (schedules-tab.tsx).
@@ -15,6 +16,7 @@ import type {
AgentConfigResponse,
AgentConfigUpdateRequest,
AgentCompactionConfigDto,
+ AgentKernelUpdateResponse,
AgentModelConfigDto,
} from "@prismshadow/penguin-server/api";
import type { ToolDefinitionConfig, ToolPermission } from "@prismshadow/penguin-core/interfaces";
@@ -33,8 +35,10 @@ import { OptionMenu, type OptionMenuChoice } from "../../components/ui/option-me
import { Switch } from "../../components/ui/switch";
import { ConfirmModal, useSaveConfirm } from "../../components/ui/confirm-modal";
import { Skeleton } from "../../components/ui/skeleton";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
import { SkillsTab } from "./skills-tab";
import { MemoryTab } from "./memory-tab";
+import { kernelFieldLabel } from "./kernel-labels";
import { VaultTab } from "./vault-tab";
import { SchedulesTab } from "./schedules-tab";
import { McpServersSection } from "./mcp-servers-section";
@@ -173,6 +177,17 @@ export function AgentSettingsPage() {
void reloadAgents();
}, [load, reloadAgents]);
+ /**
+ * Kernel update succeeded: refresh in place (keepStale keeps the Overview mounted so its
+ * kept-fields report stays visible; the other tabs re-seed on their next mount) and reload
+ * the list for its outdated markers. The toast comes from the Overview tab, which holds
+ * the merge report.
+ */
+ const onKernelUpdated = useCallback(() => {
+ load({ keepStale: true });
+ void reloadAgents();
+ }, [load, reloadAgents]);
+
const save = useCallback(
async (update: AgentConfigUpdateRequest) => {
if (!projectId || !agentId) return;
@@ -247,6 +262,7 @@ export function AgentSettingsPage() {
onSave={save}
onImported={onImported}
onConfigReset={onConfigReset}
+ onKernelUpdated={onKernelUpdated}
/>
)}
{tab === "prompt" && <PromptTab data={data} onSave={save} />}
@@ -280,18 +296,23 @@ const TRANSFER_BUTTON_CLASS =
"hover:bg-gray-50 focus-within:ring-2 focus-within:ring-gray-400/30 " +
"dark:border-gray-700 dark:bg-gray-900 dark:text-gray-200 dark:hover:bg-gray-800";
+/** Kernel-outdated hint icon (rotate-cw, 24×24 line path — the skill library's update glyph). */
+const KERNEL_UPDATE_ICON = "M23 4v6h-6M20.49 15a9 9 0 1 1-2.12-9.36L23 10";
+
function OverviewTab({
data,
agentId,
onSave,
onImported,
onConfigReset,
+ onKernelUpdated,
}: {
data: AgentConfigResponse;
agentId: string;
onSave: SaveFn;
onImported: (version: number) => void;
onConfigReset: () => void;
+ onKernelUpdated: () => void;
}) {
const { currentProject } = useProject();
const projectId = currentProject?.projectId ?? null;
@@ -304,6 +325,10 @@ function OverviewTab({
const [conflict, setConflict] = useState<string | null>(null);
const [resetOpen, setResetOpen] = useState(false);
const [resetting, setResetting] = useState(false);
+ const [kernelOpen, setKernelOpen] = useState(false);
+ const [kernelUpdating, setKernelUpdating] = useState(false);
+ /** Last kernel update's merge report (kept fields listed under the section until the next full reload). */
+ const [kernelResult, setKernelResult] = useState<AgentKernelUpdateResponse | null>(null);
const { requestSave, element: saveConfirm } = useSaveConfirm();
const runReset = async () => {
@@ -320,6 +345,22 @@ function OverviewTab({
}
};
+ const runKernelUpdate = async () => {
+ if (!projectId) return;
+ setKernelUpdating(true);
+ try {
+ const res = await api.kernelUpdateAgentConfig(projectId, agentId);
+ setKernelOpen(false);
+ setKernelResult(res);
+ toastSuccess(S.agent.kernelUpdateDone(res.kernelVersion, res.advanced.length));
+ onKernelUpdated();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setKernelUpdating(false);
+ }
+ };
+
const submit = () => {
const config: NonNullable<AgentConfigUpdateRequest["config"]> = {};
if (name.trim() !== (data.config.name ?? "")) config.name = name.trim();
@@ -399,6 +440,66 @@ function OverviewTab({
<p className="mb-1 text-xs font-medium text-gray-500">{S.agent.stateVersion}</p>
<p className="font-mono text-sm">v{data.config.version}</p>
</div>
+ {/* Kernel card (the injection-toggle cards' visual family): the defaults generation the
+ config is based on, with its two maintenance actions grouped beside it — update
+ (smart merge, enabled only when outdated) and restore defaults (destructive, danger
+ tone). Both keep their confirm-first modals below. */}
+ <section className="rounded-lg border border-gray-200 px-4 py-3 dark:border-gray-800">
+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
+ <div className="min-w-0">
+ <p className="text-sm font-medium">{S.agent.kernelTitle}</p>
+ <p className="mt-0.5 flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400">
+ {data.config.kernelOutdated ? (
+ <>
+ <span>
+ {S.agent.kernelVersions(
+ data.config.kernelVersion ?? S.agent.kernelLegacy,
+ data.config.kernelLatest,
+ )}
+ </span>
+ {/* Minimal outdated hint: icon + tooltip only (no textual alarm). */}
+ <span
+ role="img"
+ title={S.agent.kernelOutdatedHint}
+ aria-label={S.agent.kernelOutdatedHint}
+ >
+ <GlyphIcon d={KERNEL_UPDATE_ICON} size={12} />
+ </span>
+ </>
+ ) : (
+ <>
+ <span className="font-mono">{data.config.kernelVersion}</span>
+ <span>· {S.agent.kernelUpToDate}</span>
+ </>
+ )}
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ <Button
+ size="sm"
+ disabled={kernelUpdating || !data.config.kernelOutdated}
+ onClick={() => setKernelOpen(true)}
+ >
+ {S.agent.kernelUpdateAction}
+ </Button>
+ <Button
+ size="sm"
+ variant="danger"
+ disabled={resetting}
+ onClick={() => setResetOpen(true)}
+ >
+ {S.agent.resetConfigAction}
+ </Button>
+ </div>
+ </div>
+ {/* Merge report: which fields the last update kept because customized (lightweight inline note). */}
+ {kernelResult !== null && kernelResult.kept.length > 0 && (
+ <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">
+ {S.agent.kernelUpdateKeptIntro}
+ {kernelResult.kept.map(kernelFieldLabel).join(S.agent.kernelListSeparator)}
+ </p>
+ )}
+ </section>
{/* Snapshot export / import: export is available to any member; import overwrites the entire Agent State, visible only to owners. */}
<div>
@@ -428,15 +529,6 @@ function OverviewTab({
)}
</div>
- {/* Restore default configuration: overwrite system_config.yaml with the current defaults (name/description/version kept) — the config-side analogue of a skill update. */}
- <div>
- <p className="mb-1 text-xs font-medium text-gray-500">{S.agent.resetConfigTitle}</p>
- <p className="mb-2 text-xs text-gray-500 dark:text-gray-400">{S.agent.resetConfigDesc}</p>
- <Button size="sm" disabled={resetting} onClick={() => setResetOpen(true)}>
- {S.agent.resetConfigAction}
- </Button>
- </div>
-
<Button size="sm" variant="primary" onClick={submit}>
{S.common.save}
</Button>
@@ -455,6 +547,23 @@ function OverviewTab({
<p className="text-sm text-gray-600 dark:text-gray-300">{S.agent.importConflictBody}</p>
</ConfirmModal>
+ {/* Kernel update confirmation: lossless by design, but it still rewrites config fields —
+ confirm-first like the sibling reset, with the primary (overwrite) tone rather than
+ the reset's danger tone. */}
+ <ConfirmModal
+ open={kernelOpen}
+ title={S.agent.kernelUpdateTitle}
+ busy={kernelUpdating}
+ tone="primary"
+ onClose={() => setKernelOpen(false)}
+ onConfirm={() => void runKernelUpdate()}
+ confirmLabel={S.agent.kernelUpdateAction}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.agent.kernelUpdateConfirmBody}
+ </p>
+ </ConfirmModal>
+
{/* Reset confirmation: overwriting customizations with the defaults is destructive, so it keeps the danger tone. */}
<ConfirmModal
open={resetOpen}
diff --git a/packages/web/src/features/agents/agents-page.tsx b/packages/web/src/features/agents/agents-page.tsx
index 915a9704..fafffaff 100644
--- a/packages/web/src/features/agents/agents-page.tsx
+++ b/packages/web/src/features/agents/agents-page.tsx
@@ -66,6 +66,8 @@ const CARD_ICONS = {
/** Memory (brain: two hemispheres + inner fold, lucide simplified), opens the settings tab */
memory:
"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18ZM12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18ZM15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",
+ /** Kernel update available (rotate-cw — the skill library's update glyph), deep-links to the settings overview */
+ kernelUpdate: "M23 4v6h-6M20.49 15a9 9 0 1 1-2.12-9.36L23 10",
} as const;
/**
@@ -155,7 +157,7 @@ export function AgentsPage() {
*/
const openSettingsTab = (
agentId: string,
- tab: "tools" | "vault" | "schedules" | "skills" | "memory",
+ tab: "overview" | "tools" | "vault" | "schedules" | "skills" | "memory",
) => {
setCurrentAgentId(agentId);
navigate(`/agents/${agentId}?tab=${tab}`);
@@ -242,6 +244,20 @@ export function AgentsPage() {
{a.agentId}
</span>
<Badge tone="gray">v{a.version}</Badge>
+ {/* Kernel-outdated hint: minimal icon + tooltip (skills-library update
+ convention, no textual/red alarm), deep-linking to the settings
+ overview where the update action lives. */}
+ {a.kernelOutdated && (
+ <button
+ type="button"
+ className="shrink-0 cursor-pointer text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300"
+ title={S.agent.kernelOutdatedHint}
+ aria-label={S.agent.kernelOutdatedHint}
+ onClick={() => openSettingsTab(a.agentId, "overview")}
+ >
+ <GlyphIcon d={CARD_ICONS.kernelUpdate} size={12} />
+ </button>
+ )}
</div>
{/* Description truncated to one line (an empty description still takes up a line, keeping card heights equal) */}
<p className="mt-1.5 min-h-4 truncate text-xs text-gray-500 dark:text-gray-400">
diff --git a/packages/web/src/features/agents/kernel-labels.ts b/packages/web/src/features/agents/kernel-labels.ts
new file mode 100644
index 00000000..af4ec6d0
--- /dev/null
+++ b/packages/web/src/features/agents/kernel-labels.ts
@@ -0,0 +1,18 @@
+/**
+ * Display names for kernel merge leaves (the dotted config paths a kernel update reports in
+ * `advanced` / `kept`): fixed paths map through the dictionary, `tools.builtin.<name>`
+ * renders per tool, and unknown paths (a future default the dictionary does not know yet)
+ * fall back to the raw path — never hidden, never crashing.
+ */
+import { S } from "../../lib/strings";
+
+const TOOL_PATH_PREFIX = "tools.builtin.";
+
+export function kernelFieldLabel(path: string): string {
+ const fixed = S.agent.kernelFields[path];
+ if (fixed !== undefined) return fixed;
+ if (path.startsWith(TOOL_PATH_PREFIX) && path.length > TOOL_PATH_PREFIX.length) {
+ return S.agent.kernelFieldTool(path.slice(TOOL_PATH_PREFIX.length));
+ }
+ return path;
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 5f1c68bd..f3830724 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -406,12 +406,47 @@ export const en: Strings = {
importConflictBody:
"The snapshot's version is not newer than the current one; importing will overwrite the existing Agent State. Continue?",
resetConfigTitle: "Restore default configuration",
- resetConfigDesc:
- "Restores system_config.yaml to the current built-in defaults (same semantics as a skill update): the custom system prompt, tool list, model/compaction settings and MCP servers are overwritten; only name, description and the State version are kept.",
resetConfigAction: "Restore default configuration",
resetConfigConfirmBody:
"This overwrites the agent's existing configuration with the current defaults: the custom system prompt, tool list, model/compaction settings and MCP servers are all replaced, keeping only name and description. Like a skill update this cannot be undone. Continue?",
resetConfigDone: "Configuration restored to the current defaults",
+ kernelTitle: "Kernel",
+ kernelLegacy: "predates kernel versioning",
+ kernelOutdatedHint: "Kernel update available",
+ kernelUpToDate: "Up to date",
+ kernelUpdateTitle: "Update kernel",
+ kernelVersions: (current: string, latest: string): string =>
+ `current ${current} · latest ${latest}`,
+ kernelUpdateAction: "Update kernel",
+ kernelUpdateConfirmBody:
+ "Fields you have not customized will be updated to the current built-in defaults; customized fields stay unchanged and are listed in the result. Name, description, the State version and MCP servers are unaffected. Continue?",
+ kernelUpdateDone: (version: string, advanced: number): string =>
+ advanced > 0
+ ? `Kernel updated to ${version}; ${advanced} field(s) now follow the new defaults`
+ : `Kernel updated to ${version}; every field was already current or kept as customized`,
+ kernelUpdateKeptIntro: "Kept because customized:",
+ kernelListSeparator: ", ",
+ kernelFieldTool: (name: string): string => `tool ${name}`,
+ kernelFields: {
+ system_prompt: "system prompt template",
+ max_turns: "max turns per task",
+ "model.max_tokens": "model max output tokens",
+ "model.thinking_level": "thinking level",
+ "model.timeoutMs": "request timeout",
+ "compaction.max_context_length": "compaction context threshold",
+ "compaction.max_session_turns": "compaction session-turn threshold",
+ "compaction.mode": "compaction mode",
+ "compaction.prompt": "compaction prompt",
+ "memory.enabled": "memory switch",
+ "memory.prompt": "memory prompt",
+ "memory.workspace_prompt": "workspace memory prompt",
+ "vault.enabled": "Vault section switch",
+ "vault.prompt": "Vault prompt",
+ "skills.enabled": "Skills section switch",
+ "skills.prompt": "Skills prompt",
+ "schedules.enabled": "Schedules section switch",
+ "schedules.prompt": "Schedules prompt",
+ } as Record<string, string>,
},
models: {
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 933835d3..50ee9a76 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -374,12 +374,49 @@ export const zh = {
importConflictTitle: "版本冲突",
importConflictBody: "快照包版本不高于当前版本,导入将覆盖现有 Agent State。确认继续?",
resetConfigTitle: "还原为默认配置",
- resetConfigDesc:
- "把 system_config.yaml 还原为当前内置默认值(与 Skill 更新同语义):自定义的系统提示词、工具列表、模型/压缩参数与 MCP Server 将被覆盖,仅保留名称、描述与版本号。",
resetConfigAction: "还原为默认配置",
resetConfigConfirmBody:
"此操作会用当前默认值覆盖该 Agent 的现有配置:自定义系统提示词、工具列表、模型/压缩参数与 MCP Server 全部被替换,仅保留名称与描述。与 Skill 更新一样不可撤销,确认继续?",
resetConfigDone: "配置已还原为当前默认值",
+ /** Kernel card: which defaults generation the config is based on (dates; unrelated to the optimization counter shown as stateVersion), with the update / restore actions. */
+ kernelTitle: "内核",
+ kernelLegacy: "早于内核版本机制",
+ kernelOutdatedHint: "内核有更新",
+ kernelUpToDate: "已是最新",
+ kernelUpdateTitle: "更新内核",
+ kernelVersions: (current: string, latest: string): string => `当前 ${current} · 最新 ${latest}`,
+ kernelUpdateAction: "更新内核",
+ kernelUpdateConfirmBody:
+ "将把未自定义的字段更新为当前内置默认值;自定义过的字段保持不变并在结果中列出。名称、描述、版本号与 MCP Server 不受影响。确认继续?",
+ kernelUpdateDone: (version: string, advanced: number): string =>
+ advanced > 0
+ ? `内核已更新至 ${version},${advanced} 个字段跟进新默认`
+ : `内核已更新至 ${version},字段均已是当前默认或保持自定义`,
+ kernelUpdateKeptIntro: "以下字段因自定义被保留:",
+ kernelListSeparator: "、",
+ /** Display name of a per-tool merge leaf (`tools.builtin.<name>`) in the kept/advanced lists. */
+ kernelFieldTool: (name: string): string => `工具 ${name}`,
+ /** Display names of the fixed kernel merge leaves (dotted config paths); unknown paths fall back to the raw path. */
+ kernelFields: {
+ system_prompt: "系统提示词模板",
+ max_turns: "单任务最大轮数",
+ "model.max_tokens": "模型最大输出 Token",
+ "model.thinking_level": "思考力度",
+ "model.timeoutMs": "请求超时",
+ "compaction.max_context_length": "压缩上下文阈值",
+ "compaction.max_session_turns": "压缩会话轮数阈值",
+ "compaction.mode": "压缩模式",
+ "compaction.prompt": "压缩提示词",
+ "memory.enabled": "记忆开关",
+ "memory.prompt": "记忆提示词",
+ "memory.workspace_prompt": "工作区记忆提示词",
+ "vault.enabled": "Vault 小节开关",
+ "vault.prompt": "Vault 提示词",
+ "skills.enabled": "技能小节开关",
+ "skills.prompt": "技能提示词",
+ "schedules.enabled": "定时任务小节开关",
+ "schedules.prompt": "定时任务提示词",
+ } as Record<string, string>,
},
models: {
diff --git a/packages/web/test/agent-handoff.test.ts b/packages/web/test/agent-handoff.test.ts
index 7d310fe6..d3e441e6 100644
--- a/packages/web/test/agent-handoff.test.ts
+++ b/packages/web/test/agent-handoff.test.ts
@@ -25,6 +25,7 @@ const agent = (agentId: string, name?: string): AgentSummary => ({
sessionActivity: [],
toolCount: 0,
version: 1,
+ kernelOutdated: false,
vaultKeyCount: 0,
scheduleCount: 0,
skillCount: 0,
diff --git a/packages/web/test/kernel-labels.test.ts b/packages/web/test/kernel-labels.test.ts
new file mode 100644
index 00000000..fde6a91f
--- /dev/null
+++ b/packages/web/test/kernel-labels.test.ts
@@ -0,0 +1,40 @@
+/**
+ * kernelFieldLabel unit tests: the kernel merge report's path → display-name mapping — fixed
+ * paths through the dictionary, per-tool paths rendered with the tool name, and unknown
+ * (future) paths falling back to the raw path in both locales.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { kernelFieldLabel } from "../src/features/agents/kernel-labels";
+import { setActiveStrings, zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+
+afterEach(() => setActiveStrings(zh));
+
+describe("kernelFieldLabel", () => {
+ it("maps fixed paths through the active dictionary", () => {
+ expect(kernelFieldLabel("system_prompt")).toBe("系统提示词模板");
+ expect(kernelFieldLabel("memory.prompt")).toBe("记忆提示词");
+ setActiveStrings(en);
+ expect(kernelFieldLabel("system_prompt")).toBe("system prompt template");
+ });
+
+ it("renders per-tool paths with the tool name", () => {
+ expect(kernelFieldLabel("tools.builtin.read_file")).toBe("工具 read_file");
+ setActiveStrings(en);
+ expect(kernelFieldLabel("tools.builtin.my_tool")).toBe("tool my_tool");
+ });
+
+ it("covers every fixed kernel merge leaf in both dictionaries (no raw-path fallbacks for known paths)", () => {
+ // The dictionaries must agree on the covered paths — a path only one locale knows would
+ // render raw in the other.
+ expect(Object.keys(en.agent.kernelFields).sort()).toEqual(
+ Object.keys(zh.agent.kernelFields).sort(),
+ );
+ });
+
+ it("falls back to the raw path for unknown leaves (a future default the dictionary predates)", () => {
+ expect(kernelFieldLabel("future.section.key")).toBe("future.section.key");
+ // The bare prefix with no tool name is not a per-tool path either.
+ expect(kernelFieldLabel("tools.builtin.")).toBe("tools.builtin.");
+ });
+});