Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(ok): add server.* config keys and reload classes (PRD-7810) (#3327)

omar-inkeep85f3a19c825f
diff --git a/.changeset/server-config-keys.md b/.changeset/server-config-keys.md
new file mode 100644
index 000000000..ddd7fd0c8
--- /dev/null
+++ b/.changeset/server-config-keys.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+New `server.*` config section in `.ok/config.yml` — the canonical way to describe how the OpenKnowledge server listens and is reached, ahead of the unified single-server boot. `server.port`, `server.bind` (a list of bind addresses, loopback-only by default), and `server.publicUrl` (the canonical external origin) are committed project settings; `server.openBrowser`, `server.idleShutdown`, and the `server.allowExternal` exposure-consent interlock are per-machine settings in the gitignored `.ok/local/config.yml`, so consent to external exposure never travels via git, clone, or share. `openBrowser` and `idleShutdown` default from the bind: a loopback-only server opens the UI and idles out after 30 minutes, while an exposed or containerized server is headless and stays up — there is deliberately no `server.mode` key.
+
+The existing `remote.url` and `remote.port` keys are superseded: each is still read while its successor (`server.publicUrl` / `server.port`) is absent, so existing configs keep working unchanged. The `server.host` removed-key message now points at `server.bind`. Every config field also now declares whether it applies live or at the next server start, and this is documented in each field's description.
diff --git a/packages/cli/src/commands/config.test.ts b/packages/cli/src/commands/config.test.ts
index e72f52844..bf9772916 100644
--- a/packages/cli/src/commands/config.test.ts
+++ b/packages/cli/src/commands/config.test.ts
@@ -1,7 +1,7 @@
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { REMOVED_KEYS } from '@inkeep/open-knowledge-core';
+import { ConfigSchema, getLeafFieldMeta, REMOVED_KEYS } from '@inkeep/open-knowledge-core';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { CONFIG_FILENAME, OK_DIR } from '../constants.ts';
import {
@@ -338,11 +338,13 @@ describe('runMigrate', () => {
expect(stdout.some((m) => m.includes('removed') && m.includes('sync'))).toBe(true);
});
- test('removes server.port and persistence.* leaf fields (project)', async () => {
+ test('removes persistence.* leaf fields while preserving the live server.port key (project)', async () => {
const wsPath = projectConfigPath(project.cwd);
- // `content.dir` is the surviving unrelated field; server.port +
- // persistence.* are silent-drop leaves. (server.host / openOnAgentEdit are
- // now removed keys themselves, so they can't serve as preserved siblings.)
+ // `content.dir` is the surviving unrelated field; persistence.* are the
+ // silent-drop leaves. `server.port` is present precisely to prove migrate
+ // does NOT touch it — it returned as a live schema key, so a codemod that
+ // stripped it would destroy config on the exact command every removed-key
+ // redirect tells the user to run.
const original = `content:\n dir: docs\nserver:\n port: 3000\npersistence:\n debounceMs: 5000\n maxDebounceMs: 10000\n`;
writeConfigYaml(wsPath, original);
const outcome = await runMigrate({
@@ -353,14 +355,15 @@ describe('runMigrate', () => {
});
expect(outcome.ok).toBe(true);
const migrated = readFileSync(wsPath, 'utf-8');
- expect(migrated).not.toContain('port:');
expect(migrated).not.toContain('debounceMs');
expect(migrated).not.toContain('maxDebounceMs');
+ // The live server.port key survives untouched.
+ expect(migrated).toContain('port: 3000');
// Unrelated field preserved.
expect(migrated).toContain('dir: docs');
const wsOutcome = outcome.outcomes.find((o) => o.scope === 'project');
expect(wsOutcome?.removed.sort()).toEqual(
- ['persistence.debounceMs', 'persistence.maxDebounceMs', 'server.port'].sort(),
+ ['persistence.debounceMs', 'persistence.maxDebounceMs'].sort(),
);
});
@@ -740,22 +743,35 @@ describe('configCommand migrate --scope', () => {
describe('DROPPED_FIELD_PATHS', () => {
test('is the silent-drop set followed by every removed-key registry path', () => {
- // Silently-dropped sections (no removed-key error) come first.
- expect(DROPPED_FIELD_PATHS.slice(0, 4)).toEqual([
+ // Silently-dropped sections (no removed-key error) come first. `server.port`
+ // was here until it returned as a live schema key (see the disjointness
+ // guard below).
+ expect(DROPPED_FIELD_PATHS.slice(0, 3)).toEqual([
['sync'],
['persistence', 'debounceMs'],
['persistence', 'maxDebounceMs'],
- ['server', 'port'],
]);
// ...then the shared registry, so the "run `ok config migrate`" hint in
// every removed-key redirect is truthful.
- expect(DROPPED_FIELD_PATHS.slice(4)).toEqual(REMOVED_KEYS.map((k) => k.path));
+ expect(DROPPED_FIELD_PATHS.slice(3)).toEqual(REMOVED_KEYS.map((k) => k.path));
// Headline keys that used to be silent are now strippable.
const dotted = DROPPED_FIELD_PATHS.map((p) => p.join('.'));
expect(dotted).toContain('folders');
expect(dotted).toContain('appearance.editorModeDefault');
expect(dotted).toContain('content.include');
});
+
+ test('no dropped path is a live ConfigSchema leaf (codemod never deletes a key the engine reads)', () => {
+ // The failure this guards against: a key resurrected into ConfigSchema
+ // while still listed here, so `ok config migrate` silently deletes live
+ // user config. `server.port` was exactly that. A dropped path must resolve
+ // to NO field metadata — it is either a whole removed section or a leaf the
+ // schema no longer declares.
+ const live = DROPPED_FIELD_PATHS.filter(
+ (path) => getLeafFieldMeta(ConfigSchema, path) !== undefined,
+ ).map((path) => path.join('.'));
+ expect(live).toEqual([]);
+ });
});
describe('buildClearPatchForTest (internal)', () => {
diff --git a/packages/cli/src/commands/config.ts b/packages/cli/src/commands/config.ts
index bbd7f2536..70f67d76c 100644
--- a/packages/cli/src/commands/config.ts
+++ b/packages/cli/src/commands/config.ts
@@ -8,10 +8,9 @@
* source-located errors on failure. Success message goes to stderr (stdout
* is reserved for structured CI output, of which we emit none).
* - `migrate` — codemod removing deprecated fields (`sync.*`,
- * `persistence.{debounceMs,maxDebounceMs}`, `server.port`, plus every
- * entry in the shared removed-key registry) idempotently. Funnels through
- * `writeConfigPatch` so atomic-write + Zod safeParse invariants apply
- * automatically.
+ * `persistence.{debounceMs,maxDebounceMs}`, plus every entry in the shared
+ * removed-key registry) idempotently. Funnels through `writeConfigPatch`
+ * so atomic-write + Zod safeParse invariants apply automatically.
*/
import { existsSync, readFileSync } from 'node:fs';
@@ -37,19 +36,25 @@ import { loadConfig } from '../config/loader.ts';
*
* 1. Silently-dropped sections that never carried a user contract — `sync`
* collapses to a single key delete (all 7 subfields with it);
- * `persistence.{debounceMs, maxDebounceMs}` and `server.port` are
- * field-level deletes leaving their parent sections intact. These produce
- * no `REMOVED_KEY` error; the codemod only tidies them away.
+ * `persistence.{debounceMs, maxDebounceMs}` are field-level deletes leaving
+ * their parent sections intact. These produce no `REMOVED_KEY` error; the
+ * codemod only tidies them away.
* 2. Every entry in the shared removed-key registry — these DO hard-error on
* load, so sourcing them here keeps the "run `ok config migrate`" hint in
* each redirect truthful. `content.{include, exclude}` patterns must be
* recreated in `.okignore` manually; the codemod only removes the keys.
+ *
+ * `server.port` is deliberately NOT here: it was a silently-dropped field
+ * until it returned as a live `ConfigSchema` leaf (project scope, boot
+ * reload). Listing it would make `ok config migrate` delete a key the engine
+ * now reads — data loss on the exact command every removed-key redirect tells
+ * users to run. The disjointness of this list and the live schema is pinned by
+ * a guard test.
*/
export const DROPPED_FIELD_PATHS: ReadonlyArray<readonly string[]> = [
['sync'],
['persistence', 'debounceMs'],
['persistence', 'maxDebounceMs'],
- ['server', 'port'],
...REMOVED_KEYS.map((k) => k.path),
];
@@ -396,7 +401,7 @@ export function configCommand(): Command {
cmd
.command('migrate')
.description(
- 'Remove deprecated config fields from config.yml idempotently (every removed key in the registry — content.*, folders, appearance.editorModeDefault, server.host, etc. — plus the silently-dropped sync.*, persistence.*, server.port)',
+ 'Remove deprecated config fields from config.yml idempotently (every removed key in the registry — content.*, folders, appearance.editorModeDefault, server.host, etc. — plus the silently-dropped sync.*, persistence.*)',
)
// Defaults to `all` so the bare `ok config migrate` that every removed-key
// redirect tells the user to run actually reaches the layer their dead key
diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.ts
index 14802834e..48dd1f03e 100644
--- a/packages/cli/src/commands/start.ts
+++ b/packages/cli/src/commands/start.ts
@@ -26,6 +26,7 @@ import type { Server as HttpServer } from 'node:http';
import { basename, join, resolve as pathResolve } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import {
+ DEFAULT_REMOTE_PORT,
DEFAULT_SERVER_HOST,
DEFAULT_SIGTERM_GRACE_MS as SHARED_DEFAULT_SIGTERM_GRACE_MS,
DEFAULT_SIGTERM_POLL_MS as SHARED_DEFAULT_SIGTERM_POLL_MS,
@@ -658,10 +659,12 @@ interface BootStartServerOptions {
*/
host: string;
/**
- * Server bind port. `server.port` is not a schema field — source ordering
- * at the call site is `--port` flag → `PORT` env → `0` (kernel-allocated).
- * `0` or `undefined` triggers kernel allocation; `bootServer` writes the
- * resolved port into `server.lock` for MCP clients to discover.
+ * Server bind port. `server.port` is a schema key but this boot path does
+ * NOT read it yet — that wiring lands with the unified server boot. Source
+ * ordering at the call site is `--port` flag → `PORT` env → `0`
+ * (kernel-allocated). `0` or `undefined` triggers kernel allocation;
+ * `bootServer` writes the resolved port into `server.lock` for MCP clients
+ * to discover.
*/
port?: number;
/**
@@ -1391,12 +1394,12 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)
// break the tunnel on every restart.
if (remoteEnabled && portFromCli === undefined && portFromEnv !== undefined) {
console.warn(
- `remote access is enabled — ignoring env PORT=${process.env.PORT}; the tunnel's port mapping targets the stable remote port (${activeConfig.remote?.port}). Pass --port to override deliberately.`,
+ `remote access is enabled — ignoring env PORT=${process.env.PORT}; the tunnel's port mapping targets the stable remote port (${activeConfig.remote?.port ?? DEFAULT_REMOTE_PORT}). Pass --port to override deliberately.`,
);
}
const port =
resolveCollabPort(portFromCli, portFromEnv, requestedUiPort, remoteEnabled) ??
- (remoteEnabled ? activeConfig.remote?.port : undefined);
+ (remoteEnabled ? (activeConfig.remote?.port ?? DEFAULT_REMOTE_PORT) : undefined);
// Fast path: when `--ui-port` is set (the worktree-preview recipe), a
// live collab server already in this folder means we must NOT boot a second
diff --git a/packages/core/src/config/field-registry.test.ts b/packages/core/src/config/field-registry.test.ts
index ab18b8760..24c021e4d 100644
--- a/packages/core/src/config/field-registry.test.ts
+++ b/packages/core/src/config/field-registry.test.ts
@@ -29,32 +29,46 @@ describe('getFieldMeta walker (descends innerType)', () => {
test('descends through .default()', () => {
const inner = z.string();
- fieldRegistry.add(inner, { scope: 'user', agentSettable: false });
+ fieldRegistry.add(inner, { scope: 'user', agentSettable: false, reload: 'live' });
const wrapped = inner.default('localhost');
- expect(getFieldMeta(wrapped)).toEqual({ scope: 'user', agentSettable: false });
+ expect(getFieldMeta(wrapped)).toEqual({ scope: 'user', agentSettable: false, reload: 'live' });
});
test('descends through .refine()', () => {
const inner = z.string();
- fieldRegistry.add(inner, { scope: 'project', agentSettable: false });
+ fieldRegistry.add(inner, { scope: 'project', agentSettable: false, reload: 'live' });
const wrapped = inner.refine(() => true).default('x');
- expect(getFieldMeta(wrapped)).toEqual({ scope: 'project', agentSettable: false });
+ expect(getFieldMeta(wrapped)).toEqual({
+ scope: 'project',
+ agentSettable: false,
+ reload: 'live',
+ });
});
test('descends through chained .optional().nullable().default()', () => {
const inner = z.number();
- fieldRegistry.add(inner, { scope: 'project', agentSettable: true });
+ fieldRegistry.add(inner, { scope: 'project', agentSettable: true, reload: 'live' });
const wrapped = inner.optional().nullable().default(42);
- expect(getFieldMeta(wrapped)).toEqual({ scope: 'project', agentSettable: true });
+ expect(getFieldMeta(wrapped)).toEqual({
+ scope: 'project',
+ agentSettable: true,
+ reload: 'live',
+ });
});
test('descends through z.array(...).min(...).default(...)', () => {
const arr = z.array(z.string()).min(1);
- fieldRegistry.add(arr, { scope: 'either', agentSettable: true, defaultScope: 'project' });
+ fieldRegistry.add(arr, {
+ scope: 'either',
+ agentSettable: true,
+ reload: 'live',
+ defaultScope: 'project',
+ });
const wrapped = arr.default(['a']);
expect(getFieldMeta(wrapped)).toEqual({
scope: 'either',
agentSettable: true,
+ reload: 'live',
defaultScope: 'project',
});
});
@@ -253,6 +267,13 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'
'lossCapture.maxBytes',
'remote.port',
'remote.url',
+ // `server.{port,bind,publicUrl}` are the committed, reviewed shape of
+ // this knowledge base's server — project scope, like the `remote.*`
+ // keys they supersede. Their consent/workflow siblings are
+ // project-local (below).
+ 'server.bind',
+ 'server.port',
+ 'server.publicUrl',
'telemetry.localSink.attributeDenylist',
'telemetry.localSink.enabled',
'telemetry.localSink.logs.maxBytes',
@@ -300,6 +321,14 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'
'search.semantic.enabled',
'search.semantic.model',
'search.semantic.similarityFloor',
+ // `server.allowExternal` is exposure CONSENT — the `terminal.enabled`
+ // posture: never inherited via clone, sync, or share, so a committed
+ // `allowExternal: true` can never expose a future cloner's machine.
+ // `server.{openBrowser,idleShutdown}` are personal workflow, like the
+ // sidebar toggles.
+ 'server.allowExternal',
+ 'server.idleShutdown',
+ 'server.openBrowser',
'terminal.enabled',
]);
});
@@ -318,4 +347,42 @@ describe('ConfigSchema coverage (NR3 — every leaf has fieldRegistry metadata)'
expect(description).toContain('.md');
expect(description).toContain('.mdx');
});
+
+ test('every leaf declares a reload class', () => {
+ const leaves: { path: string[]; schema: unknown }[] = [];
+ walkLeaves(ConfigSchema, [], leaves);
+ const missing = leaves
+ .filter((l) => {
+ const reload = getFieldMeta(l.schema)?.reload;
+ return reload !== 'boot' && reload !== 'live';
+ })
+ .map((l) => l.path.join('.'));
+ expect(missing).toEqual([]);
+ });
+
+ test("boot-only leaves are exactly content.dir + the listener/exposure keys — everything else is 'live'", () => {
+ // `content.dir` re-roots the whole index (watcher, Y.Doc registry, link
+ // graph); the `server.*` keys and the superseded `remote.*` aliases shape
+ // the listener and its exposure — none can change under a running server.
+ // `remote.*` are consumed at start via the alias-read in
+ // `resolveServerRuntimeConfig`, so they carry the same 'boot' class as the
+ // `server.*` successors they map onto. `server.idleShutdown` is the one
+ // listener leaf that CAN re-arm live.
+ const leaves: { path: string[]; schema: unknown }[] = [];
+ walkLeaves(ConfigSchema, [], leaves);
+ const bootOnly = leaves
+ .filter((l) => getFieldMeta(l.schema)?.reload === 'boot')
+ .map((l) => l.path.join('.'))
+ .sort();
+ expect(bootOnly).toEqual([
+ 'content.dir',
+ 'remote.port',
+ 'remote.url',
+ 'server.allowExternal',
+ 'server.bind',
+ 'server.openBrowser',
+ 'server.port',
+ 'server.publicUrl',
+ ]);
+ });
});
diff --git a/packages/core/src/config/field-registry.ts b/packages/core/src/config/field-registry.ts
index f9ebd5446..07d414027 100644
--- a/packages/core/src/config/field-registry.ts
+++ b/packages/core/src/config/field-registry.ts
@@ -1,9 +1,21 @@
import { z } from 'zod';
import type { FieldScope, WriteScope } from './errors.ts';
+/**
+ * When a change to the field takes effect on a running server:
+ * - `'boot'` — read once at process start; changing it requires a restart.
+ * Reload attempts must not re-read it (a half-applied bind or content root
+ * is worse than a stale one).
+ * - `'live'` — read through the live layered config; a valid on-disk change
+ * applies without a restart.
+ */
+export type ReloadClass = 'boot' | 'live';
+
export interface FieldMeta {
scope: FieldScope;
agentSettable: boolean;
+ /** Reload class — see {@link ReloadClass}. Every leaf declares one. */
+ reload: ReloadClass;
defaultScope?: WriteScope;
/**
* Human-readable, English description of the field. Single source of field
diff --git a/packages/core/src/config/merge-layered.test.ts b/packages/core/src/config/merge-layered.test.ts
index 2522e25b7..e2f8e29bb 100644
--- a/packages/core/src/config/merge-layered.test.ts
+++ b/packages/core/src/config/merge-layered.test.ts
@@ -224,6 +224,30 @@ describe('mergeLayered — scope-aware leaf short-circuits', () => {
const merged = mergeLayered(user, project);
expect(merged.terminal?.enabled).toBeNull();
});
+
+ test("scope: 'project' (server.bind) returns project, ignoring a project-local override attempt", () => {
+ const user = makeConfig({});
+ const project = makeConfig({ server: { bind: ['127.0.0.1'] } });
+ const projectLocal = makeConfig({ server: { bind: ['0.0.0.0'] } });
+
+ const merged = mergeLayered(user, project, projectLocal);
+ expect(merged.server?.bind).toEqual(['127.0.0.1']);
+ });
+
+ test("scope: 'project-local' (server.allowExternal) ignores a committed project value", () => {
+ // Exposure consent has the terminal.enabled posture: a committed
+ // `allowExternal: true` must never grant consent on a cloner's machine —
+ // only this machine's gitignored project-local layer can. A fresh clone's
+ // project-local layer parses to schema defaults, so `allowExternal` is a
+ // DEFINED false there and the project-local short-circuit never falls
+ // through to the committed value.
+ const user = makeConfig({});
+ const project = makeConfig({ server: { allowExternal: true } });
+ const projectLocal = makeConfig({});
+
+ const merged = mergeLayered(user, project, projectLocal);
+ expect(merged.server?.allowExternal).toBe(false);
+ });
});
describe('mergeLayered — backward compat for two-layer call sites', () => {
@@ -254,6 +278,24 @@ describe('mergeLayered — backward compat for two-layer call sites', () => {
const merged = mergeLayered(user, project);
expect(merged.autoSync?.enabled).toBe(true);
});
+
+ test('two-layer merge passes a committed allowExternal:true through — Wave 4 enforcement MUST use the three-layer merge', () => {
+ // Tripwire, not endorsement. With no project-local layer, layers[2] is
+ // undefined, so the project-local short-circuit falls through to the
+ // committed project value — the UNSAFE result for exposure consent (a
+ // committed `true` would arm a cloner's machine). The three-layer path is
+ // safe because a parsed project-local layer supplies a DEFINED `false`
+ // default that wins (see the project-local scope test above). The Wave 4
+ // boot interlock must therefore resolve `allowExternal` over all three
+ // layers, per the requiresExternalConsent doc comment — this test exists so
+ // that requirement surfaces mechanically if someone reaches for the
+ // two-layer path.
+ const user = makeConfig({});
+ const project = makeConfig({ server: { allowExternal: true } });
+
+ const merged = mergeLayered(user, project);
+ expect(merged.server?.allowExternal).toBe(true);
+ });
});
describe('mergeLayered — structural edges', () => {
diff --git a/packages/core/src/config/removed-keys.test.ts b/packages/core/src/config/removed-keys.test.ts
index 4aea45059..88ed4911f 100644
--- a/packages/core/src/config/removed-keys.test.ts
+++ b/packages/core/src/config/removed-keys.test.ts
@@ -76,6 +76,23 @@ describe('detectRemovedKeys', () => {
expect(paths).toContain('appearance.editorModeDefault');
});
+ test('server.host redirect names the server.bind file key, not just the flag/env escape hatches', () => {
+ // The tombstone predates server.bind; while no file key existed the
+ // redirect pointed at --host / HOST. Now that server.bind is a live leaf,
+ // the redirect must lead with it — pointing users away from the file at
+ // the exact moment a file key exists would be actively misleading.
+ const errors = detectRemovedKeys({ value: { server: { host: '0.0.0.0' } } });
+ const entry = errors.find(
+ (e) =>
+ isKnownConfigError(e) && e.code === 'REMOVED_KEY' && e.path.join('.') === 'server.host',
+ );
+ expect(entry).toBeDefined();
+ if (entry !== undefined && isKnownConfigError(entry) && entry.code === 'REMOVED_KEY') {
+ expect(entry.redirect).toContain('server.bind');
+ expect(entry.redirect).toContain('server.allowExternal');
+ }
+ });
+
test('clean config yields no errors', () => {
expect(detectRemovedKeys({ value: { content: { dir: 'docs' } } })).toEqual([]);
});
diff --git a/packages/core/src/config/removed-keys.ts b/packages/core/src/config/removed-keys.ts
index 0b53acc8a..f9fc2509a 100644
--- a/packages/core/src/config/removed-keys.ts
+++ b/packages/core/src/config/removed-keys.ts
@@ -102,8 +102,12 @@ export const REMOVED_KEYS: readonly RemovedKey[] = [
},
{
path: ['server', 'host'],
+ // Rewritten when `server.bind` returned as a live config key — the old
+ // "use --host / HOST" text pointed away from the file at the exact moment
+ // a file key existed again.
redirect: [
- 'Use the --host CLI flag or the HOST environment variable instead.',
+ 'Use server.bind in .ok/config.yml instead — a list of bind addresses, e.g. [127.0.0.1]; a non-loopback bind additionally requires server.allowExternal.',
+ 'The --host CLI flag and HOST environment variable also remain available.',
MIGRATE_HINT,
].join(' '),
},
diff --git a/packages/core/src/config/resolve-server-config.test.ts b/packages/core/src/config/resolve-server-config.test.ts
new file mode 100644
index 000000000..ec33d8ce2
--- /dev/null
+++ b/packages/core/src/config/resolve-server-config.test.ts
@@ -0,0 +1,176 @@
+import { describe, expect, test } from 'vitest';
+import {
+ DEFAULT_LOOPBACK_IDLE_SHUTDOWN,
+ idleShutdownToMs,
+ isLoopbackBindAddress,
+ isLoopbackOnlyBind,
+ requiresExternalConsent,
+ resolveServerRuntimeConfig,
+} from './resolve-server-config.ts';
+import { ConfigSchema } from './schema.ts';
+
+function parse(partial: Record<string, unknown>) {
+ return ConfigSchema.parse(partial);
+}
+
+describe('isLoopbackBindAddress', () => {
+ test('accepts localhost, 127.0.0.0/8, and IPv6 ::1 (bare or bracketed)', () => {
+ expect(isLoopbackBindAddress('localhost')).toBe(true);
+ expect(isLoopbackBindAddress('LOCALHOST')).toBe(true);
+ expect(isLoopbackBindAddress('127.0.0.1')).toBe(true);
+ expect(isLoopbackBindAddress('127.1.2.3')).toBe(true);
+ expect(isLoopbackBindAddress('::1')).toBe(true);
+ expect(isLoopbackBindAddress('[::1]')).toBe(true);
+ });
+
+ test('rejects all-interfaces and external addresses', () => {
+ expect(isLoopbackBindAddress('0.0.0.0')).toBe(false);
+ expect(isLoopbackBindAddress('::')).toBe(false);
+ expect(isLoopbackBindAddress('192.168.1.10')).toBe(false);
+ expect(isLoopbackBindAddress('10.0.0.1')).toBe(false);
+ expect(isLoopbackBindAddress('example.com')).toBe(false);
+ });
+
+ test('rejects foreign hostnames that merely contain a loopback name', () => {
+ expect(isLoopbackBindAddress('localhost.evil.com')).toBe(false);
+ expect(isLoopbackBindAddress('127.0.0.1.evil.com')).toBe(false);
+ });
+
+ test('rejects 127.x addresses with out-of-range octets (fail-closed toward requiring consent)', () => {
+ expect(isLoopbackBindAddress('127.999.0.1')).toBe(false);
+ expect(isLoopbackBindAddress('127.0.0.256')).toBe(false);
+ // Boundary: 255 is valid, 256 is not.
+ expect(isLoopbackBindAddress('127.255.255.255')).toBe(true);
+ });
+});
+
+describe('isLoopbackOnlyBind', () => {
+ test('true only when every address is loopback', () => {
+ expect(isLoopbackOnlyBind(['127.0.0.1'])).toBe(true);
+ expect(isLoopbackOnlyBind(['127.0.0.1', '::1'])).toBe(true);
+ expect(isLoopbackOnlyBind(['127.0.0.1', '0.0.0.0'])).toBe(false);
+ });
+});
+
+describe('resolveServerRuntimeConfig — defaults', () => {
+ test('empty config resolves to loopback-only with derived local defaults', () => {
+ const resolved = resolveServerRuntimeConfig(parse({}));
+ expect(resolved.bind).toEqual(['127.0.0.1']);
+ expect(resolved.loopbackOnly).toBe(true);
+ expect(resolved.port).toBeUndefined();
+ expect(resolved.publicUrl).toBeUndefined();
+ expect(resolved.allowExternal).toBe(false);
+ // Loopback-only derivations: a laptop start pops the UI and idles out.
+ expect(resolved.openBrowser).toBe(true);
+ expect(resolved.idleShutdown).toBe(DEFAULT_LOOPBACK_IDLE_SHUTDOWN);
+ });
+
+ test('undefined config resolves like an empty one', () => {
+ const resolved = resolveServerRuntimeConfig(undefined);
+ expect(resolved.bind).toEqual(['127.0.0.1']);
+ expect(resolved.openBrowser).toBe(true);
+ expect(resolved.idleShutdown).toBe(DEFAULT_LOOPBACK_IDLE_SHUTDOWN);
+ });
+
+ test('a non-loopback bind derives headless defaults (no browser, no idle shutdown)', () => {
+ const resolved = resolveServerRuntimeConfig(parse({ server: { bind: ['0.0.0.0'] } }));
+ expect(resolved.loopbackOnly).toBe(false);
+ expect(resolved.openBrowser).toBe(false);
+ expect(resolved.idleShutdown).toBe('off');
+ });
+
+ test('explicit openBrowser / idleShutdown win over the derivation in both directions', () => {
+ const headlessLaptop = resolveServerRuntimeConfig(
+ parse({ server: { openBrowser: false, idleShutdown: 'off' } }),
+ );
+ expect(headlessLaptop.openBrowser).toBe(false);
+ expect(headlessLaptop.idleShutdown).toBe('off');
+
+ const eagerContainer = resolveServerRuntimeConfig(
+ parse({ server: { bind: ['0.0.0.0'], openBrowser: true, idleShutdown: '2h' } }),
+ );
+ expect(eagerContainer.openBrowser).toBe(true);
+ expect(eagerContainer.idleShutdown).toBe('2h');
+ });
+});
+
+describe('resolveServerRuntimeConfig — remote.* alias-reads', () => {
+ test('remote.port fills server.port only while it is absent', () => {
+ expect(resolveServerRuntimeConfig(parse({ remote: { port: 24550 } })).port).toBe(24550);
+ expect(
+ resolveServerRuntimeConfig(parse({ server: { port: 8080 }, remote: { port: 24550 } })).port,
+ ).toBe(8080);
+ });
+
+ test('remote.url fills server.publicUrl only while it is absent', () => {
+ const legacyOnly = resolveServerRuntimeConfig(
+ parse({ remote: { url: 'https://kb.example.com' } }),
+ );
+ expect(legacyOnly.publicUrl).toBe('https://kb.example.com');
+
+ const both = resolveServerRuntimeConfig(
+ parse({
+ server: { publicUrl: 'https://new.example.com' },
+ remote: { url: 'https://old.example.com' },
+ }),
+ );
+ expect(both.publicUrl).toBe('https://new.example.com');
+ });
+
+ test('an empty-string remote.url reads as unset', () => {
+ const resolved = resolveServerRuntimeConfig(parse({ remote: { url: '' } }));
+ expect(resolved.publicUrl).toBeUndefined();
+ expect(requiresExternalConsent(resolved)).toBe(false);
+ });
+});
+
+describe('requiresExternalConsent', () => {
+ test('false for the loopback-only default', () => {
+ expect(requiresExternalConsent(resolveServerRuntimeConfig(parse({})))).toBe(false);
+ });
+
+ test('true for a non-loopback bind', () => {
+ const resolved = resolveServerRuntimeConfig(parse({ server: { bind: ['0.0.0.0'] } }));
+ expect(requiresExternalConsent(resolved)).toBe(true);
+ });
+
+ test('true for a declared public URL, including one alias-read from remote.url', () => {
+ expect(
+ requiresExternalConsent(
+ resolveServerRuntimeConfig(parse({ server: { publicUrl: 'https://kb.example.com' } })),
+ ),
+ ).toBe(true);
+ expect(
+ requiresExternalConsent(
+ resolveServerRuntimeConfig(parse({ remote: { url: 'https://kb.example.com' } })),
+ ),
+ ).toBe(true);
+ });
+
+ test('consent state itself does not change whether consent is required', () => {
+ const resolved = resolveServerRuntimeConfig(
+ parse({ server: { bind: ['0.0.0.0'], allowExternal: true } }),
+ );
+ expect(requiresExternalConsent(resolved)).toBe(true);
+ expect(resolved.allowExternal).toBe(true);
+ });
+});
+
+describe('idleShutdownToMs', () => {
+ test("'off' is null (never shut down)", () => {
+ expect(idleShutdownToMs('off')).toBeNull();
+ });
+
+ test('converts s / m / h durations', () => {
+ expect(idleShutdownToMs('90s')).toBe(90_000);
+ expect(idleShutdownToMs('30m')).toBe(1_800_000);
+ expect(idleShutdownToMs('2h')).toBe(7_200_000);
+ });
+
+ test('throws on strings the schema would have rejected', () => {
+ expect(() => idleShutdownToMs('30')).toThrow();
+ expect(() => idleShutdownToMs('0m')).toThrow();
+ expect(() => idleShutdownToMs('1d')).toThrow();
+ expect(() => idleShutdownToMs('')).toThrow();
+ });
+});
diff --git a/packages/core/src/config/resolve-server-config.ts b/packages/core/src/config/resolve-server-config.ts
new file mode 100644
index 000000000..965f65fd6
--- /dev/null
+++ b/packages/core/src/config/resolve-server-config.ts
@@ -0,0 +1,145 @@
+/**
+ * Resolve the effective `server.*` runtime settings from a merged `Config`.
+ *
+ * Two jobs no zod `.default()` can do:
+ *
+ * 1. **Alias-read of the superseded `remote.*` keys.** `remote.url` is read
+ * only while `server.publicUrl` is absent; `remote.port` only while
+ * `server.port` is absent — the same shape as the `autoSync.enabled` →
+ * `autoSync.mode` alias. This resolver is the single alias-read point;
+ * no other reader should consult `remote.*` for these values.
+ *
+ * 2. **Derived defaults.** `openBrowser` and `idleShutdown` default off the
+ * resolved bind: a loopback-only server pops the UI and idles out after
+ * {@link DEFAULT_LOOPBACK_IDLE_SHUTDOWN}; an exposed or containerized
+ * server is headless and stays up. The local/hosted split is emergent
+ * from these values — there is deliberately no mode key to branch on.
+ *
+ * Enforcing the exposure interlock (refusing to boot when
+ * {@link requiresExternalConsent} is true and `allowExternal` is not) is the
+ * boot pipeline's job, not this resolver's — this module only computes the
+ * predicate.
+ */
+
+import type { Config } from './schema.ts';
+import { DEFAULT_SERVER_BIND, IDLE_SHUTDOWN_DURATION_RE } from './schema.ts';
+
+/** Derived `idleShutdown` for a loopback-only server; exposed binds derive `'off'`. */
+export const DEFAULT_LOOPBACK_IDLE_SHUTDOWN = '30m';
+
+export interface ServerRuntimeConfig {
+ /**
+ * Explicit listener port; `undefined` means dynamic (the caller picks a
+ * free port, or the platform's PORT environment decides).
+ */
+ port: number | undefined;
+ /** Bind addresses; defaults to loopback-only (`DEFAULT_SERVER_BIND`). */
+ bind: readonly string[];
+ /**
+ * Canonical external origin; `undefined` means derive
+ * `http://localhost:<port>` for a loopback server.
+ */
+ publicUrl: string | undefined;
+ /** Exposure consent interlock (see `requiresExternalConsent`). */
+ allowExternal: boolean;
+ /** Open the UI in a browser at start. Derived when not set explicitly. */
+ openBrowser: boolean;
+ /** `'off'`, or a duration like `'30m'`. Derived when not set explicitly. */
+ idleShutdown: string;
+ /** True when every bind address is loopback — the derivation input. */
+ loopbackOnly: boolean;
+}
+
+/** A valid 0–255 IPv4 octet, so `127.999.0.1` doesn't read as loopback. */
+const IPV4_OCTET = '(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)';
+const LOOPBACK_V4_RE = new RegExp(`^127\\.${IPV4_OCTET}\\.${IPV4_OCTET}\\.${IPV4_OCTET}$`);
+
+/**
+ * True for addresses that stay on this machine: `localhost`, the whole
+ * 127.0.0.0/8 IPv4 block (octet-validated), and IPv6 `::1` (bracketed or
+ * bare). `0.0.0.0` and `::` are NOT loopback — they are the classic
+ * all-interfaces exposure. Anything malformed (`127.999.0.1`) is treated as
+ * non-loopback, the fail-closed direction for the consent interlock: it errs
+ * toward requiring consent, and an unbindable address fails at bind() anyway.
+ */
+export function isLoopbackBindAddress(address: string): boolean {
+ const normalized = address.trim().toLowerCase();
+ if (normalized === 'localhost' || normalized === '::1' || normalized === '[::1]') return true;
+ return LOOPBACK_V4_RE.test(normalized);
+}
+
+/** True when every address in the bind list is loopback. */
+export function isLoopbackOnlyBind(bind: readonly string[]): boolean {
+ return bind.every(isLoopbackBindAddress);
+}
+
+/**
+ * The single predicate behind the exposure interlock: consent is required
+ * when the server is reachable beyond this machine — a non-loopback bind
+ * address, or a declared external origin (`publicUrl`, including one
+ * alias-read from `remote.url`).
+ *
+ * Wave 4 wiring requirement: the boot path that enforces this MUST resolve
+ * `allowExternal` scope-correctly — through `mergeLayered` over all three
+ * layers (which fills the project-local default so a committed project-file
+ * value can't win), or by reading the leaf from the project-local layer
+ * directly. The CLI's `loader.ts` currently merges only user + project with a
+ * scope-blind deep merge, so consuming its `Config` here would let a
+ * hand-edited committed `server.allowExternal: true` arm exposure on a
+ * cloner's machine — the exact leak the project-local scope exists to prevent.
+ */
+export function requiresExternalConsent(
+ resolved: Pick<ServerRuntimeConfig, 'loopbackOnly' | 'publicUrl'>,
+): boolean {
+ return !resolved.loopbackOnly || resolved.publicUrl !== undefined;
+}
+
+/**
+ * Convert a validated `idleShutdown` value to milliseconds; `null` for
+ * `'off'`. Throws on a string the schema would have rejected — callers hold
+ * schema-validated config, so a mismatch here is a programming error, not a
+ * user error.
+ */
+export function idleShutdownToMs(value: string): number | null {
+ if (value === 'off') return null;
+ // Validate against the single canonical grammar (shared with the schema
+ // leaf), then split: the match guarantees a trailing s/m/h with a positive
+ // integer before it.
+ if (!IDLE_SHUTDOWN_DURATION_RE.test(value)) {
+ throw new Error(`invalid idleShutdown duration: ${JSON.stringify(value)}`);
+ }
+ const amount = Number(value.slice(0, -1));
+ switch (value.at(-1)) {
+ case 's':
+ return amount * 1000;
+ case 'm':
+ return amount * 60_000;
+ default:
+ return amount * 3_600_000;
+ }
+}
+
+export function resolveServerRuntimeConfig(config: Config | undefined): ServerRuntimeConfig {
+ const server = config?.server;
+ const remote = config?.remote;
+
+ const bind =
+ server?.bind === undefined || server.bind.length === 0 ? DEFAULT_SERVER_BIND : server.bind;
+ const loopbackOnly = isLoopbackOnlyBind(bind);
+
+ // Alias-reads: the successor key wins whenever present; an empty-string
+ // `remote.url` reads as unset (matching `resolveRemoteAccess`).
+ const port = server?.port ?? remote?.port;
+ const legacyUrl = remote?.url === '' ? undefined : remote?.url;
+ const publicUrl = server?.publicUrl ?? legacyUrl;
+
+ return {
+ port,
+ bind,
+ publicUrl,
+ allowExternal: server?.allowExternal ?? false,
+ openBrowser: server?.openBrowser ?? loopbackOnly,
+ idleShutdown: server?.idleShutdown ?? (loopbackOnly ? DEFAULT_LOOPBACK_IDLE_SHUTDOWN : 'off'),
+ loopbackOnly,
+ };
+}
diff --git a/packages/core/src/config/schema-jsonschema.test.ts b/packages/core/src/config/schema-jsonschema.test.ts
index f80262e20..73729fde7 100644
--- a/packages/core/src/config/schema-jsonschema.test.ts
+++ b/packages/core/src/config/schema-jsonschema.test.ts
@@ -155,15 +155,82 @@ const FIXTURES: Fixture[] = [
shouldAccept: true,
},
{
+ // `server.host` is a removed key (REMOVED_KEYS), not a schema leaf — it
+ // rides through the loose `server` section, which now also carries live
+ // leaves (`server.port` etc. below).
name: 'stale dropped fields pass via loose-mode',
input: {
sync: { pushIntervalSeconds: 30 },
persistence: { debounceMs: 2000 },
- server: { port: 3000, host: 'localhost' },
+ server: { host: 'localhost' },
mcp: { autoStart: false },
},
shouldAccept: true,
},
+ {
+ name: 'server.port in range accepted',
+ input: { server: { port: 8080 } },
+ shouldAccept: true,
+ },
+ {
+ name: 'server.port out of range rejected',
+ input: { server: { port: 0 } },
+ shouldAccept: false,
+ },
+ {
+ name: 'server.bind list accepted',
+ input: { server: { bind: ['127.0.0.1', '::1'] } },
+ shouldAccept: true,
+ },
+ {
+ name: 'server.bind empty list rejected',
+ input: { server: { bind: [] } },
+ shouldAccept: false,
+ },
+ {
+ name: 'server.publicUrl https URL accepted',
+ input: { server: { publicUrl: 'https://kb.example.com' } },
+ shouldAccept: true,
+ },
+ {
+ name: 'server.publicUrl non-URL rejected',
+ input: { server: { publicUrl: 'not a url' } },
+ shouldAccept: false,
+ },
+ {
+ // The protocol restriction must appear in the published JSON schema, not
+ // just at runtime — otherwise a $schema-aware editor green-lights a scheme
+ // (ftp:, javascript:) that ConfigSchema rejects at boot. publicUrl drives
+ // CORS + URL issuance, so the divergence is security-relevant.
+ name: 'server.publicUrl ftp:// rejected in both validators (protocol pattern serializes)',
+ input: { server: { publicUrl: 'ftp://kb.example.com' } },
+ shouldAccept: false,
+ },
+ {
+ name: 'server.allowExternal boolean accepted',
+ input: { server: { allowExternal: true } },
+ shouldAccept: true,
+ },
+ {
+ name: 'server.allowExternal string rejected',
+ input: { server: { allowExternal: 'yes' } },
+ shouldAccept: false,
+ },
+ {
+ name: "server.idleShutdown 'off' accepted",
+ input: { server: { idleShutdown: 'off' } },
+ shouldAccept: true,
+ },
+ {
+ name: 'server.idleShutdown duration accepted',
+ input: { server: { idleShutdown: '30m' } },
+ shouldAccept: true,
+ },
+ {
+ name: 'server.idleShutdown unknown unit rejected',
+ input: { server: { idleShutdown: '1d' } },
+ shouldAccept: false,
+ },
];
describe('JSON Schema ↔ runtime equivalence', () => {
@@ -197,7 +264,7 @@ describe('loose-mode forgiveness', () => {
const result = ConfigSchema.safeParse({
sync: { pushIntervalSeconds: 30, autoCommit: true },
persistence: { debounceMs: 2000 },
- server: { port: 3000, host: 'example.dev' },
+ server: { host: 'example.dev' },
mcp: { autoStart: false },
content: { dir: 'docs' },
});
diff --git a/packages/core/src/config/schema-leaf.test.ts b/packages/core/src/config/schema-leaf.test.ts
index 183143714..0ee17fc06 100644
--- a/packages/core/src/config/schema-leaf.test.ts
+++ b/packages/core/src/config/schema-leaf.test.ts
@@ -34,6 +34,7 @@ describe('getLeafFieldMeta', () => {
expect(meta).toEqual({
scope: 'project',
agentSettable: false,
+ reload: 'boot',
defaultScope: 'project',
description: expect.any(String),
});
@@ -44,6 +45,7 @@ describe('getLeafFieldMeta', () => {
expect(meta).toEqual({
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description: expect.any(String),
});
@@ -54,6 +56,7 @@ describe('getLeafFieldMeta', () => {
expect(meta).toEqual({
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description: expect.any(String),
});
@@ -64,6 +67,7 @@ describe('getLeafFieldMeta', () => {
expect(meta).toEqual({
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description: expect.any(String),
});
@@ -74,6 +78,7 @@ describe('getLeafFieldMeta', () => {
expect(meta).toEqual({
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description: expect.any(String),
});
@@ -84,6 +89,7 @@ describe('getLeafFieldMeta', () => {
expect(meta).toEqual({
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description: expect.any(String),
});
@@ -94,6 +100,7 @@ describe('getLeafFieldMeta', () => {
expect(meta).toEqual({
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description: expect.any(String),
});
@@ -104,6 +111,7 @@ describe('getLeafFieldMeta', () => {
expect(meta).toEqual({
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description: expect.any(String),
});
diff --git a/packages/core/src/config/schema.test.ts b/packages/core/src/config/schema.test.ts
index 7bc8211d4..9ccf4919a 100644
--- a/packages/core/src/config/schema.test.ts
+++ b/packages/core/src/config/schema.test.ts
@@ -387,3 +387,63 @@ describe('autoSync forward/backward compatibility (looseObject round-trip)', ()
expect(legacyDefaults.autoSync.default).toBeNull();
});
});
+
+describe('server.* (canonical listener/exposure surface)', () => {
+ test('defaults: loopback-only bind, consent off, everything else unset', () => {
+ const config = ConfigSchema.parse({});
+ expect(config.server.bind).toEqual(['127.0.0.1']);
+ expect(config.server.allowExternal).toBe(false);
+ // No schema default: unset means dynamic locally / platform PORT env in
+ // images, and keeps the remote.port alias-read detectable.
+ expect(config.server.port).toBeUndefined();
+ expect(config.server.publicUrl).toBeUndefined();
+ // Derived defaults resolve in resolveServerRuntimeConfig, not here.
+ expect(config.server.openBrowser).toBeUndefined();
+ expect(config.server.idleShutdown).toBeUndefined();
+ });
+
+ test('port accepts the valid range and rejects out-of-range or fractional values', () => {
+ expect(ConfigSchema.parse({ server: { port: 8080 } }).server.port).toBe(8080);
+ expect(ConfigSchema.safeParse({ server: { port: 0 } }).success).toBe(false);
+ expect(ConfigSchema.safeParse({ server: { port: 65536 } }).success).toBe(false);
+ expect(ConfigSchema.safeParse({ server: { port: 80.5 } }).success).toBe(false);
+ });
+
+ test('bind is a non-empty list of non-empty addresses', () => {
+ expect(ConfigSchema.parse({ server: { bind: ['0.0.0.0'] } }).server.bind).toEqual(['0.0.0.0']);
+ expect(ConfigSchema.parse({ server: { bind: ['127.0.0.1', '::1'] } }).server.bind).toEqual([
+ '127.0.0.1',
+ '::1',
+ ]);
+ expect(ConfigSchema.safeParse({ server: { bind: [] } }).success).toBe(false);
+ expect(ConfigSchema.safeParse({ server: { bind: [''] } }).success).toBe(false);
+ expect(ConfigSchema.safeParse({ server: { bind: '127.0.0.1' } }).success).toBe(false);
+ });
+
+ test('publicUrl accepts http(s) URLs and rejects other schemes or non-URLs', () => {
+ expect(
+ ConfigSchema.parse({ server: { publicUrl: 'https://kb.example.com' } }).server.publicUrl,
+ ).toBe('https://kb.example.com');
+ expect(
+ ConfigSchema.parse({ server: { publicUrl: 'http://localhost:8080' } }).server.publicUrl,
+ ).toBe('http://localhost:8080');
+ expect(ConfigSchema.safeParse({ server: { publicUrl: 'not a url' } }).success).toBe(false);
+ expect(ConfigSchema.safeParse({ server: { publicUrl: 'ftp://kb.example.com' } }).success).toBe(
+ false,
+ );
+ });
+
+ test("idleShutdown accepts 'off' and s/m/h durations, rejects bare numbers and other units", () => {
+ for (const good of ['off', '90s', '30m', '2h']) {
+ expect(ConfigSchema.parse({ server: { idleShutdown: good } }).server.idleShutdown).toBe(good);
+ }
+ for (const bad of ['30', '0m', '1d', 'never', '']) {
+ expect(ConfigSchema.safeParse({ server: { idleShutdown: bad } }).success).toBe(false);
+ }
+ });
+
+ test('remote.port no longer bakes a schema default (alias-read needs absence to be detectable)', () => {
+ expect(ConfigSchema.parse({}).remote.port).toBeUndefined();
+ expect(ConfigSchema.parse({ remote: { port: 24550 } }).remote.port).toBe(24550);
+ });
+});
diff --git a/packages/core/src/config/schema.ts b/packages/core/src/config/schema.ts
index 5d15e077e..60db87fe0 100644
--- a/packages/core/src/config/schema.ts
+++ b/packages/core/src/config/schema.ts
@@ -21,6 +21,7 @@ function base16SlotFields() {
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description: `Custom theme: base16 ${slot} — ${BASE16_SLOT_ROLES[slot]}, as a #rrggbb hex string.`,
})
@@ -72,6 +73,43 @@ const DEFAULT_LOSS_CAPTURE_MAX_BYTES = 12_582_912;
export const DEFAULT_EMBEDDINGS_BASE_URL = 'https://api.openai.com/v1';
export const DEFAULT_EMBEDDINGS_MODEL = 'text-embedding-3-small';
+/**
+ * Loopback-only default bind: nothing off this machine can connect until
+ * `server.bind` says otherwise (and `server.allowExternal` consents to it).
+ */
+export const DEFAULT_SERVER_BIND: readonly string[] = Object.freeze(['127.0.0.1']);
+
+/**
+ * Accepted `server.idleShutdown` duration strings: a positive integer with an
+ * `s` / `m` / `h` unit (e.g. `90s`, `30m`, `2h`). `'off'` is the union's other
+ * arm, not part of this pattern. Kept alongside the schema so the published
+ * JSON schema's `pattern` and the runtime validator cannot drift.
+ */
+export const IDLE_SHUTDOWN_DURATION_RE = /^[1-9]\d*(s|m|h)$/;
+
+/**
+ * `server.publicUrl` scheme guard, paired with the runtime `z.url({ protocol })`
+ * check. Zod's URL `protocol` option validates at runtime but does NOT
+ * serialize through `z.toJSONSchema` (which emits only `format: "uri"`, a
+ * scheme it would accept `ftp:`/`javascript:` under). Attaching this as a
+ * `.regex()` makes the constraint round-trip as a JSON Schema `pattern`, so a
+ * `$schema`-aware editor rejects a non-http(s) origin instead of green-lighting
+ * one that fails at boot. Same round-trip technique as the idle-shutdown grammar.
+ *
+ * Module-local (not exported): unlike `IDLE_SHUTDOWN_DURATION_RE`, the resolver
+ * has no need for it — the scheme constraint lives entirely in the schema leaf.
+ */
+const HTTP_URL_SCHEME_RE = /^https?:\/\//;
+
+/**
+ * Fallback listen port when remote access is enabled but `remote.port` is
+ * unset. Lives in the READERS (`resolveRemoteAccess`, the CLI port
+ * resolution), not as a zod `.default()` — the successor `server.port` is
+ * alias-read from `remote.port` only when unset, and a schema-baked default
+ * would make "unset" undetectable in a parsed config.
+ */
+export const DEFAULT_REMOTE_PORT = 24550;
+
/** Why an embeddings base URL is rejected: unparseable, or a plaintext scheme. */
export type EmbeddingsBaseUrlProblem = 'invalid-url' | 'insecure-scheme';
@@ -155,9 +193,12 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ // Boot-only: re-rooting the content dir live would re-root the whole
+ // index (watcher, Y.Doc registry, link graph) under a running server.
+ reload: 'boot',
defaultScope: 'project',
description:
- 'Folder OpenKnowledge reads and writes documents under, relative to the project root (the folder that contains .ok/). Defaults to the project root. Exclude paths with .okignore.',
+ 'Folder OpenKnowledge reads and writes documents under, relative to the project root (the folder that contains .ok/). Defaults to the project root. Exclude paths with .okignore. Read at server start; changing it requires a restart.',
})
.default('.'),
attachmentFolderPath: z
@@ -165,6 +206,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
"Where pasted and dropped assets are stored, relative to the content root. './' colocates beside the current document (default); '/' targets the content root; './subdir' targets a subfolder under the current document folder; 'folder' targets a fixed folder under the content root. Whitespace-only values are treated as './'.",
@@ -243,6 +285,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description:
"Editor color theme: 'light', 'dark', or 'system' (follow the OS). A personal preference (user scope) — not shared with the project.",
@@ -262,6 +305,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description:
"Interface language. 'system' follows the operating system. A personal preference (user scope) — not shared with the project, and never applied to document content.",
@@ -289,6 +333,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description: `IDE color palette applied in light mode: 'default' (no palette), 'custom' (your own colors from appearance.customTheme), one of ${namedThemeIds()}, or the id of a saved theme. A short id of lowercase letters, digits, and hyphens (max 32 characters); an id no palette matches falls back to 'default' for this mode only, leaving the rest of your config untouched. A personal preference (user scope) — not shared with the project.`,
})
@@ -302,6 +347,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description: `IDE color palette applied in dark mode: 'default' (no palette), 'custom' (your own colors from appearance.customTheme), one of ${namedThemeIds()}, or the id of a saved theme. A short id of lowercase letters, digits, and hyphens (max 32 characters); an id no palette matches falls back to 'default' for this mode only, leaving the rest of your config untouched. A personal preference (user scope) — not shared with the project.`,
})
@@ -321,6 +367,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description:
"Superseded by appearance.colorThemeLight / appearance.colorThemeDark. Read as the palette for both modes while neither of those is set. A short theme id (lowercase letters, digits, and hyphens; max 32 characters); an id no palette matches falls back to 'default'. A personal preference (user scope) — not shared with the project.",
@@ -338,6 +385,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description:
'Whether the Themes plugin appears in Settings → Plugins. A personal preference (user scope). Default on.',
@@ -358,6 +406,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description: "Custom theme: the scheme's display name.",
})
@@ -367,6 +416,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description:
"Custom theme: the scheme's author credit, carried through from an imported base16 scheme.",
@@ -377,6 +427,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description:
"Custom theme: whether the scheme is 'dark' or 'light'. Auto-detected from the palette when omitted.",
@@ -392,6 +443,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description:
'When on, the agent opens or refreshes the live preview after each edit. Turn off if you manage your own preview window. A personal preference (user scope).',
@@ -406,6 +458,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description:
'Show dot-prefixed entries (e.g. .ok/, .okignore) in the file tree. Per-machine (project-local) — not shared with collaborators.',
@@ -416,6 +469,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description:
'Show only markdown documents (.md/.mdx) and folders in the file tree, hiding other file types from view. View-only: hidden files stay on disk and remain reachable via links and search. Per-machine (project-local) — not shared with collaborators.',
@@ -426,6 +480,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description:
'Show the Skills section in the sidebar. Skill documents remain reachable via links and search while the section is hidden. Per-machine (project-local) — not shared with collaborators.',
@@ -436,6 +491,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description:
'Show .ok folders (skills, templates, and other OpenKnowledge-managed state) in the file tree as read-only entries. .ok/worktrees and .ok/local never appear. Per-machine (project-local) — not shared with collaborators.',
@@ -458,6 +514,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description:
'Soft-wrap long lines in the source (CodeMirror) editor. A personal preference (user scope).',
@@ -468,6 +525,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description:
'Reuse one tab when clicking through the Files and Skills sidebars, the way an editor preview tab works. Turn off to open every click in its own tab. Pinned tabs keep their own tab either way. A personal preference (user scope).',
@@ -494,6 +552,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description:
"Auto-approve OpenKnowledge's own tools (and `ok open` on Claude) for agents launched from the built-in terminal. Destructive tools (delete/move/share/install) still prompt. Per-machine personal preference (user scope).",
@@ -528,6 +587,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description:
"How this machine syncs this project with its git remote: 'off' (no sync), 'follow' (one-directional — pull remote changes, never push your own; 'pull' is accepted as a legacy alias), or 'full' (bidirectional pull and push). null = not chosen yet (onboarding asks). Per-machine (project-local) — not shared. Supersedes the legacy autoSync.enabled boolean.",
@@ -541,6 +601,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description:
'Legacy per-machine sync toggle, superseded by autoSync.mode. Read only when mode is absent (true = full, false = off). null = not chosen yet. Per-machine (project-local) — not shared.',
@@ -559,6 +620,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description:
"When sync is paused (autoSync.mode 'off') after having been enabled, the active mode to resume into ('follow' | 'full'). Per-machine UI memory; ignored while a mode is active. Not shared.",
@@ -577,6 +639,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
"Committed project default for a machine's sync mode on first open: 'off' | 'follow' | 'full', or the legacy boolean (true = full, false = off). null = ask (show the onboarding prompt). Shared via git. A per-machine autoSync.mode choice overrides it.",
@@ -609,6 +672,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description:
'Opt-out for the in-app terminal (a real OS shell at full user privilege). The terminal is on by default; set false to disable it for this project on this machine. Per-machine (project-local) — never shared via git, clone, or sync.',
@@ -631,6 +695,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description:
'Whether the Slides plugin appears in Settings → Plugins. When on, a document whose frontmatter has `slides: true` offers an action that opens the deck in a dedicated window (desktop only, requires a resolvable slidev). A personal preference (user scope). Default off.',
@@ -660,6 +725,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
'Write local diagnostic spans + logs under .ok/local/ for `ok diagnose bundle`. Local-only — never leaves the machine until you run bundle. Set false for sensitive workspaces. Shared across collaborators.',
@@ -672,6 +738,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
'Maximum size, in bytes, of the local diagnostic spans file before it rotates (default ~50 MB).',
@@ -686,6 +753,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
'Maximum size, in bytes, of the local diagnostic logs file before it rotates (default ~25 MB).',
@@ -698,6 +766,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
'Telemetry attribute keys whose values are redacted before any local span/log is written (credential / secret guard). Extends the built-in denylist.',
@@ -722,6 +791,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'user',
agentSettable: false,
+ reload: 'live',
defaultScope: 'user',
description:
'Report skill installs to skills.sh so a published skill shows an accurate install count. Sends the skill name, its source repo, and which agent tools it was installed for — never file contents, and never for a private or local source. One report per skill per machine. Default on; the DO_NOT_TRACK and DISABLE_TELEMETRY environment variables also turn it off.',
@@ -755,6 +825,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
'Record bridge loss-class events (content-free) under .ok/local/loss-capture/ for `ok diagnose bundle`. Local-only — never leaves the machine until you run bundle. Set false for sensitive workspaces. Shared across collaborators.',
@@ -765,6 +836,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
'Maximum size, in bytes, of the local loss-capture file before it rotates (default ~12 MB).',
@@ -793,6 +865,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
"Keep the desktop window's timers running at full rate while it holds unsynced work, so backgrounding the app never starves sync or recovery; when the window is idle the OS-default background throttling is restored (battery). Honored by the desktop app. Default ON — disable only to isolate a suspected regression.",
@@ -807,6 +880,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
'Defer a drain-shaped Observer B re-derive when the WYSIWYG fragment holds an un-propagated keystroke Y.Text lacks, so the keystroke survives instead of being stomped. Default ON — disable only to isolate a suspected regression.',
@@ -821,6 +895,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
'Detect content the bridge silently dropped at its reconciliation boundary (an Observer-A apply arm or a paired agent-undo derive) and write a recovery checkpoint plus a content-free loss event. Detection only — never blocks a write. Default ON — disable only to isolate a suspected regression.',
@@ -835,6 +910,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
'Bound the Y.Text→WYSIWYG re-derive loop with a drain-count backstop: a run of re-derive drains that never reaches a raw-byte fixed point freezes the re-derive loop and writes a recovery checkpoint plus a content-free loss event, instead of churning unbounded. Default ON — disable only to isolate a suspected regression.',
@@ -849,6 +925,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
'Before an agent write or undo rebuilds the WYSIWYG fragment, flush an un-propagated keystroke that provably does not overlap the operation into Y.Text so the keystroke survives instead of needing recovery; overlapping or unmodellable cases fall back to the checkpoint floor. Scope: appending writes and single-frame undos — a write that replaces the whole body (replace / edit) overwrites the keystroke either way, so those always take the checkpoint floor. Default ON — disable only to isolate a suspected regression.',
@@ -863,6 +940,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
"On tab hide/unload, force-send each doc's unsynced work to the server and commit its local cache, and re-sync on return to foreground, so a backgrounded tab never strands edits that IndexedDB alone would lose on recycle. Honored client-side. Default ON — disable only to isolate a suspected regression.",
@@ -899,6 +977,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description:
'Add semantic (embeddings) ranking to the MCP search tool, fused with the lexical engine so conceptually-related pages surface even with no shared keywords. When ON and an API key is set (`ok embeddings set-key`), the search query and matching document content are sent to the configured embeddings provider — content egress. Default OFF. Per-machine (project-local) — not shared with collaborators.',
@@ -909,6 +988,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description:
'Base URL of the OpenAI-compatible embeddings API (default https://api.openai.com/v1). Override to point at a self-hosted server (Ollama / vLLM / LM Studio) or another provider. The API key is NOT stored here — set it with `ok embeddings set-key` (`~/.ok/secrets.yml`); it is sent to whichever endpoint this names.',
@@ -919,6 +999,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description:
'Embeddings model id (default text-embedding-3-small). Must be served by the provider at baseUrl. Changing it re-embeds the corpus (the cache is keyed by provider + model + dimensions).',
@@ -931,6 +1012,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description:
"Optional output vector dimensions. Omit (recommended) to detect the model's native size from its first response — that is what lets a non-OpenAI model work without knowing its size up front. Set a smaller value (text-embedding-3 supports e.g. 512 / 1024) to shrink the on-disk cache, trading a little retrieval quality; a server that ignores the request param then fails loudly instead of silently. Changing it re-embeds the corpus.",
@@ -943,6 +1025,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description:
'Optional hard cutoff: drop any "by meaning" match whose cosine similarity is below this value. Off by default (0) because retrieval is rank-based (the closest pages are returned regardless of absolute score) and the right cutoff is model-specific. Set it only to suppress weak matches for a specific provider/model whose cosine scale you know. Most setups should leave it unset and rely on the result-count cap.',
@@ -990,6 +1073,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description: 'Whether the markdownlint plugin (body rules) contributes diagnostics.',
})
@@ -1008,6 +1092,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
'Whether the frontmatter plugin (JSON-Schema validation of document frontmatter) contributes diagnostics.',
@@ -1032,6 +1117,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
'Frontmatter schema mappings: which docs (appliesTo globs) validate against which JSON Schema file (project-root-relative path).',
@@ -1061,6 +1147,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
"How broken internal links are reported on the validation plane: 'off' hides them, 'warning' (default) or 'error' sets their severity.",
@@ -1071,6 +1158,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project',
description:
'Whether the file tree tints and badges files that have validation problems.',
@@ -1097,6 +1185,7 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project-local',
agentSettable: false,
+ reload: 'live',
defaultScope: 'project-local',
description:
"Show a rich preview card (site name, page title, description, favicon) when you hover an external link in the editor. When ON, hovering an external link sends that link's URL to the destination site to fetch its preview metadata — outbound egress, one request per previewed link. Default ON; set to false to turn external previews off. Per-machine (project-local) — not shared with collaborators. Previews of links to other documents in this project are read from the local index with no network request and are always on.",
@@ -1108,6 +1197,19 @@ export const ConfigSchema = z.looseObject({
// the `ok start --remote` flag does. Trust-the-tunnel: no server-side auth
// and no access-level knob; restricting reach is the tunnel's job.
// `agentSettable: false` everywhere so an agent can't self-expose the box.
+ //
+ // SUPERSEDED by the `server.*` section below: `remote.url` by
+ // `server.publicUrl`, `remote.port` by `server.port`. Each is alias-read
+ // only while its successor is absent (`resolveServerRuntimeConfig` — the
+ // same shape as the `autoSync.enabled` → `autoSync.mode` alias). The keys
+ // stay readable so existing configs keep working; removal (REMOVED_KEYS +
+ // `ok config migrate`) comes only after the successors have shipped and
+ // soaked. `remote.port` deliberately has no zod `.default()` — see
+ // `DEFAULT_REMOTE_PORT`.
+ //
+ // Reload class `'boot'`, matching their `server.*` successors: both are
+ // listener/exposure config consumed at server start (via the alias-read in
+ // `resolveServerRuntimeConfig`), so a change takes effect only on restart.
remote: z
.looseObject({
url: z
@@ -1115,9 +1217,10 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'boot',
defaultScope: 'project',
description:
- 'Public URL your tunnel gives you, e.g. https://myproject.ngrok.app. Used only with `ok start --remote` (config alone never enables remote access); its host is admitted through the Host-header allowlist. There is no server-side auth, so restrict access at the tunnel (ngrok OAuth, Cloudflare Access, Tailscale ACLs).',
+ 'Superseded by server.publicUrl — read only while server.publicUrl is absent. Public URL your tunnel gives you, e.g. https://myproject.ngrok.app. Used only with `ok start --remote` (config alone never enables remote access); its host is admitted through the Host-header allowlist. There is no server-side auth, so restrict access at the tunnel (ngrok OAuth, Cloudflare Access, Tailscale ACLs).',
})
.optional(),
port: z
@@ -1128,14 +1231,117 @@ export const ConfigSchema = z.looseObject({
.register(fieldRegistry, {
scope: 'project',
agentSettable: false,
+ reload: 'boot',
+ defaultScope: 'project',
+ description:
+ "Superseded by server.port — read only while server.port is absent. TCP port the server binds when remote access is enabled (default 24550). Fixed so the tunnel's port mapping survives restarts. Set it only on a conflict. An explicit --port still wins; the PORT env var is ignored in remote mode.",
+ })
+ .optional(),
+ })
+ .default({}),
+ // The canonical server surface: one listener whose local vs hosted posture
+ // is EMERGENT from the values set here — there is deliberately no
+ // `server.mode` / profile discriminator key. A mode key becomes a branch
+ // target that drifts from the values that actually matter; "hosted" is
+ // just what a non-loopback bind, a public URL, and consent look like.
+ //
+ // Scopes: `port` / `bind` / `publicUrl` are PROJECT — the committed,
+ // reviewed shape of this knowledge base's server. `openBrowser` /
+ // `idleShutdown` are PROJECT-LOCAL — personal workflow, like the sidebar
+ // toggles. `allowExternal` is PROJECT-LOCAL consent, the same posture as
+ // `terminal.enabled`: consent never travels via git, clone, or share, so a
+ // committed `allowExternal: true` can never expose a future cloner's
+ // machine (containers consent via environment instead).
+ //
+ // `agentSettable: false` on every leaf, same reasoning as `remote.*`: an
+ // agent must never widen its own network exposure.
+ //
+ // `openBrowser` and `idleShutdown` have DERIVED defaults (they depend on
+ // whether the resolved `bind` is loopback-only), so those leaves stay
+ // optional here — a schema-time `.default()` cannot see `bind`. The
+ // derivation lives in `resolveServerRuntimeConfig`
+ // (`resolve-server-config.ts`), which is also the single alias-read point
+ // for the superseded `remote.*` keys.
+ server: z
+ .looseObject({
+ port: z
+ .number()
+ .int()
+ .min(1)
+ .max(65535)
+ .register(fieldRegistry, {
+ scope: 'project',
+ agentSettable: false,
+ reload: 'boot',
+ defaultScope: 'project',
+ description:
+ 'TCP port the server listens on. Unset by default: a local start picks a free port dynamically, and deployment platforms inject the PORT environment variable instead. Supersedes remote.port (still read while this key is absent). Read at server start; changing it requires a restart.',
+ })
+ .optional(),
+ bind: z
+ .array(z.string().min(1))
+ .min(1)
+ .register(fieldRegistry, {
+ scope: 'project',
+ agentSettable: false,
+ reload: 'boot',
+ defaultScope: 'project',
+ description:
+ 'Addresses the server binds, e.g. [127.0.0.1] or [0.0.0.0]. Default loopback-only ([127.0.0.1]): nothing off this machine can connect. A non-loopback bind additionally requires the server.allowExternal consent interlock. Lists replace, never merge. Read at server start; changing it requires a restart.',
+ })
+ .default([...DEFAULT_SERVER_BIND]),
+ publicUrl: z
+ .url({ protocol: /^https?$/ })
+ // Runtime protocol check + the JSON-schema-serializable pattern (see
+ // HTTP_URL_SCHEME_RE) — together they keep the published schema and the
+ // runtime parser in agreement on the scheme.
+ .regex(HTTP_URL_SCHEME_RE)
+ .register(fieldRegistry, {
+ scope: 'project',
+ agentSettable: false,
+ reload: 'boot',
defaultScope: 'project',
description:
- "TCP port the server binds when remote access is enabled (default 24550). Fixed so the tunnel's port mapping survives restarts. Set it only on a conflict. An explicit --port still wins; the PORT env var is ignored in remote mode.",
+ 'Canonical external origin the server is reached at, e.g. https://kb.example.com — drives issued URLs and CORS. Unset by default: a loopback server derives http://localhost:<port>. Setting it declares external exposure, which additionally requires the server.allowExternal consent interlock. Supersedes remote.url (still read while this key is absent). Read at server start; changing it requires a restart.',
})
- .default(24550),
+ .optional(),
+ allowExternal: z
+ .boolean()
+ .register(fieldRegistry, {
+ scope: 'project-local',
+ agentSettable: false,
+ reload: 'boot',
+ defaultScope: 'project-local',
+ description:
+ 'Exposure consent interlock. Once the unified server boot lands, a non-loopback server.bind or a server.publicUrl without allowExternal: true will be refused at boot with a one-line fix. Default off. Per-machine (project-local) — consent never travels via git, clone, or share; containers consent via the environment instead.',
+ })
+ .default(false),
+ openBrowser: z
+ .boolean()
+ .register(fieldRegistry, {
+ scope: 'project-local',
+ agentSettable: false,
+ reload: 'boot',
+ defaultScope: 'project-local',
+ description:
+ 'Open the UI in a browser when the server starts. Default derived: true when every bind address is loopback (a laptop start pops the UI), false otherwise (a container or exposed bind is headless and must never try). Acts once at start. Per-machine (project-local) — not shared.',
+ })
+ .optional(),
+ idleShutdown: z
+ .union([z.literal('off'), z.string().regex(IDLE_SHUTDOWN_DURATION_RE)])
+ .register(fieldRegistry, {
+ scope: 'project-local',
+ agentSettable: false,
+ reload: 'live',
+ defaultScope: 'project-local',
+ description:
+ "Shut the server down after this long with no activity: a duration like '30m' (positive integer with unit s, m, or h), or 'off'. Default derived: '30m' when every bind address is loopback, 'off' otherwise (an exposed or containerized server stays up). Reloadable — a valid change applies without a restart. Per-machine (project-local) — not shared.",
+ })
+ .optional(),
})
.default({
- port: 24550,
+ bind: [...DEFAULT_SERVER_BIND],
+ allowExternal: false,
}),
});
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 0ccea339a..fac8b80c2 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -193,6 +193,7 @@ export {
type FieldMeta,
fieldRegistry,
getFieldMeta,
+ type ReloadClass,
} from './config/field-registry.ts';
export { mergeLayered } from './config/merge-layered.ts';
export {
@@ -202,6 +203,15 @@ export {
type RemovedKey,
stripRemovedKeys,
} from './config/removed-keys.ts';
+export {
+ DEFAULT_LOOPBACK_IDLE_SHUTDOWN,
+ idleShutdownToMs,
+ isLoopbackBindAddress,
+ isLoopbackOnlyBind,
+ requiresExternalConsent,
+ resolveServerRuntimeConfig,
+ type ServerRuntimeConfig,
+} from './config/resolve-server-config.ts';
export type { Err, Ok, Result } from './config/result.ts';
// Config schema, error envelope, and Result helper. Browser+node compatible.
export {
@@ -212,8 +222,11 @@ export {
DEFAULT_EMBEDDINGS_BASE_URL,
DEFAULT_EMBEDDINGS_MODEL,
DEFAULT_LOGS_MAX_BYTES,
+ DEFAULT_REMOTE_PORT,
+ DEFAULT_SERVER_BIND,
DEFAULT_SPANS_MAX_BYTES,
DEFAULT_TELEMETRY_ATTRIBUTE_DENYLIST,
+ IDLE_SHUTDOWN_DURATION_RE,
isLoopbackEmbeddingsUrl,
isValidAttachmentFolderPath,
normalizeAttachmentFolderPath,
diff --git a/packages/server/src/remote-access.ts b/packages/server/src/remote-access.ts
index 14f1cebda..88d38b4d0 100644
--- a/packages/server/src/remote-access.ts
+++ b/packages/server/src/remote-access.ts
@@ -17,6 +17,7 @@
*/
import type { IncomingMessage } from 'node:http';
+import { DEFAULT_REMOTE_PORT } from '@inkeep/open-knowledge-core';
import type { Config } from './config/schema.ts';
import { isAllowedWorkspaceHostHeader, isLoopbackAddress } from './loopback.ts';
@@ -25,7 +26,7 @@ export interface ResolvedRemoteAccess {
url: string;
/** `host[:port]` of `url` with any default-port suffix stripped — Host-header comparand. */
publicHost: string;
- /** Fixed listen port from config (schema default 24550). */
+ /** Fixed listen port from config (`remote.port`, falling back to 24550). */
port: number;
}
@@ -54,7 +55,7 @@ export function resolveRemoteAccess(config: Config | undefined): ResolvedRemoteA
return {
url: remote.url.replace(/\/+$/, ''),
publicHost: normalizeHostHeader(parsed.host),
- port: remote.port,
+ port: remote.port ?? DEFAULT_REMOTE_PORT,
};
}