Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Instrument desktop startup (waterfall log + cross-process OTel trace) (#2313)
Andrew Mikofalvy54d4a3e81c8c
diff --git a/.changeset/desktop-startup-instrumentation.md b/.changeset/desktop-startup-instrumentation.mdnew file mode 100644index 000000000..fcba7d28b--- /dev/null+++ b/.changeset/desktop-startup-instrumentation.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Add always-on desktop startup instrumentation. Every launch now emits one structured `desktop.startup-timeline` log line with bounded per-phase durations (app-ready → bootstrap → server spawn → lock-ready → window → load → shown, plus the server's HTTP-listen / seed-walk / index / ready timings and the renderer's page-list and first-content marks). The server exposes its boot timings on `GET /api/server-info`, and the file-watcher seed walk and index phases are now traced (`ok.boot.seed-walk`, `ok.boot.indexes`). When OpenTelemetry is enabled, the three processes (Electron main, server, renderer) join into a single correlated `ok.app-startup` trace via W3C traceparent propagation. This is instrumentation only; startup behavior and timing are unchanged.diff --git a/bun.lock b/bun.lockindex b899f4e4f..8645e7a73 100644--- a/bun.lock+++ b/bun.lock@@ -334,6 +334,7 @@"@inkeep/open-knowledge-native-config": "workspace:*","@inkeep/open-knowledge-server": "workspace:*","@napi-rs/keyring": "^1.3.0",+ "@opentelemetry/api": "^1.9.0","electron-updater": "6.8.4","node-pty": "1.1.0","pino": "^10.3.1",diff --git a/packages/app/src/components/PageListContext.tsx b/packages/app/src/components/PageListContext.tsxindex 7a1a116ab..06eda495a 100644--- a/packages/app/src/components/PageListContext.tsx+++ b/packages/app/src/components/PageListContext.tsx@@ -9,6 +9,7 @@ import {import { subscribeToDocumentsChanged } from '@/lib/documents-events';import { fetchDocumentListShared } from '@/lib/documents-fetch';import { parseApiError } from '@/lib/parse-api-error';+import { pageListReady } from '@/lib/perf/startup-marks';import { deriveKnownFolderPaths } from './navigation-targets';export interface PageMeta {@@ -183,6 +184,7 @@ export function PageListProvider({ children }: { children: ReactNode }) {setServerFilePaths(new Set(documentList.filePaths));setOptimisticPages((prev) => pruneConfirmedOptimisticPages(prev, pageNames));setError(null);+ pageListReady();}).catch((err) => {if (requestId !== latestRequestIdRef.current) return;diff --git a/packages/app/src/editor/sync-promise.ts b/packages/app/src/editor/sync-promise.tsindex e9d436d48..5b414b7d1 100644--- a/packages/app/src/editor/sync-promise.ts+++ b/packages/app/src/editor/sync-promise.ts@@ -2,6 +2,7 @@ import type { HocuspocusProvider, onCloseParameters } from '@hocuspocus/providerimport { mark } from '@/lib/perf';import { readNumericOverride } from '@/lib/perf/env-override';import { emitColdMountChild, finalizeColdMountSpan } from '@/lib/perf/otel-spans';+import { firstContent } from '@/lib/perf/startup-marks';import { getMountId } from './mount-id-registry';export function getSyncTimeoutMs(): number {@@ -248,6 +249,7 @@ export function syncPromise(docName: string, provider: HocuspocusProvider): Promdetach(entry);if (!hasPendingEntries()) uninstallVisibilityHandler();entry.resolve();+ firstContent();if (coldMountId !== undefined) {const nowMs = Date.now();emitColdMountChild(diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.tsindex 5a161d2a6..3577a118d 100644--- a/packages/app/src/lib/desktop-bridge-types.ts+++ b/packages/app/src/lib/desktop-bridge-types.ts@@ -123,6 +123,7 @@ export interface OkDesktopConfig {readonly e2eSmoke: boolean;readonly singleFile: boolean;readonly initialDoc: string | null;+ readonly startupTraceparent?: string;}type OkMenuAction =@@ -728,6 +729,9 @@ export interface OkDesktopBridge {notifyActiveTargetChanged(target: OkEditorActiveTargetSnapshot): void;notifyViewMenuStateChanged(state: Partial<OkEditorViewMenuStateSnapshot>): void;};+ startup: {+ reportMarks(marks: { pageListReadyMs: number; firstContentMs: number }): void;+ };sidebar: {expandAll(cb: () => void): OkUnsubscribe;collapseAll(cb: () => void): OkUnsubscribe;diff --git a/packages/app/src/lib/perf/startup-marks.test.ts b/packages/app/src/lib/perf/startup-marks.test.tsnew file mode 100644index 000000000..24efb803b--- /dev/null+++ b/packages/app/src/lib/perf/startup-marks.test.ts@@ -0,0 +1,118 @@+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import {+ __resetStartupMarksForTest,+ firstContent,+ onFirstContent,+ pageListReady,+} from './startup-marks';++interface ReportedMarks {+ pageListReadyMs: number;+ firstContentMs: number;+}++const globalRef = globalThis as unknown as { window?: { okDesktop?: unknown } };+const HAD_WINDOW = 'window' in globalRef;+const ORIGINAL_WINDOW = globalRef.window;++function win(): { okDesktop?: unknown } {+ globalRef.window ??= {};+ return globalRef.window;+}++function installBridge(): ReportedMarks[] {+ const calls: ReportedMarks[] = [];+ win().okDesktop = {+ startup: {+ reportMarks: (marks: ReportedMarks) => {+ calls.push(marks);+ },+ },+ };+ return calls;+}++function clearBridge(): void {+ delete win().okDesktop;+}++beforeEach(() => {+ __resetStartupMarksForTest();+});++afterEach(() => {+ __resetStartupMarksForTest();+ if (HAD_WINDOW) globalRef.window = ORIGINAL_WINDOW;+ else delete globalRef.window;+});++describe('startup-marks', () => {+ test('reports only once both checkpoints land, with first-content = the later of the two', () => {+ const calls = installBridge();+ pageListReady();+ expect(calls.length).toBe(0);+ firstContent();+ expect(calls.length).toBe(1);+ const { pageListReadyMs, firstContentMs } = calls[0];+ expect(firstContentMs).toBeGreaterThanOrEqual(pageListReadyMs);+ });++ test('first-content is the later of the two regardless of arrival order', () => {+ const calls = installBridge();+ firstContent();+ expect(calls.length).toBe(0);+ pageListReady();+ expect(calls.length).toBe(1);+ const { pageListReadyMs, firstContentMs } = calls[0];+ expect(firstContentMs).toBe(pageListReadyMs);+ });++ test('reports exactly once even if checkpoints fire repeatedly', () => {+ const calls = installBridge();+ pageListReady();+ pageListReady();+ firstContent();+ firstContent();+ pageListReady();+ expect(calls.length).toBe(1);+ });++ test('is a no-op (no throw) when the desktop bridge is absent', () => {+ clearBridge();+ expect(() => {+ pageListReady();+ firstContent();+ }).not.toThrow();+ });++ test('is a no-op when the bridge lacks the startup surface (older host)', () => {+ win().okDesktop = {};+ expect(() => {+ pageListReady();+ firstContent();+ }).not.toThrow();+ });++ test('onFirstContent fires with the computed first-content epoch when both land', () => {+ installBridge();+ let received: number | undefined;+ onFirstContent((ms) => {+ received = ms;+ });+ pageListReady();+ expect(received).toBeUndefined();+ firstContent();+ expect(typeof received).toBe('number');+ });++ test('onFirstContent fires immediately if first-content already reached', () => {+ installBridge();+ pageListReady();+ firstContent();+ let received: number | undefined;+ onFirstContent((ms) => {+ received = ms;+ });+ expect(typeof received).toBe('number');+ });+});diff --git a/packages/app/src/lib/perf/startup-marks.ts b/packages/app/src/lib/perf/startup-marks.tsnew file mode 100644index 000000000..f3d63ab66--- /dev/null+++ b/packages/app/src/lib/perf/startup-marks.ts@@ -0,0 +1,48 @@+import { mark } from './index';++let pageListReadyAt: number | undefined;+let activeDocSyncedAt: number | undefined;+let reported = false;+let firstContentListener: ((firstContentMs: number) => void) | undefined;++export function onFirstContent(listener: (firstContentMs: number) => void): void {+ if (reported && pageListReadyAt !== undefined && activeDocSyncedAt !== undefined) {+ listener(Math.max(pageListReadyAt, activeDocSyncedAt));+ return;+ }+ firstContentListener = listener;+}++function maybeReport(): void {+ if (reported) return;+ if (pageListReadyAt === undefined || activeDocSyncedAt === undefined) return;+ reported = true;++ const firstContentMs = Math.max(pageListReadyAt, activeDocSyncedAt);+ const reportMarks =+ typeof window !== 'undefined' ? window.okDesktop?.startup?.reportMarks : undefined;+ reportMarks?.({ pageListReadyMs: pageListReadyAt, firstContentMs });+ firstContentListener?.(firstContentMs);+ firstContentListener = undefined;+}++export function pageListReady(): void {+ if (pageListReadyAt !== undefined) return;+ pageListReadyAt = Date.now();+ mark('ok/startup/page-list-ready');+ maybeReport();+}++export function firstContent(): void {+ if (activeDocSyncedAt !== undefined) return;+ activeDocSyncedAt = Date.now();+ mark('ok/startup/first-content');+ maybeReport();+}++export function __resetStartupMarksForTest(): void {+ pageListReadyAt = undefined;+ activeDocSyncedAt = undefined;+ reported = false;+ firstContentListener = undefined;+}diff --git a/packages/app/src/main.tsx b/packages/app/src/main.tsxindex b776e8cb0..d67f9081c 100644--- a/packages/app/src/main.tsx+++ b/packages/app/src/main.tsx@@ -1,6 +1,7 @@import { initFrontendTelemetry } from './telemetry';initFrontendTelemetry();+void import('./telemetry-startup').then((m) => m.initStartupTrace());import '@/lib/perf/scheduler-polyfill-shim';diff --git a/packages/app/src/telemetry-startup.ts b/packages/app/src/telemetry-startup.tsnew file mode 100644index 000000000..714333987--- /dev/null+++ b/packages/app/src/telemetry-startup.ts@@ -0,0 +1,25 @@+import { context, propagation, type Span } from '@opentelemetry/api';+import { onFirstContent } from '@/lib/perf/startup-marks';+import { getAppTracer } from './telemetry-impl';++let startupSpan: Span | undefined;++export function initStartupTrace(): void {+ if (startupSpan) return;+ try {+ const traceparent =+ typeof window !== 'undefined' ? window.okDesktop?.config.startupTraceparent : undefined;+ if (!traceparent) return;++ const parentCtx = propagation.extract(context.active(), { traceparent });+ const span = getAppTracer().startSpan('ok.app-startup', undefined, parentCtx);+ startupSpan = span;++ onFirstContent((firstContentMs) => {+ try {+ span.end(firstContentMs);+ } catch {}+ startupSpan = undefined;+ });+ } catch {}+}diff --git a/packages/app/tests/integration/api-error-envelope/server-info.test.ts b/packages/app/tests/integration/api-error-envelope/server-info.test.tsindex 8dd9c7948..880c0e994 100644--- a/packages/app/tests/integration/api-error-envelope/server-info.test.ts+++ b/packages/app/tests/integration/api-error-envelope/server-info.test.ts@@ -1,5 +1,9 @@import { afterAll, beforeAll, describe, expect, test } from 'bun:test';-import { ProblemDetailsSchema, ServerInfoSuccessSchema } from '@inkeep/open-knowledge-core';+import {+ ProblemDetailsSchema,+ ServerInfoBootSchema,+ ServerInfoSuccessSchema,+} from '@inkeep/open-knowledge-core';import { HARNESS_BOOT_TIMEOUT_MS } from '../harness-boot-timeout';import { createTestServer, type TestServer } from '../test-harness';@@ -28,6 +32,44 @@ describe('server-info envelope (RFC 9457)', () => {expect((body as Record<string, unknown>).ok).toBeUndefined();});+ test('optional boot timings block round-trips through the success schema', () => {+ const boot = {+ startedAt: '2026-06-30T00:00:00.000Z',+ httpListenMs: 12,+ seedWalkMs: 34,+ indexesMs: 56,+ readyMs: 78,+ fileCount: 9,+ };+ expect(ServerInfoBootSchema.safeParse(boot).success).toBe(true);++ const withBoot = ServerInfoSuccessSchema.safeParse({+ serverInstanceId: 'test-instance',+ currentBranch: 'main',+ boot,+ });+ expect(withBoot.success).toBe(true);+ if (withBoot.success) {+ expect(withBoot.data.boot).toEqual(boot);+ }++ const withoutBoot = ServerInfoSuccessSchema.safeParse({+ serverInstanceId: 'test-instance',+ });+ expect(withoutBoot.success).toBe(true);+ if (withoutBoot.success) {+ expect(withoutBoot.data.boot).toBeUndefined();+ }++ expect(ServerInfoBootSchema.safeParse({ startedAt: '2026-06-30T00:00:00.000Z' }).success).toBe(+ true,+ );+ expect(+ ServerInfoBootSchema.safeParse({ startedAt: '2026-06-30T00:00:00.000Z', readyMs: -1 })+ .success,+ ).toBe(false);+ });+test('method-not-allowed on POST emits problem+json with Allow: GET', async () => {const res = await fetch(`http://127.0.0.1:${server.port}/api/server-info`, { method: 'POST' });expect(res.status).toBe(405);diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.tsindex 6855caa6e..72380fbee 100644--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts@@ -348,6 +348,9 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): PnotifyActiveTargetChanged: (): void => {},notifyViewMenuStateChanged: (): void => {},},+ startup: {+ reportMarks: (): void => {},+ },sidebar: {expandAll: (_cb: () => void) => () => {},collapseAll: (_cb: () => void) => () => {},diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.tsindex a430d1dc3..9170a46b6 100644--- a/packages/core/src/desktop-bridge.ts+++ b/packages/core/src/desktop-bridge.ts@@ -719,6 +719,10 @@ export interface OkDesktopBridge {notifyViewMenuStateChanged(state: Partial<OkEditorViewMenuStateSnapshot>): void;};+ startup: {+ reportMarks(marks: { pageListReadyMs: number; firstContentMs: number }): void;+ };+sidebar: {expandAll(cb: () => void): OkUnsubscribe;collapseAll(cb: () => void): OkUnsubscribe;diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 23ad52a40..f00e3c2a5 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -776,6 +776,8 @@ export {SeedPlanSuccessSchema,type SemanticIndexStatus,SemanticIndexStatusSchema,+ type ServerInfoBoot,+ ServerInfoBootSchema,type ServerInfoSuccess,ServerInfoSuccessSchema,type ShareConstructUrlErrorCode,diff --git a/packages/core/src/schemas/api/_envelope.ts b/packages/core/src/schemas/api/_envelope.tsindex 368247080..b11a767b3 100644--- a/packages/core/src/schemas/api/_envelope.ts+++ b/packages/core/src/schemas/api/_envelope.ts@@ -4,11 +4,22 @@ import { z } from 'zod';import { URN_UUID_RE } from './_shared.ts';import { isValidBranchName } from './share.ts';+export const ServerInfoBootSchema = z.object({+ startedAt: z.string().min(1),+ httpListenMs: z.number().nonnegative().optional(),+ seedWalkMs: z.number().nonnegative().optional(),+ indexesMs: z.number().nonnegative().optional(),+ readyMs: z.number().nonnegative().optional(),+ fileCount: z.number().nonnegative().optional(),+});+export type ServerInfoBoot = z.infer<typeof ServerInfoBootSchema>;+export const ServerInfoSuccessSchema = z.object({serverInstanceId: z.string().min(1),currentBranch: z.string().min(1).optional(),currentDiskAckSVs: z.record(z.string().min(1), z.string().min(1)).optional(),+ boot: ServerInfoBootSchema.optional(),}).loose() satisfies StandardSchemaV1;export type ServerInfoSuccess = z.infer<typeof ServerInfoSuccessSchema>;diff --git a/packages/desktop/package.json b/packages/desktop/package.jsonindex cb973bf2c..7b48947d1 100644--- a/packages/desktop/package.json+++ b/packages/desktop/package.json@@ -30,6 +30,7 @@"@inkeep/open-knowledge-native-config": "workspace:*","@inkeep/open-knowledge-server": "workspace:*","@napi-rs/keyring": "^1.3.0",+ "@opentelemetry/api": "^1.9.0","electron-updater": "6.8.4","node-pty": "1.1.0","pino": "^10.3.1",diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex af360159b..9fc3c87ec 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -35,6 +35,7 @@ import {import {CLIENT_VERSION_HEADER,PROTOCOL_VERSION,+ ServerInfoSuccessSchema,SPAWN_ERROR_LOG,TERMINAL_CLIS,type TerminalCli,@@ -207,6 +208,8 @@ import { createShowGateRegistry, type ShowGateRegistry } from './show-gate.ts';import { reclaimProjectSkillsOnProjectOpen, reclaimUserSkillsOnLaunch } from './skill-reclaim.ts';import { attachSpellcheckContextMenu } from './spellcheck-context-menu.ts';import { popSpellcheckMenu } from './spellcheck-menu.ts';+import { beginRoot, childSpan, endRoot, injectTraceparent } from './startup-trace.ts';+import { type RendererMarks, StartupWaterfall } from './startup-waterfall.ts';import {type AppState,addRecentProject,@@ -428,6 +431,66 @@ let navigatorWindow: BrowserWindowLike | null = null;let wm: WindowManager;let terminalReaper: TerminalReaper | null = null;const dockVisibleForWindow = new Map<number, boolean>();+const startupWaterfall = new StartupWaterfall({ otelEnabled: false });+let firstWindowShown = false;+let waterfallDeadlineTimer: ReturnType<typeof setTimeout> | undefined;++function emitStartupWaterfall(): void {+ if (waterfallDeadlineTimer !== undefined) {+ clearTimeout(waterfallDeadlineTimer);+ waterfallDeadlineTimer = undefined;+ }+ const payload = startupWaterfall.emit({+ info: (obj, msg) => getLogger('startup').info(obj, msg),+ });+ if (payload !== undefined) {+ if (startupWaterfall.otelEnabled) {+ for (const phase of startupWaterfall.mainPhaseIntervals()) {+ childSpan(phase.name, {}, phase.startMs, phase.endMs);+ }+ }+ endRoot();+ }+}++function onFirstWindowShown(): void {+ if (firstWindowShown) return;+ firstWindowShown = true;+ startupWaterfall.mark('windowShown');+ if (startupWaterfall.readyToEmit) {+ emitStartupWaterfall();+ return;+ }+ waterfallDeadlineTimer = setTimeout(() => {+ waterfallDeadlineTimer = undefined;+ emitStartupWaterfall();+ }, startupWaterfall.flushDeadlineMs);+ waterfallDeadlineTimer.unref?.();+}++let serverBootFetched = false;+function maybeFetchServerBoot(apiOrigin: string): void {+ if (serverBootFetched) return;+ serverBootFetched = true;+ void (async () => {+ try {+ const res = await fetch(`${apiOrigin}/api/server-info`, {+ signal: AbortSignal.timeout(startupWaterfall.flushDeadlineMs),+ });+ if (!res.ok) return;+ const parsed = ServerInfoSuccessSchema.safeParse(await res.json());+ if (!parsed.success || parsed.data.boot === undefined) return;+ startupWaterfall.ingestServerBoot(parsed.data.boot);+ if (firstWindowShown && startupWaterfall.canEmit) emitStartupWaterfall();+ } catch {}+ })();+}++function ingestRendererStartupMarks(marks: RendererMarks): void {+ startupWaterfall.ingestRendererMarks(marks);+ if (firstWindowShown && startupWaterfall.canEmit) emitStartupWaterfall();+}+const showGate: ShowGateRegistry = createShowGateRegistry({log: {warn: (obj, msg) => {@@ -436,6 +499,7 @@ const showGate: ShowGateRegistry = createShowGateRegistry({},setTimeout: (cb, ms) => setTimeout(cb, ms),clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),+ onShown: () => onFirstWindowShown(),});const reducedTransparencyDeps: ReducedTransparencyDeps = {@@ -559,9 +623,13 @@ function ensureWindowManager() {if (process.platform === 'darwin') app.focus({ steal: true });},forkUtility: (entry, args, opts) => {+ startupWaterfall.mark('serverSpawned');const child = utilityProcess.fork(entry, args, {...opts,- env: buildUtilityForkEnv(process.env),+ env: buildUtilityForkEnv(process.env, {+ startupTraceparent: injectTraceparent(),+ otlpEndpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,+ }),} as unknown as Parameters<typeof utilityProcess.fork>[2]);return child as unknown as UtilityProcessLike;},@@ -620,10 +688,14 @@ function ensureWindowManager() {reactShellDistDir,contentDir,spawnErrorLogFd,- env: buildUtilityForkEnv(process.env),+ env: buildUtilityForkEnv(process.env, {+ startupTraceparent: injectTraceparent(),+ otlpEndpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT,+ }),...(singleFile !== undefined ? { singleFile, projectDir } : {}),});let childRef: ReturnType<typeof spawn>;+ startupWaterfall.mark('serverSpawned');try {childRef = spawn(spawnArgs.file, spawnArgs.args, spawnArgs.opts);} catch (spawnErr) {@@ -710,6 +782,17 @@ function ensureWindowManager() {readServerLock: (lockDir) => readServerLock(lockDir),}),showGate,+ startup: {+ get traceparent() {+ return injectTraceparent();+ },+ markServerLockReady: (info) => {+ startupWaterfall.mark('serverLockReady');+ if (info?.apiOrigin !== undefined) maybeFetchServerBoot(info.apiOrigin);+ },+ markWindowCreated: () => startupWaterfall.mark('windowCreated'),+ markLoadUrlResolved: () => startupWaterfall.mark('loadUrlResolved'),+ },});}@@ -1999,6 +2082,14 @@ function registerIpcHandlers() {return undefined;});+ handle('ok:startup:renderer-marks', async (_event, marks) => {+ if (!Number.isFinite(marks?.pageListReadyMs) || !Number.isFinite(marks?.firstContentMs)) {+ return undefined;+ }+ ingestRendererStartupMarks(marks);+ return undefined;+ });+handle('ok:project:get-info', async (event) => {const win = BrowserWindow.fromWebContents(event.sender);if (!win) throw new Error('webContents has no parent BrowserWindow');@@ -2653,6 +2744,8 @@ function bootPrimaryInstance(): void {app.whenReady().then(async () => {+ startupWaterfall.mark('appReady');+ startupWaterfall.otelEnabled = beginRoot();const userDataMigrationLog = getLogger('userdata-migration');const userDataMigration = await migrateLegacyUserDataDir({userDataDir: app.getPath('userData'),@@ -2687,6 +2780,7 @@ function bootPrimaryInstance(): void {});appState = result.appState;pendingSchemaIncompatibility = result.pendingSchemaIncompatibility;+ startupWaterfall.mark('bootstrapDone');app.on('browser-window-created', (_event, win) => {win.webContents.once('did-finish-load', () => {@@ -2963,6 +3057,8 @@ function bootPrimaryInstance(): void {app.on('before-quit', () => {getLogger('lifecycle').info({}, 'before-quit');+ emitStartupWaterfall();+ endRoot();flushDesktopLogger();});electronAutoUpdater.on('before-quit-for-update', () => {diff --git a/packages/desktop/src/main/show-gate.ts b/packages/desktop/src/main/show-gate.tsindex b9e4d062b..c2136a36f 100644--- a/packages/desktop/src/main/show-gate.ts+++ b/packages/desktop/src/main/show-gate.ts@@ -9,6 +9,7 @@ interface ShowGateRegistryDeps {setTimeout: (cb: () => void, ms: number) => unknown;clearTimeout?: (handle: unknown) => void;timeoutMs?: number;+ onShown?: (kind: WindowKind) => void;}export interface ShowGateRegistry {@@ -40,6 +41,18 @@ export function createShowGateRegistry(deps: ShowGateRegistryDeps): ShowGateRegitry {window.show?.();state.shown = true;+ try {+ deps.onShown?.(state.kind);+ } catch (cbErr) {+ deps.log?.warn(+ {+ event: 'show-gate-on-shown-failed',+ windowKind: state.kind,+ error: cbErr instanceof Error ? cbErr.message : String(cbErr),+ },+ 'show-gate onShown callback threw',+ );+ }} catch (err) {deps.log?.warn({diff --git a/packages/desktop/src/main/startup-trace.test.ts b/packages/desktop/src/main/startup-trace.test.tsnew file mode 100644index 000000000..fba09c078--- /dev/null+++ b/packages/desktop/src/main/startup-trace.test.ts@@ -0,0 +1,50 @@+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import {+ __resetStartupTraceForTest,+ beginRoot,+ childSpan,+ endRoot,+ injectTraceparent,+ isStartupTraceActive,+} from './startup-trace.ts';++const prevDisabled = process.env.OTEL_SDK_DISABLED;++beforeEach(() => {+ __resetStartupTraceForTest();+});++afterEach(() => {+ __resetStartupTraceForTest();+ endRoot();+ if (prevDisabled === undefined) delete process.env.OTEL_SDK_DISABLED;+ else process.env.OTEL_SDK_DISABLED = prevDisabled;+});++describe('startup-trace (Plan A) — disabled path', () => {+ test('beginRoot is a no-op when OTEL_SDK_DISABLED is not "false"', () => {+ delete process.env.OTEL_SDK_DISABLED;+ expect(beginRoot()).toBe(false);+ expect(isStartupTraceActive()).toBe(false);+ });++ test('beginRoot is a no-op when OTEL_SDK_DISABLED === "true"', () => {+ process.env.OTEL_SDK_DISABLED = 'true';+ expect(beginRoot()).toBe(false);+ expect(isStartupTraceActive()).toBe(false);+ });++ test('injectTraceparent returns undefined when not active', () => {+ delete process.env.OTEL_SDK_DISABLED;+ beginRoot();+ expect(injectTraceparent()).toBeUndefined();+ });++ test('childSpan + endRoot are safe no-ops when not active', () => {+ delete process.env.OTEL_SDK_DISABLED;+ expect(() => {+ childSpan('phase', { ok: true }, 0, 1);+ endRoot();+ }).not.toThrow();+ });+});diff --git a/packages/desktop/src/main/startup-trace.ts b/packages/desktop/src/main/startup-trace.tsnew file mode 100644index 000000000..5cc3d6dd1--- /dev/null+++ b/packages/desktop/src/main/startup-trace.ts@@ -0,0 +1,78 @@+import { getTracer, initTelemetry } from '@inkeep/open-knowledge-server';+import { type Context, context, propagation, type Span, trace } from '@opentelemetry/api';+import { getLogger } from './desktop-logger.ts';++let rootSpan: Span | undefined;+let rootContext: Context | undefined;+let active = false;++export function beginRoot(): boolean {+ if (active) return true;+ if (process.env.OTEL_SDK_DISABLED !== 'false') return false;+ try {+ initTelemetry();+ const span = getTracer().startSpan('ok.app-startup');+ if (!span.isRecording()) {+ span.end();+ return false;+ }+ rootSpan = span;+ rootContext = trace.setSpan(context.active(), span);+ active = true;+ return true;+ } catch (err) {+ getLogger('startup-trace').warn(+ { err: err instanceof Error ? err.message : String(err) },+ 'OTel root init failed in main — degrading to waterfall-log-only (Plan B)',+ );+ rootSpan = undefined;+ rootContext = undefined;+ active = false;+ return false;+ }+}++export function isStartupTraceActive(): boolean {+ return active;+}++export function injectTraceparent(): string | undefined {+ if (!active || !rootContext) return undefined;+ try {+ const carrier: Record<string, string> = {};+ propagation.inject(rootContext, carrier);+ return carrier.traceparent;+ } catch {+ return undefined;+ }+}++export function childSpan(+ name: string,+ attributes: Record<string, number | boolean>,+ startMs: number,+ endMs: number,+): void {+ if (!active || !rootContext) return;+ try {+ const span = getTracer().startSpan(name, { startTime: startMs }, rootContext);+ span.setAttributes(attributes);+ span.end(endMs);+ } catch {}+}++export function endRoot(endMs: number = Date.now()): void {+ if (!rootSpan) return;+ try {+ rootSpan.end(endMs);+ } catch {}+ rootSpan = undefined;+ rootContext = undefined;+ active = false;+}++export function __resetStartupTraceForTest(): void {+ rootSpan = undefined;+ rootContext = undefined;+ active = false;+}diff --git a/packages/desktop/src/main/startup-waterfall.test.ts b/packages/desktop/src/main/startup-waterfall.test.tsnew file mode 100644index 000000000..1843c755c--- /dev/null+++ b/packages/desktop/src/main/startup-waterfall.test.ts@@ -0,0 +1,177 @@+import { describe, expect, test } from 'bun:test';+import {+ type RendererMarks,+ type ServerBootTimings,+ StartupWaterfall,+ type WaterfallLogger,+ type WaterfallPayload,+} from './startup-waterfall.ts';++interface CaptureLogger extends WaterfallLogger {+ calls: Array<[Record<string, unknown>, string]>;+}++function captureLogger(): CaptureLogger {+ const calls: Array<[Record<string, unknown>, string]> = [];+ return {+ calls,+ info(obj, msg) {+ calls.push([obj, msg]);+ },+ };+}++const SERVER_BOOT: ServerBootTimings = {+ startedAt: '2026-06-30T00:00:00.000Z',+ httpListenMs: 5,+ seedWalkMs: 40,+ indexesMs: 60,+ readyMs: 120,+ fileCount: 17,+};++const RENDERER_MARKS: RendererMarks = {+ pageListReadyMs: 1000,+ firstContentMs: 1200,+};++describe('StartupWaterfall', () => {+ test('computes phase deltas from sequential marks', () => {+ const w = new StartupWaterfall({ otelEnabled: true });+ w.mark('appReady', 100);+ w.mark('bootstrapDone', 150);+ w.mark('serverSpawned', 200);+ w.mark('serverLockReady', 400);+ w.mark('windowCreated', 420);+ w.mark('loadUrlResolved', 480);+ w.mark('windowShown', 520);++ const p = w.buildPayload();+ expect(p.appReadyToBootstrapMs).toBe(50);+ expect(p.bootstrapToSpawnMs).toBe(50);+ expect(p.spawnToLockReadyMs).toBe(200);+ expect(p.lockReadyToWindowMs).toBe(20);+ expect(p.windowToLoadUrlMs).toBe(60);+ expect(p.loadUrlToShownMs).toBe(40);+ expect(p.totalLaunchToShownMs).toBe(420);+ expect(p.otelEnabled).toBe(true);+ });++ test('first-write-wins per phase (later marks do not overwrite)', () => {+ const w = new StartupWaterfall({ otelEnabled: false });+ w.mark('appReady', 100);+ w.mark('appReady', 999);+ w.mark('windowShown', 200);+ expect(w.buildPayload().totalLaunchToShownMs).toBe(100);+ });++ test('missing-bound deltas are omitted, not zero', () => {+ const w = new StartupWaterfall({ otelEnabled: false });+ w.mark('appReady', 100);+ w.mark('windowShown', 300);+ const p = w.buildPayload();+ expect(p.appReadyToBootstrapMs).toBeUndefined();+ expect(p.totalLaunchToShownMs).toBe(200);+ });++ test('passes through server boot timings + spawn→server-start vs serverSpawned', () => {+ const w = new StartupWaterfall({ otelEnabled: false });+ w.mark('appReady', 0);+ const serverStartedAtMs = Date.parse(SERVER_BOOT.startedAt);+ w.mark('serverSpawned', serverStartedAtMs - 30);+ w.ingestServerBoot(SERVER_BOOT);+ w.mark('windowShown', 50);+ const p = w.buildPayload();+ expect(p.serverHttpListenMs).toBe(5);+ expect(p.serverSeedWalkMs).toBe(40);+ expect(p.serverIndexesMs).toBe(60);+ expect(p.serverReadyMs).toBe(120);+ expect(p.serverFileCount).toBe(17);+ expect(p.spawnToServerStartMs).toBe(30);+ });++ test('mainPhaseIntervals returns present, non-decreasing phases as named spans', () => {+ const w = new StartupWaterfall({ otelEnabled: true });+ w.mark('appReady', 100);+ w.mark('bootstrapDone', 150);+ w.mark('serverLockReady', 400);+ w.mark('windowCreated', 420);+ w.mark('loadUrlResolved', 480);+ w.mark('windowShown', 520);++ const intervals = w.mainPhaseIntervals();+ const byName = new Map(intervals.map((i) => [i.name, i]));+ expect(byName.get('ok.startup.bootstrap')).toEqual({+ name: 'ok.startup.bootstrap',+ startMs: 100,+ endMs: 150,+ });+ expect(byName.has('ok.startup.spawn')).toBe(false);+ expect(byName.has('ok.startup.lock-wait')).toBe(false);+ expect(byName.get('ok.startup.window-create')).toEqual({+ name: 'ok.startup.window-create',+ startMs: 400,+ endMs: 420,+ });+ expect(byName.get('ok.startup.show')).toEqual({+ name: 'ok.startup.show',+ startMs: 480,+ endMs: 520,+ });+ });++ test('renderer marks are reported relative to appReady', () => {+ const w = new StartupWaterfall({ otelEnabled: false });+ w.mark('appReady', 800);+ w.ingestRendererMarks(RENDERER_MARKS);+ w.mark('windowShown', 1300);+ const p = w.buildPayload();+ expect(p.rendererPageListMs).toBe(200); // 1000 - 800+ expect(p.rendererFirstContentMs).toBe(400); // 1200 - 800+ expect(p.totalLaunchToFirstContentMs).toBe(400);+ });++ test('emit fires once and only after windowShown', () => {+ const w = new StartupWaterfall({ otelEnabled: false });+ const logger = captureLogger();+ expect(w.emit(logger)).toBeUndefined();+ expect(logger.calls.length).toBe(0);++ w.mark('appReady', 0);+ w.mark('windowShown', 100);+ const payload = w.emit(logger);+ expect(payload).toBeDefined();+ expect(logger.calls.length).toBe(1);+ expect(logger.calls[0][1]).toBe('desktop.startup-timeline');++ expect(w.emit(logger)).toBeUndefined();+ expect(logger.calls.length).toBe(1);+ });++ test('readyToEmit requires window-shown + both best-effort inputs', () => {+ const w = new StartupWaterfall({ otelEnabled: false });+ w.mark('appReady', 0);+ w.mark('windowShown', 100);+ expect(w.canEmit).toBe(true);+ expect(w.readyToEmit).toBe(false); // no server boot / renderer marks yet+ w.ingestServerBoot(SERVER_BOOT);+ expect(w.readyToEmit).toBe(false); // still missing renderer marks+ w.ingestRendererMarks(RENDERER_MARKS);+ expect(w.readyToEmit).toBe(true);+ });++ test('canEmit flips to false once emitted', () => {+ const w = new StartupWaterfall({ otelEnabled: false });+ w.mark('windowShown', 100);+ expect(w.canEmit).toBe(true);+ w.emit(captureLogger());+ expect(w.canEmit).toBe(false);+ });++ test('otelEnabled is carried onto the payload', () => {+ const w = new StartupWaterfall({ otelEnabled: false });+ w.mark('windowShown', 100);+ const p: WaterfallPayload | undefined = w.emit(captureLogger());+ expect(p?.otelEnabled).toBe(false);+ });+});diff --git a/packages/desktop/src/main/startup-waterfall.ts b/packages/desktop/src/main/startup-waterfall.tsnew file mode 100644index 000000000..f787b67fb--- /dev/null+++ b/packages/desktop/src/main/startup-waterfall.ts@@ -0,0 +1,169 @@+export type WaterfallPhase =+ | 'appReady'+ | 'bootstrapDone'+ | 'serverSpawned'+ | 'serverLockReady'+ | 'windowCreated'+ | 'loadUrlResolved'+ | 'windowShown';++export interface ServerBootTimings {+ startedAt: string;+ httpListenMs?: number;+ seedWalkMs?: number;+ indexesMs?: number;+ readyMs?: number;+ fileCount?: number;+}++export interface RendererMarks {+ pageListReadyMs: number;+ firstContentMs: number;+}++export interface WaterfallLogger {+ info(payload: Record<string, unknown>, message: string): void;+}++export interface WaterfallPayload {+ appReadyToBootstrapMs?: number;+ bootstrapToSpawnMs?: number;+ spawnToLockReadyMs?: number;+ lockReadyToWindowMs?: number;+ windowToLoadUrlMs?: number;+ loadUrlToShownMs?: number;+ serverHttpListenMs?: number;+ serverSeedWalkMs?: number;+ serverIndexesMs?: number;+ serverReadyMs?: number;+ serverFileCount?: number;+ rendererPageListMs?: number;+ rendererFirstContentMs?: number;+ totalLaunchToShownMs?: number;+ totalLaunchToFirstContentMs?: number;+ spawnToServerStartMs?: number;+ otelEnabled: boolean;+}++export interface StartupWaterfallOptions {+ otelEnabled: boolean;+ flushDeadlineMs?: number;+}++function round(n: number): number {+ return Math.round(n);+}++function delta(a: number | undefined, b: number | undefined): number | undefined {+ if (a === undefined || b === undefined) return undefined;+ return round(b - a);+}++const PHASE_SPANS: ReadonlyArray<{ name: string; from: WaterfallPhase; to: WaterfallPhase }> = [+ { name: 'ok.startup.bootstrap', from: 'appReady', to: 'bootstrapDone' },+ { name: 'ok.startup.spawn', from: 'bootstrapDone', to: 'serverSpawned' },+ { name: 'ok.startup.lock-wait', from: 'serverSpawned', to: 'serverLockReady' },+ { name: 'ok.startup.window-create', from: 'serverLockReady', to: 'windowCreated' },+ { name: 'ok.startup.load-url', from: 'windowCreated', to: 'loadUrlResolved' },+ { name: 'ok.startup.show', from: 'loadUrlResolved', to: 'windowShown' },+];++export class StartupWaterfall {+ private readonly marks = new Map<WaterfallPhase, number>();+ private serverBoot: ServerBootTimings | undefined;+ private rendererMarks: RendererMarks | undefined;+ private emitted = false;+ otelEnabled: boolean;+ readonly flushDeadlineMs: number;++ constructor(opts: StartupWaterfallOptions) {+ this.otelEnabled = opts.otelEnabled;+ this.flushDeadlineMs = opts.flushDeadlineMs ?? 1500;+ }++ mark(phase: WaterfallPhase, atMs: number = Date.now()): void {+ if (!this.marks.has(phase)) this.marks.set(phase, atMs);+ }++ ingestServerBoot(boot: ServerBootTimings | undefined): void {+ if (boot) this.serverBoot = boot;+ }++ ingestRendererMarks(marks: RendererMarks): void {+ this.rendererMarks = marks;+ }++ private hasBestEffortInputs(): boolean {+ return this.serverBoot !== undefined && this.rendererMarks !== undefined;+ }++ get canEmit(): boolean {+ return !this.emitted && this.marks.has('windowShown');+ }++ get readyToEmit(): boolean {+ return this.canEmit && this.hasBestEffortInputs();+ }++ buildPayload(): WaterfallPayload {+ const appReady = this.marks.get('appReady');+ const bootstrapDone = this.marks.get('bootstrapDone');+ const serverSpawned = this.marks.get('serverSpawned');+ const serverLockReady = this.marks.get('serverLockReady');+ const windowCreated = this.marks.get('windowCreated');+ const loadUrlResolved = this.marks.get('loadUrlResolved');+ const windowShown = this.marks.get('windowShown');++ const payload: WaterfallPayload = {+ appReadyToBootstrapMs: delta(appReady, bootstrapDone),+ bootstrapToSpawnMs: delta(bootstrapDone, serverSpawned),+ spawnToLockReadyMs: delta(serverSpawned, serverLockReady),+ lockReadyToWindowMs: delta(serverLockReady, windowCreated),+ windowToLoadUrlMs: delta(windowCreated, loadUrlResolved),+ loadUrlToShownMs: delta(loadUrlResolved, windowShown),+ totalLaunchToShownMs: delta(appReady, windowShown),+ otelEnabled: this.otelEnabled,+ };++ if (this.serverBoot) {+ payload.serverHttpListenMs = this.serverBoot.httpListenMs;+ payload.serverSeedWalkMs = this.serverBoot.seedWalkMs;+ payload.serverIndexesMs = this.serverBoot.indexesMs;+ payload.serverReadyMs = this.serverBoot.readyMs;+ payload.serverFileCount = this.serverBoot.fileCount;+ const serverStartedAtMs = Date.parse(this.serverBoot.startedAt);+ if (!Number.isNaN(serverStartedAtMs) && serverSpawned !== undefined) {+ payload.spawnToServerStartMs = round(serverStartedAtMs - serverSpawned);+ }+ }++ if (this.rendererMarks && appReady !== undefined) {+ payload.rendererPageListMs = round(this.rendererMarks.pageListReadyMs - appReady);+ payload.rendererFirstContentMs = round(this.rendererMarks.firstContentMs - appReady);+ payload.totalLaunchToFirstContentMs = round(this.rendererMarks.firstContentMs - appReady);+ }++ return payload;+ }++ mainPhaseIntervals(): Array<{ name: string; startMs: number; endMs: number }> {+ const out: Array<{ name: string; startMs: number; endMs: number }> = [];+ for (const { name, from, to } of PHASE_SPANS) {+ const startMs = this.marks.get(from);+ const endMs = this.marks.get(to);+ if (startMs !== undefined && endMs !== undefined && endMs >= startMs) {+ out.push({ name, startMs, endMs });+ }+ }+ return out;+ }++ emit(logger: WaterfallLogger): WaterfallPayload | undefined {+ if (this.emitted) return undefined;+ if (!this.marks.has('windowShown')) return undefined;+ this.emitted = true;+ const payload = this.buildPayload();+ logger.info(payload as unknown as Record<string, unknown>, 'desktop.startup-timeline');+ return payload;+ }+}diff --git a/packages/desktop/src/main/utility-fork-env.test.ts b/packages/desktop/src/main/utility-fork-env.test.tsindex ab8f68cfb..d5aca366d 100644--- a/packages/desktop/src/main/utility-fork-env.test.ts+++ b/packages/desktop/src/main/utility-fork-env.test.ts@@ -23,4 +23,39 @@ describe('buildUtilityForkEnv', () => {const env = buildUtilityForkEnv();expect(env.OK_ELECTRON_PROTOCOL_HOST).toBe('1');});++ test('sets OK_STARTUP_TRACEPARENT when provided', () => {+ const traceparent = '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01';+ const env = buildUtilityForkEnv({}, { startupTraceparent: traceparent });+ expect(env.OK_STARTUP_TRACEPARENT).toBe(traceparent);+ });++ test('omits OK_STARTUP_TRACEPARENT when not provided (no lingering value)', () => {+ const env = buildUtilityForkEnv({});+ expect(env.OK_STARTUP_TRACEPARENT).toBeUndefined();+ const env2 = buildUtilityForkEnv({}, {});+ expect(env2.OK_STARTUP_TRACEPARENT).toBeUndefined();+ });++ test('passes OTEL_EXPORTER_OTLP_ENDPOINT through when supplied', () => {+ const env = buildUtilityForkEnv({}, { otlpEndpoint: 'http://localhost:14318' });+ expect(env.OTEL_EXPORTER_OTLP_ENDPOINT).toBe('http://localhost:14318');+ });++ test('leaves an inherited OTEL_EXPORTER_OTLP_ENDPOINT intact when not overridden', () => {+ const env = buildUtilityForkEnv({ OTEL_EXPORTER_OTLP_ENDPOINT: 'http://collector:4318' });+ expect(env.OTEL_EXPORTER_OTLP_ENDPOINT).toBe('http://collector:4318');+ });++ test('startupTraceparent + otlpEndpoint coexist with the protocol-host marker', () => {+ const env = buildUtilityForkEnv(+ { PATH: '/usr/bin' },+ { startupTraceparent: 'tp', otlpEndpoint: 'http://x:4318' },+ );+ expect(env.OK_ELECTRON_PROTOCOL_HOST).toBe('1');+ expect(env.OK_LOCK_KIND).toBe('interactive');+ expect(env.OK_STARTUP_TRACEPARENT).toBe('tp');+ expect(env.OTEL_EXPORTER_OTLP_ENDPOINT).toBe('http://x:4318');+ expect(env.PATH).toBe('/usr/bin');+ });});diff --git a/packages/desktop/src/main/utility-fork-env.ts b/packages/desktop/src/main/utility-fork-env.tsindex b714437f8..3a6f16a53 100644--- a/packages/desktop/src/main/utility-fork-env.ts+++ b/packages/desktop/src/main/utility-fork-env.ts@@ -1,7 +1,22 @@-export function buildUtilityForkEnv(parentEnv: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {- return {+export interface UtilityForkEnvOptions {+ startupTraceparent?: string;+ otlpEndpoint?: string;+}++export function buildUtilityForkEnv(+ parentEnv: NodeJS.ProcessEnv = process.env,+ opts: UtilityForkEnvOptions = {},+): NodeJS.ProcessEnv {+ const env: NodeJS.ProcessEnv = {...parentEnv,OK_ELECTRON_PROTOCOL_HOST: '1',OK_LOCK_KIND: 'interactive',};+ if (opts.startupTraceparent !== undefined) {+ env.OK_STARTUP_TRACEPARENT = opts.startupTraceparent;+ }+ if (opts.otlpEndpoint !== undefined) {+ env.OTEL_EXPORTER_OTLP_ENDPOINT = opts.otlpEndpoint;+ }+ return env;}diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.tsindex 994e6166a..3951d34e6 100644--- a/packages/desktop/src/main/window-manager.ts+++ b/packages/desktop/src/main/window-manager.ts@@ -160,6 +160,12 @@ export interface WindowManagerDeps {};onUtilityMessage?(msg: unknown): void;onUtilityExit?(utility: UtilityProcessLike): void;+ startup?: {+ traceparent?: string;+ markServerLockReady?(info?: { startedAt?: string; apiOrigin?: string }): void;+ markWindowCreated?(): void;+ markLoadUrlResolved?(): void;+ };}export function signalDetachedServerStop(@@ -596,6 +602,10 @@ export class WindowManager {{ event: 'desktop-server-spawned-detached', pid: handle.pid, port: lock.port, lockDir },'[window-manager] detached server ready',);+ this.deps.startup?.markServerLockReady?.({+ startedAt: lock.startedAt,+ apiOrigin: `http://localhost:${lock.port}`,+ });return this.attachToExistingServer({projectPath,canonicalKey,@@ -681,6 +691,7 @@ export class WindowManager {});const { port, apiOrigin } = await ready;+ this.deps.startup?.markServerLockReady?.({ apiOrigin });if (this.deps.onUtilityMessage) {const onMessage = this.deps.onUtilityMessage;@@ -713,11 +724,15 @@ export class WindowManager {`--ok-project-name=${projectName}`,`--ok-mode=editor`,`--ok-app-version=${this.deps.appVersion}`,+ ...(this.deps.startup?.traceparent !== undefined+ ? [`--ok-startup-traceparent=${this.deps.startup.traceparent}`]+ : []),];const window = this.deps.createWindow({additionalArguments,title: formatEditorTitle(projectName),});+ this.deps.startup?.markWindowCreated?.();if (opts.pendingDeepLinkTarget) {const doc = opts.pendingDeepLinkTarget.path;@@ -759,6 +774,7 @@ export class WindowManager {} else {await window.loadFile(this.deps.rendererEntryPath);}+ this.deps.startup?.markLoadUrlResolved?.();window.on('closed', () => {disposeShowGate();@@ -1109,6 +1125,8 @@ export class WindowManager {'attaching to existing OpenKnowledge server',);+ this.deps.startup?.markServerLockReady?.({ startedAt: lock.startedAt, apiOrigin });+const window = this.deps.createWindow({additionalArguments: [`--ok-collab-url=ws://localhost:${port}/collab`,@@ -1117,9 +1135,13 @@ export class WindowManager {`--ok-project-name=${projectName}`,`--ok-mode=editor`,`--ok-app-version=${this.deps.appVersion}`,+ ...(this.deps.startup?.traceparent !== undefined+ ? [`--ok-startup-traceparent=${this.deps.startup.traceparent}`]+ : []),],title: formatEditorTitle(projectName),});+ this.deps.startup?.markWindowCreated?.();if (pendingDeepLinkTarget) {const doc = pendingDeepLinkTarget.path;@@ -1183,6 +1205,7 @@ export class WindowManager {} else {await window.loadFile(this.deps.rendererEntryPath);}+ this.deps.startup?.markLoadUrlResolved?.();if (this.deps.createKeepalive) {const existingKeepalive = this.keepalives.get(canonicalKey);diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.tsindex 894211e91..46fcd335e 100644--- a/packages/desktop/src/preload/index.ts+++ b/packages/desktop/src/preload/index.ts@@ -157,6 +157,7 @@ function readConfigFromArgv(): OkDesktopConfig {const singleFile = parseArg('single-file') === '1';const initialDoc = parseArg('initial-doc') ?? null;const e2eSmoke = parseArg('e2e-smoke') === '1';+ const startupTraceparent = parseArg('startup-traceparent');return Object.freeze({collabUrl,apiOrigin,@@ -166,6 +167,7 @@ function readConfigFromArgv(): OkDesktopConfig {e2eSmoke,singleFile,initialDoc,+ ...(startupTraceparent !== undefined ? { startupTraceparent } : {}),});}@@ -482,6 +484,12 @@ const bridge: OkDesktopBridge = {},},+ startup: {+ reportMarks: (marks: { pageListReadyMs: number; firstContentMs: number }) => {+ invoke('ok:startup:renderer-marks', marks).catch(() => {});+ },+ },+sidebar: {expandAll(cb: () => void) {const listener = (_event: IpcRendererEvent) => cb();diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.tsindex e7c4a3f72..f28bdbabe 100644--- a/packages/desktop/src/shared/bridge-contract.ts+++ b/packages/desktop/src/shared/bridge-contract.ts@@ -81,6 +81,7 @@ export interface OkDesktopConfig {readonly e2eSmoke: boolean;readonly singleFile: boolean;readonly initialDoc: string | null;+ readonly startupTraceparent?: string;}export type OkMenuAction =@@ -724,6 +725,10 @@ export interface OkDesktopBridge {notifyViewMenuStateChanged(state: Partial<OkEditorViewMenuStateSnapshot>): void;};+ startup: {+ reportMarks(marks: { pageListReadyMs: number; firstContentMs: number }): void;+ };+sidebar: {expandAll(cb: () => void): OkUnsubscribe;collapseAll(cb: () => void): OkUnsubscribe;diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.tsindex e8d1b7f53..cfba65cfd 100644--- a/packages/desktop/src/shared/ipc-channels.ts+++ b/packages/desktop/src/shared/ipc-channels.ts@@ -412,6 +412,10 @@ export interface RequestChannels {args: [opts?: { reducedTransparency?: boolean }];result: undefined;};+ 'ok:startup:renderer-marks': {+ args: [marks: { pageListReadyMs: number; firstContentMs: number }];+ result: undefined;+ };'ok:debug:keyring-smoke': { args: []; result: KeyringSmokeResult };'ok:seed:plan': { args: [options?: SeedPlanOptions]; result: SeedPlanResult };'ok:seed:apply': {diff --git a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.tsindex 63579edb0..3a5bb7feb 100644--- a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts+++ b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts@@ -5,7 +5,7 @@ import { join } from 'node:path';const SRC_PATH = join(__dirname, '..', '..', 'src', 'shared', 'ipc-channels.ts');const CHANNELS_SRC = readFileSync(SRC_PATH, 'utf-8');-const REQUEST_CHANNEL_CAP = 74;+const REQUEST_CHANNEL_CAP = 75;function extractInterfaceBody(src: string, interfaceName: string): string {const re = new RegExp(`(^|\\n)export\\s+interface\\s+${interfaceName}\\s*\\{`);diff --git a/packages/desktop/tests/main/show-gate.test.ts b/packages/desktop/tests/main/show-gate.test.tsindex 76333ba72..783f0b718 100644--- a/packages/desktop/tests/main/show-gate.test.ts+++ b/packages/desktop/tests/main/show-gate.test.ts@@ -102,6 +102,40 @@ describe('createShowGateRegistry — dual-signal show contract', () => {expect(win.show).toHaveBeenCalledTimes(1);});+ test('onShown fires once with the window kind after a successful show', () => {+ const onShown = mock((_kind: 'editor' | 'navigator') => {});+ const registry = createShowGateRegistry({+ log: { warn: () => {} },+ setTimeout: (cb, ms) => ({ cb, ms }),+ clearTimeout: () => {},+ onShown,+ });+ const win = makeWindow();+ registry.register(win, { kind: 'editor' });+ win.fireReadyToShow();+ expect(onShown).not.toHaveBeenCalled();+ registry.fireThemeApplied(win);+ expect(win.show).toHaveBeenCalledTimes(1);+ expect(onShown).toHaveBeenCalledTimes(1);+ expect(onShown).toHaveBeenCalledWith('editor');+ });++ test('a throwing onShown is isolated and does not break show', () => {+ const registry = createShowGateRegistry({+ log: { warn: () => {} },+ setTimeout: (cb, ms) => ({ cb, ms }),+ clearTimeout: () => {},+ onShown: () => {+ throw new Error('boom');+ },+ });+ const win = makeWindow();+ registry.register(win, { kind: 'editor' });+ win.fireReadyToShow();+ expect(() => registry.fireThemeApplied(win)).not.toThrow();+ expect(win.show).toHaveBeenCalledTimes(1);+ });+test('both signals (theme-applied first) → show called exactly once', () => {const win = makeWindow();env.registry.register(win);diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex ede6e5e22..19d2d6db2 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -405,6 +405,7 @@ import {type GraphNode as IndexedGraphNode,isOrphanMode,} from './backlink-index.ts';+import { getBootTimings } from './boot-timings.ts';import { composeAndWriteRawBody, replaceRawBody } from './bridge-intake.ts';import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';import type { ResolveStrategy } from './conflict-storage.ts';@@ -6323,6 +6324,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {}const currentBranch = getActiveBranch();const currentDiskAckSVs = getDiskAckSVs?.();+ const boot = getBootTimings();successResponse(res,200,@@ -6331,6 +6333,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {serverInstanceId,currentBranch,...(currentDiskAckSVs !== undefined ? { currentDiskAckSVs } : {}),+ ...(boot !== undefined ? { boot } : {}),},{handler: 'server-info',diff --git a/packages/server/src/boot-timings.test.ts b/packages/server/src/boot-timings.test.tsnew file mode 100644index 000000000..bb521b614--- /dev/null+++ b/packages/server/src/boot-timings.test.ts@@ -0,0 +1,86 @@+import { afterEach, describe, expect, test } from 'bun:test';+import {+ bootElapsedMs,+ getBootTimings,+ recordBootPhase,+ resetBootTimingsForTest,+ setBootField,+ startBootTimings,+} from './boot-timings.ts';++afterEach(() => {+ resetBootTimingsForTest();+});++describe('boot-timings', () => {+ test('returns undefined before startBootTimings runs', () => {+ resetBootTimingsForTest();+ expect(getBootTimings()).toBeUndefined();+ expect(bootElapsedMs()).toBeUndefined();+ });++ test('startBootTimings stamps startedAt and arms the monotonic clock', () => {+ startBootTimings('2026-06-30T00:00:00.000Z');+ const t = getBootTimings();+ expect(t).toBeDefined();+ expect(t?.startedAt).toBe('2026-06-30T00:00:00.000Z');+ expect(t?.httpListenMs).toBeUndefined();+ expect(t?.readyMs).toBeUndefined();+ expect(t?.fileCount).toBeUndefined();+ expect(typeof bootElapsedMs()).toBe('number');+ expect(bootElapsedMs()).toBeGreaterThanOrEqual(0);+ });++ test('defaults startedAt to an ISO string when omitted', () => {+ startBootTimings();+ const startedAt = getBootTimings()?.startedAt;+ expect(startedAt).toBeDefined();+ expect(Number.isNaN(Date.parse(startedAt as string))).toBe(false);+ });++ test('recordBootPhase accumulates duration fields', () => {+ startBootTimings('2026-06-30T00:00:00.000Z');+ recordBootPhase('httpListenMs', 12);+ recordBootPhase('seedWalkMs', 34);+ recordBootPhase('indexesMs', 56);+ recordBootPhase('readyMs', 78);+ const t = getBootTimings();+ expect(t).toMatchObject({+ startedAt: '2026-06-30T00:00:00.000Z',+ httpListenMs: 12,+ seedWalkMs: 34,+ indexesMs: 56,+ readyMs: 78,+ });+ });++ test('setBootField records the bounded file count', () => {+ startBootTimings('2026-06-30T00:00:00.000Z');+ setBootField('fileCount', 42);+ expect(getBootTimings()?.fileCount).toBe(42);+ });++ test('recordBootPhase / setBootField are no-ops before startBootTimings', () => {+ resetBootTimingsForTest();+ recordBootPhase('httpListenMs', 99);+ setBootField('fileCount', 99);+ expect(getBootTimings()).toBeUndefined();+ });++ test('resetBootTimingsForTest clears the singleton and disarms the clock', () => {+ startBootTimings('2026-06-30T00:00:00.000Z');+ recordBootPhase('readyMs', 5);+ resetBootTimingsForTest();+ expect(getBootTimings()).toBeUndefined();+ expect(bootElapsedMs()).toBeUndefined();+ });++ test('a fresh startBootTimings drops prior phase values', () => {+ startBootTimings('2026-06-30T00:00:00.000Z');+ recordBootPhase('httpListenMs', 12);+ startBootTimings('2026-06-30T01:00:00.000Z');+ const t = getBootTimings();+ expect(t?.startedAt).toBe('2026-06-30T01:00:00.000Z');+ expect(t?.httpListenMs).toBeUndefined();+ });+});diff --git a/packages/server/src/boot-timings.ts b/packages/server/src/boot-timings.tsnew file mode 100644index 000000000..a539ff5e5--- /dev/null+++ b/packages/server/src/boot-timings.ts@@ -0,0 +1,43 @@+export interface BootTimings {+ startedAt: string;+ httpListenMs?: number;+ seedWalkMs?: number;+ indexesMs?: number;+ readyMs?: number;+ fileCount?: number;+}++let current: BootTimings | undefined;+let bootStartMono: number | undefined;++export function startBootTimings(startedAt: string = new Date().toISOString()): void {+ current = { startedAt };+ bootStartMono = performance.now();+}++export function bootElapsedMs(): number | undefined {+ if (bootStartMono === undefined) return undefined;+ return Math.round(performance.now() - bootStartMono);+}++export function recordBootPhase(+ name: Exclude<keyof BootTimings, 'startedAt' | 'fileCount'>,+ ms: number,+): void {+ if (!current) return;+ current[name] = ms;+}++export function setBootField(name: 'fileCount', value: number): void {+ if (!current) return;+ current[name] = value;+}++export function getBootTimings(): BootTimings | undefined {+ return current;+}++export function resetBootTimingsForTest(): void {+ current = undefined;+ bootStartMono = undefined;+}diff --git a/packages/server/src/boot.test.ts b/packages/server/src/boot.test.tsindex 8632d9f05..b353a900c 100644--- a/packages/server/src/boot.test.ts+++ b/packages/server/src/boot.test.ts@@ -9,13 +9,16 @@ import { hostname, tmpdir } from 'node:os';import { resolve } from 'node:path';import { promisify } from 'node:util';import { emitToleranceFire, OK_DIR } from '@inkeep/open-knowledge-core';-import { context, metrics, trace } from '@opentelemetry/api';+import { context, metrics, propagation, trace } from '@opentelemetry/api';+import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';+import { W3CTraceContextPropagator } from '@opentelemetry/core';import {BasicTracerProvider,InMemorySpanExporter,SimpleSpanProcessor,} from '@opentelemetry/sdk-trace-base';import { bootServer } from './boot.ts';+import { getBootTimings } from './boot-timings.ts';import { ConfigSchema } from './config/schema.ts';import { parseKeepaliveConnectionId } from './mcp-mount.ts';import { shutdownTelemetry } from './telemetry.ts';@@ -784,6 +787,103 @@ describe('bootServer — ok.boot OTel span attributes', () => {bootSpans[1]?.attributes['ok.worktree.gitdir'],);});++ test('OK_STARTUP_TRACEPARENT (valid): ok.boot joins the desktop-main launch trace', async () => {+ const parentTraceId = '0af7651916cd43dd8448eb211c80319c';+ const prev = process.env.OK_STARTUP_TRACEPARENT;+ process.env.OK_STARTUP_TRACEPARENT = `00-${parentTraceId}-b7ad6b7169203331-01`;+ context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable());+ propagation.setGlobalPropagator(new W3CTraceContextPropagator());+ const contentDir = mkdtempSync(resolve(tmpDir, 'traceparent-valid-'));+ await execFileAsync('git', ['init', '--initial-branch=main', contentDir]);+ seedOkScaffold(contentDir);++ let booted: Awaited<ReturnType<typeof bootServer>> | null = null;+ try {+ booted = await bootServer({+ host: '127.0.0.1',+ config: TEST_CONFIG,+ contentDir,+ port: 0,+ quiet: true,+ gitEnabled: false,+ idleShutdownMs: null,+ attachUiSibling: false,+ });+ const bootSpan = (exporter?.getFinishedSpans() ?? []).find((s) => s.name === 'ok.boot');+ expect(bootSpan).toBeDefined();+ expect(bootSpan?.spanContext().traceId).toBe(parentTraceId);+ } finally {+ if (booted) await booted.destroy();+ if (prev === undefined) delete process.env.OK_STARTUP_TRACEPARENT;+ else process.env.OK_STARTUP_TRACEPARENT = prev;+ }+ });++ test('OK_STARTUP_TRACEPARENT (malformed): boot still completes; ok.boot is a fresh root', async () => {+ const prev = process.env.OK_STARTUP_TRACEPARENT;+ process.env.OK_STARTUP_TRACEPARENT = 'not-a-valid-traceparent';+ const contentDir = mkdtempSync(resolve(tmpDir, 'traceparent-malformed-'));+ await execFileAsync('git', ['init', '--initial-branch=main', contentDir]);+ seedOkScaffold(contentDir);++ let booted: Awaited<ReturnType<typeof bootServer>> | null = null;+ try {+ booted = await bootServer({+ host: '127.0.0.1',+ config: TEST_CONFIG,+ contentDir,+ port: 0,+ quiet: true,+ gitEnabled: false,+ idleShutdownMs: null,+ attachUiSibling: false,+ });+ expect(booted.port).toBeGreaterThan(0);+ const bootSpan = (exporter?.getFinishedSpans() ?? []).find((s) => s.name === 'ok.boot');+ expect(bootSpan).toBeDefined();+ expect(bootSpan?.spanContext().traceId).toMatch(/^[0-9a-f]{32}$/);+ } finally {+ if (booted) await booted.destroy();+ if (prev === undefined) delete process.env.OK_STARTUP_TRACEPARENT;+ else process.env.OK_STARTUP_TRACEPARENT = prev;+ }+ });+});++describe('bootServer — boot timings recorded end-to-end', () => {+ test('a full boot populates httpListen / seedWalk / indexes / ready / fileCount', async () => {+ const projectDir = mkdtempSync(resolve(tmpDir, 'boot-timings-e2e-'));+ await execFileAsync('git', ['init', '--initial-branch=main', projectDir]);+ seedOkScaffold(projectDir);+ writeFileSync(resolve(projectDir, 'note.md'), '# note\n', 'utf-8');++ const booted = await bootServer({+ host: '127.0.0.1',+ config: TEST_CONFIG,+ projectDir,+ contentDir: projectDir,+ port: 0,+ quiet: true,+ gitEnabled: false,+ idleShutdownMs: null,+ attachUiSibling: false,+ });+ try {+ await booted.ready;+ const timings = getBootTimings();+ expect(timings).toBeDefined();+ expect(typeof timings?.startedAt).toBe('string');+ expect(typeof timings?.httpListenMs).toBe('number');+ expect(typeof timings?.seedWalkMs).toBe('number');+ expect(typeof timings?.indexesMs).toBe('number');+ expect(typeof timings?.readyMs).toBe('number');+ expect(typeof timings?.fileCount).toBe('number');+ expect(timings?.fileCount).toBeGreaterThanOrEqual(1);+ } finally {+ await booted.destroy();+ }+ });});describe('parseKeepaliveConnectionId', () => {diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex 21525c91b..158a05e76 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -12,9 +12,11 @@ import {resolveGitDir,resolveGitDirDetailed,} from '@inkeep/open-knowledge-core/shadow-repo-layout';+import { context, propagation } from '@opentelemetry/api';import { simpleGit } from 'simple-git';import sirv from 'sirv';import { createAssetServeMiddleware } from './asset-serve-middleware.ts';+import { bootElapsedMs, recordBootPhase, startBootTimings } from './boot-timings.ts';import type { Config } from './config/schema.ts';import { ConflictStore } from './conflict-storage.ts';import { stripDocExtension } from './doc-extensions.ts';@@ -158,6 +160,8 @@ export interface BootedServer {const PINO_REDACT_MAX_DEPTH = 5;export async function bootServer(opts: BootServerOptions): Promise<BootedServer> {+ startBootTimings();+const sinkProjectDir = opts.projectDir ?? opts.contentDir;const localSinkConfig = resolveLocalSinkConfig({projectDir: sinkProjectDir,@@ -187,7 +191,21 @@ export async function bootServer(opts: BootServerOptions): Promise<BootedServer>spanAttributes['ok.worktree.gitdir'] = normalizeFsPath(worktreeGitdir);}- return withSpan('ok.boot', { attributes: spanAttributes }, async () => bootServerInner(opts));+ const startupTraceparent = process.env.OK_STARTUP_TRACEPARENT;+ const bootSpan = () =>+ withSpan('ok.boot', { attributes: spanAttributes }, async () => bootServerInner(opts));+ if (startupTraceparent) {+ try {+ const parentCtx = propagation.extract(context.active(), { traceparent: startupTraceparent });+ return context.with(parentCtx, bootSpan);+ } catch (err) {+ getLogger('boot').warn(+ { err: err instanceof Error ? err.message : String(err) },+ 'ok.boot trace-join failed — starting unparented boot',+ );+ }+ }+ return bootSpan();}async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {@@ -430,6 +448,9 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {throw err;}+ const listenMs = bootElapsedMs();+ if (listenMs !== undefined) recordBootPhase('httpListenMs', listenMs);+const addr = httpServer.address();const realPort = typeof addr === 'object' && addr !== null ? addr.port : (opts.port ?? 0);boundPort = realPort;diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.tsindex 130ecbde1..0f18a90c9 100644--- a/packages/server/src/server-factory.test.ts+++ b/packages/server/src/server-factory.test.ts@@ -467,6 +467,8 @@ describe('createServer() degraded signal', () => {expect(src).toContain("degraded.push('head-watcher')");expect(src).toMatch(/return\s*\{[^}]*degraded[^}]*\}/s);++ expect(src).toMatch(/finally\s*\{[\s\S]*?recordBootPhase\('indexesMs'/);});test('degraded is readonly — push and reassignment are compile-time errors', async () => {diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex 0454993ca..2579f7765 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -36,6 +36,7 @@ import { seedBasenameIndex, seedSingleDirBasenameIndex } from './asset-walk.ts';import { HocuspocusAuthRejection, parseHocuspocusAuthToken } from './auth-token-schema.ts';import { BacklinkIndex } from './backlink-index.ts';import { shellEscape } from './bash/shell-escape.ts';+import { bootElapsedMs, recordBootPhase, setBootField } from './boot-timings.ts';import {CC1Broadcaster,isConfigDoc,@@ -157,7 +158,7 @@ import { assertCompatibleStateManifest } from './state-manifest.ts';import { SyncEngine } from './sync-engine.ts';import { createSyncHandshakeSpanExtension } from './sync-handshake-span-extension.ts';import { TagIndex } from './tag-index.ts';-import { initTelemetry, shutdownTelemetry } from './telemetry.ts';+import { initTelemetry, shutdownTelemetry, withSpan } from './telemetry.ts';import { cleanupOrphanUploadTempfiles } from './upload-streaming.ts';export interface ServerOptions {@@ -1981,8 +1982,9 @@ export function createServer(options: ServerOptions): ServerInstance {switchReconciledBaseScope(startupBranch);backlinkIndex.switchBranch(startupBranch);+ const indexesStartMono = performance.now();try {- {+ await withSpan('ok.boot.indexes', undefined, async () => {const branch = getActiveBranch();try {const cacheLoaded = await backlinkIndex.loadFromDisk(branch);@@ -2011,59 +2013,66 @@ export function createServer(options: ServerOptions): ServerInstance {'[backlinks] startup init failed; index will populate incrementally via watcher',);}- }- watcher = await startWatcher(contentDir, onDiskEvent, contentFilter);- try {- await tagIndex.init();- } catch (err) {- log.error(- { err },- '[tag-index] startup re-init failed; tag index updates incrementally via watcher events',+ const seedWalkStartMono = performance.now();+ watcher = await withSpan('ok.boot.seed-walk', undefined, async () =>+ startWatcher(contentDir, onDiskEvent, contentFilter),);- degraded.push('tag-index');- }- let seedSkipCount = 0;- try {- if (singleDocRelPath !== undefined) {- seedSingleDirBasenameIndex({- contentDir,- basenameIndex,- onSkip: (reason, code, path) => {- seedSkipCount++;- log.warn(- { reason, code, path },- `[basename-index] skipped entry during single-file seed (${reason}${code ? ` ${code}` : ''})`,- );- },- });- } else {- await seedBasenameIndex({- contentDir,- contentFilter,- basenameIndex,- onSkip: (reason, code, path) => {- seedSkipCount++;- log.warn(- { reason, code, path },- `[basename-index] skipped entry during seed (${reason}${code ? ` ${code}` : ''})`,- );- },- });- }- if (seedSkipCount > 0) {- log.warn(- { count: seedSkipCount },- `[basename-index] startup seed completed with ${seedSkipCount} skipped entries — embeds under inaccessible subtrees will not resolve`,+ recordBootPhase('seedWalkMs', Math.round(performance.now() - seedWalkStartMono));+ try {+ await tagIndex.init();+ } catch (err) {+ log.error(+ { err },+ '[tag-index] startup re-init failed; tag index updates incrementally via watcher events',);- degraded.push('basename-index-partial');+ degraded.push('tag-index');}- } catch (err) {- log.error({ err }, '[basename-index] startup seed failed');- degraded.push('basename-index');- }+ let seedSkipCount = 0;+ try {+ if (singleDocRelPath !== undefined) {+ seedSingleDirBasenameIndex({+ contentDir,+ basenameIndex,+ onSkip: (reason, code, path) => {+ seedSkipCount++;+ log.warn(+ { reason, code, path },+ `[basename-index] skipped entry during single-file seed (${reason}${code ? ` ${code}` : ''})`,+ );+ },+ });+ } else {+ await seedBasenameIndex({+ contentDir,+ contentFilter,+ basenameIndex,+ onSkip: (reason, code, path) => {+ seedSkipCount++;+ log.warn(+ { reason, code, path },+ `[basename-index] skipped entry during seed (${reason}${code ? ` ${code}` : ''})`,+ );+ },+ });+ }+ if (seedSkipCount > 0) {+ log.warn(+ { count: seedSkipCount },+ `[basename-index] startup seed completed with ${seedSkipCount} skipped entries — embeds under inaccessible subtrees will not resolve`,+ );+ degraded.push('basename-index-partial');+ }+ } catch (err) {+ log.error({ err }, '[basename-index] startup seed failed');+ degraded.push('basename-index');+ }+ });} catch (err) {log.error({ err }, '[server] disk bridge watcher failed to start');degraded.push('file-watcher');+ } finally {+ recordBootPhase('indexesMs', Math.round(performance.now() - indexesStartMono));+ if (watcher) setBootField('fileCount', watcher.getFileIndex().size);}try {@@ -2479,6 +2488,9 @@ export function createServer(options: ServerOptions): ServerInstance {signalChannel('backlinks');signalChannel('graph');signalChannel('tags');++ const readyElapsed = bootElapsedMs();+ if (readyElapsed !== undefined) recordBootPhase('readyMs', readyElapsed);}initAsync().then(resolveReady, rejectReady);