Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

chore(server): route watcher/observer diagnostics through pino (#2731)

Andrew Mikofalvy8a084aeab1fe
diff --git a/.changeset/server-console-to-pino.md b/.changeset/server-console-to-pino.md
new file mode 100644
index 000000000..4b65ab64e
--- /dev/null
+++ b/.changeset/server-console-to-pino.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Server-side diagnostics (file watcher, observer bridge, content filter, shadow repo, persistence, rename log, and the rest of the server package) now route through the structured pino logger instead of raw `console.*`. Warnings and errors still print in the `ok start` terminal, and every diagnostic now also lands in `.ok/local/logs/server-current.jsonl` — the file bug-report bundles collect — so watcher drop decisions, symlink-escape refusals, and bridge recovery paths are diagnosable from a bug report even when the server runs detached under the desktop app, where console output goes nowhere persistent.
diff --git a/packages/app/tests/integration/worktree-boot.test.ts b/packages/app/tests/integration/worktree-boot.test.ts
index cb8c71d37..beeaaac8e 100644
--- a/packages/app/tests/integration/worktree-boot.test.ts
+++ b/packages/app/tests/integration/worktree-boot.test.ts
@@ -5,18 +5,18 @@
* against regression.
*/
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
-import { bootServer, ConfigSchema } from '@inkeep/open-knowledge-server';
+import { bootServer, ConfigSchema, getLogger } from '@inkeep/open-knowledge-server';
import { context, metrics, trace } from '@opentelemetry/api';
import {
BasicTracerProvider,
InMemorySpanExporter,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { createLinkedWorktree, type LinkedWorktreeHandle } from './worktree-test-harness.ts';
const TEST_CONFIG = ConfigSchema.parse({});
@@ -124,11 +124,7 @@ describe('bootServer pre-listen check in a linked worktree (FR3)', () => {
writeFileSync(resolve(okDir, 'config.yml'), '', 'utf-8');
// No .gitignore.
- const originalWarn = console.warn;
- const warnings: string[] = [];
- console.warn = (...args: unknown[]) => {
- warnings.push(args.map(String).join(' '));
- };
+ const warnSpy = vi.spyOn(getLogger('boot'), 'warn');
let booted: Awaited<ReturnType<typeof bootServer>> | null = null;
try {
@@ -142,11 +138,13 @@ describe('bootServer pre-listen check in a linked worktree (FR3)', () => {
idleShutdownMs: null,
attachUiSibling: false,
});
- const bootWarnings = warnings.filter((w) => w.startsWith('[boot]'));
+ const bootWarnings = warnSpy.mock.calls
+ .map((call) => String(call[1] ?? ''))
+ .filter((w) => w.includes('.gitignore is missing'));
expect(bootWarnings.length).toBe(1);
expect(bootWarnings[0]).toContain('.ok/.gitignore');
} finally {
- console.warn = originalWarn;
+ warnSpy.mockRestore();
if (booted) await booted.destroy();
}
});
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 14d251402..80cc1b8e0 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -1569,7 +1569,7 @@ export async function* streamShowAllEntries(
// Log to match the sibling walk's readdir-failure convention — an
// EACCES/EPERM here silently reporting hasChildren:false (folder renders
// as a non-expandable leaf) is otherwise invisible to operators.
- console.warn(`[document-list][showAll] probe readdir failed for ${absDir}:`, err);
+ log.warn({ dir: absDir, err }, `[document-list][showAll] probe readdir failed for ${absDir}`);
return false;
}
for (const entry of entries) {
@@ -1587,9 +1587,9 @@ export async function* streamShowAllEntries(
// silently-wrong hasChildren:false renders the folder permanently
// childless with no operator trace (same convention as the readdir
// and main-walk realpath catches).
- console.warn(
- `[document-list][showAll] probe realpath failed for ${absDir}/${entry.name}:`,
- err,
+ log.warn(
+ { path: `${absDir}/${entry.name}`, err },
+ `[document-list][showAll] probe realpath failed for ${absDir}/${entry.name}`,
);
continue;
}
@@ -1637,7 +1637,7 @@ export async function* streamShowAllEntries(
try {
entries = await readdir(absDir, { withFileTypes: true });
} catch (err) {
- console.warn(`[document-list][showAll] readdir failed for ${absDir}:`, err);
+ log.warn({ dir: absDir, err }, `[document-list][showAll] readdir failed for ${absDir}`);
continue;
}
const variantCountsByDocName = await docVariantCounts(entries, absDir, relDir);
@@ -1678,11 +1678,15 @@ export async function* streamShowAllEntries(
try {
dirCanonical = await realpath(dirAbsRaw);
} catch (err) {
- console.warn(`[document-list][showAll] realpath failed for ${dirAbsRaw}:`, err);
+ log.warn(
+ { path: dirAbsRaw, err },
+ `[document-list][showAll] realpath failed for ${dirAbsRaw}`,
+ );
continue;
}
if (!isInsideContentDir(dirCanonical)) {
- console.warn(
+ log.warn(
+ { path: dirAbsRaw, canonical: dirCanonical },
`[document-list][showAll] refusing symlink-escape ${dirAbsRaw} -> ${dirCanonical}`,
);
continue;
@@ -1699,7 +1703,10 @@ export async function* streamShowAllEntries(
// sibling catch below, so EACCES/EPERM/ELOOP on a restricted
// subdir is visible in operator logs instead of silently
// returning empty-mtime folder entries.
- console.warn(`[document-list][showAll] stat failed for ${dirAbsRaw}:`, err);
+ log.warn(
+ { path: dirAbsRaw, err },
+ `[document-list][showAll] stat failed for ${dirAbsRaw}`,
+ );
}
emitted += 1;
// At leaf depth (the depth-1 lazy contract stops descending here),
@@ -1748,11 +1755,15 @@ export async function* streamShowAllEntries(
try {
canonical = await realpath(linkAbs);
} catch (err) {
- console.warn(`[document-list][showAll] symlink realpath failed for ${linkAbs}:`, err);
+ log.warn(
+ { path: linkAbs, err },
+ `[document-list][showAll] symlink realpath failed for ${linkAbs}`,
+ );
continue;
}
if (!isInsideContentDir(canonical)) {
- console.warn(
+ log.warn(
+ { path: linkAbs, canonical },
`[document-list][showAll] refusing symlink-escape ${linkAbs} -> ${canonical}`,
);
continue;
@@ -1761,9 +1772,9 @@ export async function* streamShowAllEntries(
try {
canonStat = await stat(canonical);
} catch (err) {
- console.warn(
- `[document-list][showAll] symlink target stat failed for ${linkAbs}:`,
- err,
+ log.warn(
+ { path: linkAbs, err },
+ `[document-list][showAll] symlink target stat failed for ${linkAbs}`,
);
continue;
}
@@ -1832,7 +1843,10 @@ export async function* streamShowAllEntries(
try {
fileStat = await stat(join(absDir, entry.name));
} catch (err) {
- console.warn(`[document-list][showAll] stat failed for ${absDir}/${entry.name}:`, err);
+ log.warn(
+ { path: `${absDir}/${entry.name}`, err },
+ `[document-list][showAll] stat failed for ${absDir}/${entry.name}`,
+ );
continue;
}
@@ -2437,15 +2451,15 @@ function renamePathOnDisk(sourcePath: string, destinationPath: string): void {
if (tempExists && !sourceExists) {
tracedRenameSync(tempPath, sourcePath);
} else {
- console.warn('[renamePathOnDisk] skipped case-only rollback due to unexpected state:', {
- tempExists,
- sourceExists,
- });
+ log.warn(
+ { tempExists, sourceExists },
+ '[renamePathOnDisk] skipped case-only rollback due to unexpected state',
+ );
}
} catch (rollbackErr) {
- console.warn(
- '[renamePathOnDisk] failed to roll back temporary case-only rename:',
- rollbackErr,
+ log.warn(
+ { err: rollbackErr },
+ '[renamePathOnDisk] failed to roll back temporary case-only rename',
);
}
throw err;
@@ -2474,7 +2488,7 @@ async function renameTrackedPathInGit(
try {
tracked = (await pg.raw('ls-files', '--', sourceRel)).trim();
} catch (err) {
- console.warn('[renameTrackedPathInGit] git ls-files failed, falling back to fs rename:', err);
+ log.warn({ err }, '[renameTrackedPathInGit] git ls-files failed, falling back to fs rename');
return false;
}
if (!tracked) return false;
@@ -2492,9 +2506,9 @@ async function renameTrackedPathInGit(
try {
await pg.raw('mv', '--', tempRel, sourceRel);
} catch (rollbackErr) {
- console.warn(
- '[renameTrackedPathInGit] case-only git rename failed and rollback also failed; git index and disk may have diverged:',
- rollbackErr,
+ log.warn(
+ { err: rollbackErr },
+ '[renameTrackedPathInGit] case-only git rename failed and rollback also failed; git index and disk may have diverged',
);
partialStateMutation = true;
}
@@ -2506,7 +2520,7 @@ async function renameTrackedPathInGit(
return true;
} catch (err) {
if (partialStateMutation) throw err;
- console.warn('[renameTrackedPathInGit] git mv failed, falling back to fs rename:', err);
+ log.warn({ err }, '[renameTrackedPathInGit] git mv failed, falling back to fs rename');
return false;
}
});
@@ -2977,7 +2991,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const folderStat = statSync(fullPath);
upsertFolderIndexEntryInIndex(index, contentDir, fullPath, folderStat, fullPath);
} catch (err) {
- console.warn(`[api-extension] folder index stat failed for ${fullPath}:`, err);
+ log.warn({ path: fullPath, err }, `folder index stat failed for ${fullPath}`);
}
}
@@ -3187,7 +3201,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
},
];
} catch (err) {
- console.warn('[orphan-hint] computeOrphanHints failed:', err);
+ log.warn({ err }, '[orphan-hint] computeOrphanHints failed');
return undefined;
}
}
@@ -3618,7 +3632,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
for (const docName of docNames) {
await sessionManager.closeAllForDoc(docName).catch((err) => {
- console.warn(`[file-ops] Failed to close agent session for ${docName}:`, err);
+ log.warn({ docName, err }, `[file-ops] Failed to close agent session for ${docName}`);
});
}
@@ -4042,9 +4056,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const rewrittenDocs = applyPendingAssetReferenceRewrites(pendingRewrites, renamedAssets);
void backlinkIndex.saveToDisk().catch((err) => {
- console.warn(
- `[backlinks] Failed to persist asset rename cache for ${fromPath} -> ${destinationAssetPath}:`,
- err,
+ log.warn(
+ { fromPath, toPath: destinationAssetPath, err },
+ `[backlinks] Failed to persist asset rename cache for ${fromPath} -> ${destinationAssetPath}`,
);
});
signalChannel?.('files');
@@ -4185,9 +4199,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
rewrittenDocs = applyPendingAssetReferenceRewrites(pendingRewrites, renamedAssets);
void backlinkIndex.saveToDisk().catch((err) => {
- console.warn(
- `[backlinks] Failed to persist document-to-file rename cache for ${fromPath} -> ${toPath}:`,
- err,
+ log.warn(
+ { fromPath, toPath, err },
+ `[backlinks] Failed to persist document-to-file rename cache for ${fromPath} -> ${toPath}`,
);
});
signalChannel?.('files');
@@ -4330,9 +4344,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
if (rewrittenDocs.length > 0) {
void backlinkIndex.saveToDisk().catch((err) => {
- console.warn(
- `[backlinks] Failed to persist managed rename cache for ${fromPath} -> ${toPath}:`,
- err,
+ log.warn(
+ { fromPath, toPath, err },
+ `[backlinks] Failed to persist managed rename cache for ${fromPath} -> ${toPath}`,
);
});
signalChannel?.('backlinks');
@@ -4733,9 +4747,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
});
void backlinkIndex.saveToDisk().catch((err) => {
- console.warn(
- `[backlinks] Failed to persist managed rename cache for ${fromPath} -> ${toPath}:`,
- err,
+ log.warn(
+ { fromPath, toPath, err },
+ `[backlinks] Failed to persist managed rename cache for ${fromPath} -> ${toPath}`,
);
});
signalChannel?.('files');
@@ -5026,9 +5040,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// failed flush leaves this write's attribution queued for the next
// mutation's flush to retry. If no later mutation follows, it is lost —
// best-effort by design, never fatal to the mutation that already landed.
- console.warn(
- `[${context}] flushContributors failed; attribution stays queued for the next flush:`,
- flushErr,
+ log.warn(
+ { context, err: flushErr },
+ `[${context}] flushContributors failed; attribution stays queued for the next flush`,
);
}
}
@@ -6265,7 +6279,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
assets = referencedAssetsCache?.assets ?? [];
} catch (err) {
referencedAssetsCache = null;
- console.warn('[document-list] asset collection failed; returning documents only:', err);
+ log.warn({ err }, '[document-list] asset collection failed; returning documents only');
}
// Dedup set: every path emitted as a kind:'asset' entry is suppressed
@@ -7706,9 +7720,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
if (backlinkIndex) {
backlinkIndex.deleteDocument(docName);
void backlinkIndex.saveToDisk().catch((err) => {
- console.warn(
- `[backlinks] Failed to persist cache after test-reset for ${docName}:`,
- err,
+ log.warn(
+ { docName, err },
+ `[backlinks] Failed to persist cache after test-reset for ${docName}`,
);
});
signalChannel?.('backlinks');
@@ -7751,7 +7765,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
await contentFilter.rebuildIgnorePatterns();
}
} catch (err) {
- console.warn('[test-reset] okignore reset partial failure:', err);
+ log.warn({ err }, '[test-reset] okignore reset partial failure');
}
}
signalChannel?.('files');
@@ -7803,7 +7817,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// so a forced rescan keeps the global skill graph intact.
await backlinkIndex.ingestGlobalSkillBundles([resolve(skillsHome, '.ok', 'skills')]);
void backlinkIndex.saveToDisk().catch((err) => {
- console.warn('[backlinks] Failed to persist cache after test-rescan-backlinks:', err);
+ log.warn({ err }, '[backlinks] Failed to persist cache after test-rescan-backlinks');
});
signalChannel?.('backlinks');
signalChannel?.('graph');
@@ -8000,7 +8014,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
try {
await gcRenameLog(shadow, getOrLoadRenameLogIndex(shadow.gitDir));
} catch (err) {
- console.warn('[rename-log] post-saveVersion GC failed:', err);
+ log.warn({ err }, '[rename-log] post-saveVersion GC failed');
}
successResponse(
@@ -9014,12 +9028,13 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
} catch (err) {
const code = (err as NodeJS.ErrnoException | undefined)?.code;
if (code === 'ENOENT') {
- console.warn('[workspace] contentDir does not exist; returning unresolved path', {
- path: resolvedRoot,
- });
+ log.warn(
+ { path: resolvedRoot },
+ '[workspace] contentDir does not exist; returning unresolved path',
+ );
symlinkResolved = false;
} else {
- console.warn('[workspace] realpath failed for contentDir', { path: resolvedRoot, err });
+ log.warn({ path: resolvedRoot, err }, '[workspace] realpath failed for contentDir');
errorResponse(
res,
500,
@@ -9327,7 +9342,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
try {
unlinkSync(filePath);
} catch (e) {
- console.debug('[rescue] cleanup failed (non-critical):', e);
+ log.debug({ err: e }, '[rescue] cleanup failed (non-critical)');
}
continue;
}
@@ -9579,7 +9594,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
if (backlinkIndex) {
backlinkIndex.updateDocumentFromMarkdown(docName, initialContent);
void backlinkIndex.saveToDisk().catch((err) => {
- console.warn(`[backlinks] Failed to persist create-page cache for ${docName}:`, err);
+ log.warn(
+ { docName, err },
+ `[backlinks] Failed to persist create-page cache for ${docName}`,
+ );
});
signalChannel?.('backlinks');
signalChannel?.('graph');
@@ -9841,10 +9859,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
} catch (cleanupErr) {
const cleanupCode = (cleanupErr as NodeJS.ErrnoException).code;
if (cleanupCode !== 'ENOENT' && cleanupCode !== 'ENOTEMPTY') {
- console.warn('[duplicate-path] failed to clean duplicate parent directory:', {
- destinationDir,
- err: cleanupErr,
- });
+ log.warn(
+ { destinationDir, err: cleanupErr },
+ '[duplicate-path] failed to clean duplicate parent directory',
+ );
}
}
}
@@ -9871,10 +9889,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
try {
tracedRmSync(destinationPath, { force: true });
} catch (cleanupErr) {
- console.warn('[duplicate-path] failed to clean partial file duplicate:', {
- destinationPath,
- err: cleanupErr,
- });
+ log.warn(
+ { destinationPath, err: cleanupErr },
+ '[duplicate-path] failed to clean partial file duplicate',
+ );
}
forgetDocExtension(duplicatedPath);
if (contentFilter && didIncrementMdDir) {
@@ -9946,10 +9964,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
try {
tracedRmSync(destinationPath, { recursive: true, force: true });
} catch (cleanupErr) {
- console.warn('[duplicate-path] failed to clean partial folder duplicate:', {
- destinationPath,
- err: cleanupErr,
- });
+ log.warn(
+ { destinationPath, err: cleanupErr },
+ '[duplicate-path] failed to clean partial folder duplicate',
+ );
}
throw err;
}
@@ -9981,7 +9999,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
if (backlinkIndex && duplicatedDocNames.length > 0) {
void backlinkIndex.saveToDisk().catch((err) => {
- console.warn('[backlinks] Failed to persist duplicate-path cache:', err);
+ log.warn({ err }, '[backlinks] Failed to persist duplicate-path cache');
});
signalChannel?.('backlinks');
signalChannel?.('graph');
@@ -10212,9 +10230,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
try {
await flushContributors();
} catch (flushErr) {
- console.warn(
- `[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred):`,
- flushErr,
+ log.warn(
+ { err: flushErr },
+ '[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred)',
);
}
}
@@ -10397,9 +10415,9 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
try {
await flushContributors();
} catch (flushErr) {
- console.warn(
- `[rename-path] flushContributors failed (commitSha backfill may be deferred):`,
- flushErr,
+ log.warn(
+ { err: flushErr },
+ '[rename-path] flushContributors failed (commitSha backfill may be deferred)',
);
}
}
@@ -10826,7 +10844,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
title = extractPageTitle(content, docName);
icon = extractPageIcon(content);
} catch (err) {
- console.warn(`[pages] Failed to read title for ${docName}:`, err);
+ log.warn({ docName, err }, `[pages] Failed to read title for ${docName}`);
}
}
pages.push({ docName, title, docExt, size: entry.size, modified: entry.modified, icon });
@@ -11776,7 +11794,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
const gitDirKind = resolveGitDirDetailed(canonicalPath).kind;
if (gitDirKind !== 'directory' && gitDirKind !== 'linked') {
- console.warn(
+ log.warn(
+ { project: basename(canonicalPath), result: 'not-a-git-worktree', kind: gitDirKind },
`[ok-init] action=init project=${basename(canonicalPath)} result=not-a-git-worktree kind=${gitDirKind}`,
);
successResponse(
@@ -11798,7 +11817,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// earlier so callers don't see two `[ok-init] action=init …` log lines
// for a no-op call.
if (isProjectRoot(canonicalPath)) {
- console.warn(
+ log.warn(
+ { project: basename(canonicalPath), result: 'already-initialized' },
`[ok-init] action=init project=${basename(canonicalPath)} result=already-initialized`,
);
successResponse(
@@ -11828,7 +11848,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
await withParentLock(async () => {
initContent(canonicalPath);
});
- console.warn(`[ok-init] action=init project=${basename(canonicalPath)} result=success`);
+ log.warn(
+ { project: basename(canonicalPath), result: 'success' },
+ `[ok-init] action=init project=${basename(canonicalPath)} result=success`,
+ );
successResponse(
res,
200,
@@ -11838,7 +11861,8 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
- console.warn(
+ log.warn(
+ { project: basename(canonicalPath), result: 'failed', reason: message },
`[ok-init] action=init project=${basename(canonicalPath)} result=failed reason=${message}`,
);
successResponse(
@@ -12874,7 +12898,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
}
} else {
- console.warn(`[conflict-content] doc ${docName} not loaded; lifecycleStatus unavailable`);
+ log.warn(
+ { docName },
+ `[conflict-content] doc ${docName} not loaded; lifecycleStatus unavailable`,
+ );
}
}
successResponse(
@@ -13377,7 +13404,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
- console.warn(`[folder-config:get] malformed YAML in ${localFmPath}: ${reason}`);
+ log.warn(
+ { path: localFmPath, reason },
+ `[folder-config:get] malformed YAML in ${localFmPath}: ${reason}`,
+ );
frontmatterLocal = null;
}
}
@@ -14238,7 +14268,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
let starterContent = '';
if (Object.keys(starterFmObj).length > 0) {
const fmYaml = stringifyYaml(starterFmObj);
- starterContent = fmYaml.trim() + '\n';
+ starterContent = `${fmYaml.trim()}\n`;
}
starterContent = starterContent ? `---\n${starterContent}---\n${sourceBody}` : sourceBody;
@@ -16724,7 +16754,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// mtime/size/inode shifts. Skip the cache write so the next rebuild
// retries, preserving the pre-cache self-healing behavior.
readFailed = true;
- console.warn(`[search] Failed to read ${docName}:`, err);
+ log.warn({ docName, err }, `[search] Failed to read ${docName}`);
}
if (!readFailed) {
try {
@@ -16735,7 +16765,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// docName as title but still cache (the read succeeded) — caching it
// avoids re-parsing the same failing content on every rebuild, the
// opposite of the read-failure path's deliberate retry.
- console.warn(`[search] Failed to extract title for ${docName}:`, err);
+ log.warn({ docName, err }, `[search] Failed to extract title for ${docName}`);
}
}
const doc = createWorkspaceSearchDocument({
@@ -16916,7 +16946,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
for (const delayMs of [0, 1000, 3000]) {
setTimeout(() => {
void getWorkspaceSearchCorpus().catch((err) => {
- console.warn('[search] Failed to prewarm workspace search cache:', err);
+ log.warn({ err }, '[search] Failed to prewarm workspace search cache');
});
}, delayMs);
}
@@ -17532,7 +17562,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
* inline spawn so the route-shape meta-tests scan one consistent pattern.
*
* stderr is piped + collected; on non-zero exit, a redacted prefix is
- * logged via `console.warn('[share] subprocess ...')` so production
+ * logged via the `api` logger (`[share] subprocess ...`) so production
* failures (git binary missing, keychain denied, Octokit auth error)
* leave a diagnostic trail. Credential URLs of the form
* `x-access-token:<token>@github.com` get the token replaced with `***`
@@ -17574,7 +17604,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
if (code !== 0) {
const stderr = Buffer.concat(stderrChunks).toString('utf-8');
const redacted = redactShareSubprocessStderr(stderr).slice(0, 500);
- console.warn(`[share] subprocess exited code=${code} stderr=${redacted}`);
+ log.warn(
+ { code, stderr: redacted },
+ `[share] subprocess exited code=${code} stderr=${redacted}`,
+ );
}
resolveSpawn({ stdout, code });
});
diff --git a/packages/server/src/asset-references.test.ts b/packages/server/src/asset-references.test.ts
index 6f44b1882..ff9bc8827 100644
--- a/packages/server/src/asset-references.test.ts
+++ b/packages/server/src/asset-references.test.ts
@@ -1,7 +1,7 @@
-import { describe, expect, spyOn, test } from 'bun:test';
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
+import { describe, expect, test, vi } from 'vitest';
import {
assetReferenceSignature,
assetReferencesChanged,
@@ -13,6 +13,7 @@ import {
stripHrefDecorations,
} from './asset-references.ts';
import type { FileIndexEntry } from './file-watcher.ts';
+import { getLogger } from './logger.ts';
function withFixture(fn: (dir: string) => void) {
const dir = mkdtempSync(join(tmpdir(), 'ok-assets-'));
@@ -391,7 +392,7 @@ describe('asset reference extraction', () => {
}));
test('returns empty asset list when content directory cannot be resolved', () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(getLogger('asset-references'), 'warn');
try {
const assets = collectReferencedAssets({
contentDir: join(tmpdir(), 'ok-missing-content-dir'),
@@ -407,7 +408,7 @@ describe('asset reference extraction', () => {
});
test('returns null when resolving from a missing content directory', () => {
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(getLogger('asset-references'), 'warn');
try {
expect(
resolveReferencedAssetPath({
diff --git a/packages/server/src/asset-references.ts b/packages/server/src/asset-references.ts
index 1fd70605c..f769448d1 100644
--- a/packages/server/src/asset-references.ts
+++ b/packages/server/src/asset-references.ts
@@ -8,8 +8,11 @@ import {
resolveAssetProjectPath,
} from '@inkeep/open-knowledge-core';
import type { FileIndexEntry } from './file-watcher.ts';
+import { getLogger } from './logger.ts';
import { isWithinContentDir } from './persistence.ts';
+const log = getLogger('asset-references');
+
interface ReferencedAssetEntry {
kind: 'asset';
path: string;
@@ -156,7 +159,7 @@ function resolveReferencedAssetWithinContentDir(args: {
} catch (err) {
const code = errnoCode(err);
if (code !== 'ENOENT' && code !== 'ENOTDIR') {
- console.warn('[asset-references] unexpected error resolving asset:', args.href, err);
+ log.warn({ href: args.href, err }, 'unexpected error resolving asset');
}
return null;
}
@@ -177,7 +180,7 @@ export function resolveReferencedAssetPath(args: {
try {
contentDir = normalize(realpathSync(args.contentDir));
} catch (err) {
- console.warn('[asset-references] could not resolve content directory:', err);
+ log.warn({ err }, 'could not resolve content directory');
return null;
}
return resolveReferencedAssetWithinContentDir({ ...args, contentDir })?.absolutePath ?? null;
@@ -207,7 +210,7 @@ export function collectReferencedAssets(args: {
try {
contentDir = normalize(realpathSync(args.contentDir));
} catch (err) {
- console.warn('[asset-references] could not resolve content directory:', err);
+ log.warn({ err }, 'could not resolve content directory');
return [];
}
const byPath = new Map<string, ReferencedAssetEntry>();
diff --git a/packages/server/src/backlink-index.ts b/packages/server/src/backlink-index.ts
index 0966fb257..68c887a58 100644
--- a/packages/server/src/backlink-index.ts
+++ b/packages/server/src/backlink-index.ts
@@ -23,8 +23,11 @@ import { isLinkIndexExcludedDoc } from './cc1-broadcast.ts';
import { getLocalDir } from './config/paths.ts';
import type { ContentFilter } from './content-filter.ts';
import { isSupportedDocFile, stripDocExtension } from './doc-extensions.ts';
+import { getLogger } from './logger.ts';
import { toPosix } from './path-utils.ts';
+const log = getLogger('backlinks');
+
// Line-oriented variant: excludes \n since lines are pre-split.
// cf. packages/core/src/extensions/wiki-link.ts WIKI_LINK_PATTERN (no \n exclusion).
// Sticky flag ('y') enables position-based matching via lastIndex.
@@ -1198,7 +1201,7 @@ export class BacklinkIndex {
];
this.updateDocument(docName, merged, mergedExternal, branch);
} catch (err) {
- console.warn(`[backlinks] Failed to scan ${docName} for link extraction:`, err);
+ log.warn({ docName, err }, `Failed to scan ${docName} for link extraction`);
this.deleteDocument(docName, branch);
}
}
@@ -1621,7 +1624,7 @@ export class BacklinkIndex {
}
return true;
} catch (err) {
- console.warn(`[backlinks] Failed to load cache for ${branch}:`, err);
+ log.warn({ branch, err }, `Failed to load cache for ${branch}`);
return false;
}
}
@@ -1672,7 +1675,7 @@ export class BacklinkIndex {
for (const result of settled) {
if (result.status === 'rejected') {
- console.warn('[backlinks] Failed to rebuild entry:', result.reason);
+ log.warn({ err: result.reason }, 'Failed to rebuild entry');
continue;
}
const { docName, mtimeMs, markdown } = result.value;
@@ -1743,7 +1746,7 @@ export class BacklinkIndex {
try {
entries = await readdir(dir, { withFileTypes: true });
} catch (err) {
- console.warn(`[backlinks] Failed to read directory ${dir}:`, err);
+ log.warn({ dir, err }, `Failed to read directory ${dir}`);
return;
}
for (const entry of entries) {
@@ -1840,7 +1843,7 @@ export class BacklinkIndex {
);
for (const result of settled) {
if (result.status === 'rejected') {
- console.warn('[backlinks] Failed to reconcile file:', result.reason);
+ log.warn({ err: result.reason }, 'Failed to reconcile file');
continue;
}
const { docName, mtimeMs, isNew, markdown } = result.value;
@@ -1898,7 +1901,7 @@ export class BacklinkIndex {
try {
skillDirs = await readdir(root, { withFileTypes: true });
} catch (err) {
- console.warn(`[backlinks] Failed to read global skills root ${root}:`, err);
+ log.warn({ root, err }, `Failed to read global skills root ${root}`);
continue;
}
for (const skillDir of skillDirs) {
@@ -1951,7 +1954,7 @@ export class BacklinkIndex {
// A real IO failure (EACCES/EIO) silently drops a skill's references
// from the graph, so surface it rather than swallowing indistinguishably.
if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') {
- console.warn(`[backlinks] Failed to read skill references dir ${dir}:`, err);
+ log.warn({ dir, err }, `Failed to read skill references dir ${dir}`);
}
return;
}
diff --git a/packages/server/src/boot.test.ts b/packages/server/src/boot.test.ts
index feb02f22f..0c58043da 100644
--- a/packages/server/src/boot.test.ts
+++ b/packages/server/src/boot.test.ts
@@ -1,4 +1,4 @@
-import { describe as _bunDescribe, afterEach, beforeEach, expect, test } from 'bun:test';
+import { describe as _bunDescribe, afterEach, beforeEach, expect, test, vi } from 'vitest';
// Skip-on-CI gate (oven-sh/bun#11892): subprocess or git child spawns; Bun fails to reap children on ubuntu-latest GHA runners (oven-sh/bun#11892).
// Tests run normally locally; follow-up will narrow the leak surface.
@@ -22,6 +22,7 @@ import {
import { bootServer } from './boot.ts';
import { getBootTimings } from './boot-timings.ts';
import { ConfigSchema } from './config/schema.ts';
+import { getLogger } from './logger.ts';
import { parseKeepaliveConnectionId } from './mcp-mount.ts';
import { shutdownTelemetry } from './telemetry.ts';
@@ -188,11 +189,7 @@ describe('bootServer — MissingOkConfigError pre-listen check', () => {
writeFileSync(resolve(okDir, 'config.yml'), '', 'utf-8');
// Note: NO .gitignore.
- const originalWarn = console.warn;
- const warnings: string[] = [];
- console.warn = (...args: unknown[]) => {
- warnings.push(args.map(String).join(' '));
- };
+ const warnSpy = vi.spyOn(getLogger('boot'), 'warn');
let booted: Awaited<ReturnType<typeof bootServer>> | null = null;
try {
booted = await bootServer({
@@ -205,12 +202,14 @@ describe('bootServer — MissingOkConfigError pre-listen check', () => {
idleShutdownMs: null,
attachUiSibling: false,
});
- const bootWarnings = warnings.filter((w) => w.startsWith('[boot]'));
+ const bootWarnings = warnSpy.mock.calls
+ .map((call) => String(call[1] ?? ''))
+ .filter((w) => w.includes('.gitignore is missing'));
expect(bootWarnings.length).toBe(1);
expect(bootWarnings[0]).toContain('.ok/.gitignore');
expect(bootWarnings[0]).toContain('ok init');
} finally {
- console.warn = originalWarn;
+ warnSpy.mockRestore();
if (booted) await booted.destroy();
}
});
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index 753b387a3..ba69bac2f 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -571,8 +571,9 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
}
const gitignorePath = resolve(okDir, '.gitignore');
if (!existsSync(gitignorePath)) {
- console.warn(
- `[boot] Note: ${OK_DIR}/.gitignore is missing — per-machine state files in ${OK_DIR}/ may show up as untracked changes. Run \`ok init\` to add the recommended ignore entries.`,
+ getLogger('boot').warn(
+ { path: gitignorePath },
+ `Note: ${OK_DIR}/.gitignore is missing — per-machine state files in ${OK_DIR}/ may show up as untracked changes. Run \`ok init\` to add the recommended ignore entries.`,
);
}
@@ -635,8 +636,9 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
// No action taken; boot proceeds.
const legacyFound = findLegacyRuntimeFiles(okDir);
if (legacyFound.length > 0) {
- console.warn(
- `[boot] Found legacy runtime files at ${OK_DIR}/${legacyFound.join(', ')}. Delete ${OK_DIR}/ and re-init — these files moved to ${OK_DIR}/${LOCAL_DIR}/.`,
+ getLogger('boot').warn(
+ { files: legacyFound },
+ `Found legacy runtime files at ${OK_DIR}/${legacyFound.join(', ')}. Delete ${OK_DIR}/ and re-init — these files moved to ${OK_DIR}/${LOCAL_DIR}/.`,
);
}
diff --git a/packages/server/src/config-persistence.ts b/packages/server/src/config-persistence.ts
index 7c5c806f3..add06a3ed 100644
--- a/packages/server/src/config-persistence.ts
+++ b/packages/server/src/config-persistence.ts
@@ -50,6 +50,8 @@ import { tracedMkdir, tracedRename, tracedUnlinkSync, tracedWriteFile } from './
import { getLogger } from './logger.ts';
import { getMeter } from './telemetry.ts';
+const log = getLogger('config-persistence');
+
/**
* Map a documentName to the OTel `config.scope` enum attribute.
* Returns `undefined` for non-config docs (caller should never invoke this
@@ -327,7 +329,10 @@ export function loadConfigDoc(
raw = readFileSync(filePath, 'utf-8');
} catch (e) {
const detail = e instanceof Error ? e.message : String(e);
- console.warn(`[config] Could not read ${filePath}: ${detail}. Seeding with empty content.`);
+ log.warn(
+ { path: filePath, err: e },
+ `[config-persistence] Could not read ${filePath}: ${detail}. Seeding with empty content.`,
+ );
raw = '';
}
}
@@ -338,7 +343,7 @@ export function loadConfigDoc(
// errors" at boot rather than discovering it only via the L3 hook
// when the next mutation triggers a revert. The Y.Text is still
// seeded with the raw content so a UI can display + repair it.
- getLogger('config-persistence').warn(
+ log.warn(
{ docName: documentName, path: filePath },
`[config-persistence] loadConfigDoc seeding invalid content for ${documentName} into Y.Text — first mutation will revert to LKG`,
);
@@ -526,7 +531,7 @@ async function storeConfigDocInner(
await tracedMkdir(dirname(filePath), { recursive: true });
} catch (e) {
const detail = e instanceof Error ? e.message : String(e);
- getLogger('config-persistence').warn(
+ log.warn(
{ docName: documentName, path: filePath, err: e },
`[config-persistence] could not create parent dir for ${filePath}: ${detail}`,
);
@@ -572,7 +577,7 @@ async function storeConfigDocInner(
// the cross-window clobber (we'd overwrite
// disk we couldn't observe).
const detail = e instanceof Error ? e.message : String(e);
- getLogger('config-persistence').warn(
+ log.warn(
{ docName: documentName, path: filePath, err: e },
`[config-persistence] could not read config for reconciliation: ${detail}`,
);
@@ -593,7 +598,7 @@ async function storeConfigDocInner(
ytext.insert(0, diskContent);
}, CONFIG_FILE_WATCHER_ORIGIN);
ctx.lkgCache.set(documentName, diskContent);
- getLogger('config-persistence').info(
+ log.info(
{ docName: documentName, path: filePath },
'[config-persistence] reconciled: external writer landed; imported disk into Y.Text',
);
@@ -602,7 +607,7 @@ async function storeConfigDocInner(
// Disk diverged but content is invalid — don't poison Y.Text or
// LKG. Our content was already validated above the lock; writing
// it here replaces the disk's broken state with valid bytes.
- getLogger('config-persistence').warn(
+ log.warn(
{ docName: documentName, path: filePath },
'[config-persistence] disk diverged from LKG but contains invalid content; proceeding with local write',
);
@@ -617,7 +622,7 @@ async function storeConfigDocInner(
// `onConfigRejected` callback. Disk-full / permissions /
// parent-replaced-by-file are otherwise invisible — the L3 hook
// returns silently and the next mutation re-attempts indefinitely.
- getLogger('config-persistence').warn(
+ log.warn(
{ docName: documentName, path: filePath, err: e },
`[config-persistence] write-failed at ${filePath}: ${detail}`,
);
@@ -632,7 +637,7 @@ async function storeConfigDocInner(
},
{
onWarn: (message, context) => {
- getLogger('config-persistence').warn(context, `[config-persistence] ${message}`);
+ log.warn(context, `[config-persistence] ${message}`);
},
},
);
@@ -645,7 +650,7 @@ async function storeConfigDocInner(
// Y.Text and re-attempts on next store. Any other thrown error is
// unexpected and should propagate so the operator sees it.
if (e instanceof FileLockTimeoutError) {
- getLogger('config-persistence').warn(
+ log.warn(
{ docName: documentName, path: filePath, err: e },
`[config-persistence] lock timeout at ${filePath}: ${e.message}`,
);
diff --git a/packages/server/src/conflict-lifecycle-seed.ts b/packages/server/src/conflict-lifecycle-seed.ts
index 752c02e6e..de2e2c5cc 100644
--- a/packages/server/src/conflict-lifecycle-seed.ts
+++ b/packages/server/src/conflict-lifecycle-seed.ts
@@ -40,6 +40,7 @@ import type { Extension } from '@hocuspocus/server';
import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';
import type { ConflictEntry } from './conflict-storage.ts';
import { stripDocExtension } from './doc-extensions.ts';
+import { getLogger } from './logger.ts';
import { toPosix } from './path-utils.ts';
import type { SyncEngine } from './sync-engine.ts';
@@ -101,9 +102,9 @@ export function createConflictLifecycleSeedExtension(
}),
);
} catch (err) {
- console.warn(
- `[conflict-lifecycle-seed] failed to seed lifecycle on load (doc=${documentName}):`,
- err instanceof Error ? err : String(err),
+ getLogger('conflict-lifecycle-seed').warn(
+ { docName: documentName, err: err instanceof Error ? err : new Error(String(err)) },
+ `failed to seed lifecycle on load (doc=${documentName})`,
);
}
},
diff --git a/packages/server/src/console-discipline.test.ts b/packages/server/src/console-discipline.test.ts
new file mode 100644
index 000000000..8e07deacc
--- /dev/null
+++ b/packages/server/src/console-discipline.test.ts
@@ -0,0 +1,205 @@
+/**
+ * Source-scan STOP rule for server-side logging discipline: non-test server
+ * sources route diagnostics through pino `getLogger(name)` (logger.ts), never
+ * raw `console.*`. Console output only reaches the terminal; the pino file
+ * sink (`.ok/local/logs/server-current.jsonl`) is what bug-report bundles
+ * collect, and the packaged desktop app runs the server detached with no
+ * persistent stdio — a raw `console.warn` there is a diagnostic dropped on
+ * the floor.
+ *
+ * Two sanctioned exceptions:
+ * 1. The structured telemetry-event channel: `console.<level>(JSON.stringify(
+ * { event: ... }))`. This is a designed observation contract — in-process
+ * integration harnesses and e2e suites capture `console.warn` and
+ * string-match `"event":"..."` payloads across package boundaries, so
+ * those emissions stay on console by contract. Detected structurally:
+ * a `JSON.stringify(` within the call's argument window.
+ * 2. Whole-file exemptions (`FILE_ALLOWLIST`), each with a structural why:
+ * logger bootstrap paths that cannot log through the logger itself, the
+ * MCP stdio surface where stdout is the JSON-RPC channel, and CLI-run
+ * eval harnesses whose stdout is the user-facing report.
+ *
+ * The predicate is line-window based, so it has planted-positive +
+ * adjacent-negative self-tests below (an absence-checker without a planted
+ * positive is a vacuous no-op — same discipline as
+ * loopback-bind-discipline.test.ts).
+ */
+
+import { readdirSync, readFileSync } from 'node:fs';
+import { basename, dirname, join, relative } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const SCAN_ROOT = __dirname; // packages/server/src
+
+/** This file embeds the banned patterns as predicate fixtures. */
+const SELF_BASENAME = basename(fileURLToPath(import.meta.url));
+
+/**
+ * Whole-file exemptions, keyed by path relative to packages/server/src.
+ * Every entry needs a reason that explains why pino cannot serve the site.
+ */
+const FILE_ALLOWLIST: ReadonlyMap<string, string> = new Map([
+ [
+ 'logger.ts',
+ 'pino-pretty bootstrap fallback — the logger cannot report its own construction failure through itself',
+ ],
+ [
+ 'local-sink-resolver.ts',
+ 'resolves the file-sink config the logger is built FROM; runs before any logger is wired',
+ ],
+ [
+ 'mcp/logger.ts',
+ 'MCP stdio logger self-failure path — stdout is the JSON-RPC channel, so this surface writes to stderr/OK_LOG_FILE by design',
+ ],
+ [
+ 'mcp/pretty-zod-errors.ts',
+ 'runs inside the MCP server surface where stdout is the JSON-RPC channel; console.warn targets stderr',
+ ],
+ [
+ 'embeddings/eval/semantic-eval.ts',
+ 'CLI-run eval harness — stdout IS the user-facing report (same carve-out as CLI user-facing stdout)',
+ ],
+]);
+
+interface FileLines {
+ /** Path relative to packages/server/src for failure messages. */
+ path: string;
+ lines: string[];
+}
+
+function listScannedSourceFiles(): FileLines[] {
+ const out: FileLines[] = [];
+ function walk(dir: string) {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const abs = join(dir, entry.name);
+ if (entry.isDirectory()) {
+ walk(abs);
+ continue;
+ }
+ if (!entry.isFile() || !entry.name.endsWith('.ts')) continue;
+ if (entry.name.endsWith('.test.ts') || entry.name.endsWith('.test-helper.ts')) continue;
+ if (entry.name === SELF_BASENAME) continue;
+ out.push({
+ path: relative(SCAN_ROOT, abs),
+ lines: readFileSync(abs, 'utf-8').split('\n'),
+ });
+ }
+ }
+ walk(SCAN_ROOT);
+ return out;
+}
+
+function isCommentOnlyLine(line: string): boolean {
+ const trimmed = line.trim();
+ return trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('/*');
+}
+
+const CONSOLE_CALL = /\bconsole\.(log|info|warn|error|debug)\(/;
+
+/**
+ * Find raw `console.<level>(` call sites whose argument window (the match
+ * line plus up to 2 continuation lines) does NOT open with `JSON.stringify(`
+ * — i.e. everything except the sanctioned structured-event channel. The
+ * window is small on purpose: every current structured emission puts
+ * `JSON.stringify(` on the call line or the immediately following line.
+ */
+export function findRawConsoleCalls(lines: string[]): Array<{ line: number; text: string }> {
+ const violations: Array<{ line: number; text: string }> = [];
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i] ?? '';
+ if (isCommentOnlyLine(line)) continue;
+ const m = CONSOLE_CALL.exec(line);
+ if (!m) continue;
+ const windowText = [line, lines[i + 1] ?? '', lines[i + 2] ?? ''].join('\n');
+ const afterCall = windowText.slice(windowText.indexOf(m[0]) + m[0].length);
+ if (/^\s*JSON\.stringify\(/.test(afterCall)) continue;
+ violations.push({ line: i + 1, text: line.trim() });
+ }
+ return violations;
+}
+
+describe('console discipline (server sources)', () => {
+ const files = listScannedSourceFiles();
+
+ test('there are source files to scan (sanity)', () => {
+ expect(files.length).toBeGreaterThan(0);
+ expect(files.some((f) => f.path === 'file-watcher.ts')).toBe(true);
+ });
+
+ test('every FILE_ALLOWLIST entry still exists on disk', () => {
+ const paths = new Set(files.map((f) => f.path));
+ for (const allowed of FILE_ALLOWLIST.keys()) {
+ expect(paths.has(allowed)).toBe(true);
+ }
+ });
+
+ test('non-test server sources use getLogger, not raw console.*', () => {
+ const violations: string[] = [];
+ for (const file of files) {
+ if (FILE_ALLOWLIST.has(file.path)) continue;
+ for (const v of findRawConsoleCalls(file.lines)) {
+ violations.push(` ${file.path}:${v.line} ${v.text}`);
+ }
+ }
+ if (violations.length > 0) {
+ throw new Error(
+ `Raw console.* call found in packages/server/src — console output never reaches the pino file sink ` +
+ `(.ok/local/logs/server-current.jsonl) that bug-report bundles collect, and the packaged desktop app ` +
+ `runs the server detached with no persistent stdio. Use getLogger(name) from './logger.ts' ` +
+ `(warn/error still reach the terminal through the console stream). The only sanctioned console shapes ` +
+ `are the structured telemetry-event channel (console.<level>(JSON.stringify({ event: ... }))) and the ` +
+ `FILE_ALLOWLIST bootstrap/stdio surfaces in console-discipline.test.ts:\n${violations.join('\n')}`,
+ );
+ }
+ });
+
+ test('predicate fires on planted violations and not on adjacent negatives', () => {
+ // Planted positives: the raw shapes this rule bans.
+ expect(findRawConsoleCalls([" console.warn('[file-watcher] dropping event');"]).length).toBe(
+ 1,
+ );
+ expect(findRawConsoleCalls([" console.error('failed for path:', err);"]).length).toBe(1);
+ expect(findRawConsoleCalls([' console.log("hi");']).length).toBe(1);
+ // Multi-line raw call: first argument is a plain string, not JSON.stringify.
+ expect(
+ findRawConsoleCalls([' console.warn(', " 'lstat failed for path',", ' );']).length,
+ ).toBe(1);
+
+ // Adjacent negatives: the sanctioned structured-event channel.
+ expect(
+ findRawConsoleCalls([" console.warn(JSON.stringify({ event: 'x', docName }));"]).length,
+ ).toBe(0);
+ expect(
+ findRawConsoleCalls([' console.warn(', ' JSON.stringify({', " event: 'x',"]).length,
+ ).toBe(0);
+ expect(
+ findRawConsoleCalls([' console.info(', ' JSON.stringify({', " event: 'y',"]).length,
+ ).toBe(0);
+
+ // Comment-only lines are exempt.
+ expect(findRawConsoleCalls([' // a stray console.warn(x) in prose']).length).toBe(0);
+ expect(findRawConsoleCalls([' * logged via `console.warn(...)` so production']).length).toBe(0);
+
+ // getLogger call sites are not console calls at all.
+ expect(findRawConsoleCalls([" getLogger('file-watcher').warn({ err }, 'x');"]).length).toBe(0);
+
+ // Known limitation, pinned: JSON.stringify further than 2 lines below the
+ // call is flagged — keep the stringify adjacent to the console call.
+ expect(
+ findRawConsoleCalls([
+ ' console.warn(',
+ ' // comment',
+ ' // comment',
+ ' JSON.stringify({',
+ ]).length,
+ ).toBe(1);
+
+ // Known limitation, pinned: a trailing inline comment containing the
+ // banned pattern false-positives (isCommentOnlyLine only exempts lines
+ // that START with a comment marker). Don't write `console.warn(` in a
+ // trailing comment — reword the prose instead.
+ expect(findRawConsoleCalls([' doSomething(); // like console.warn(x) did']).length).toBe(1);
+ });
+});
diff --git a/packages/server/src/content-filter.ts b/packages/server/src/content-filter.ts
index 1763003f6..9d1804c7c 100644
--- a/packages/server/src/content-filter.ts
+++ b/packages/server/src/content-filter.ts
@@ -33,6 +33,8 @@ import { getLogger } from './logger.ts';
import { toPosix } from './path-utils.ts';
import { withSpan } from './telemetry.ts';
+const log = getLogger('content-filter');
+
const execFileAsync = promisify(execFileCb);
/**
@@ -504,7 +506,7 @@ function appendExcludeFileIfExists(
bytesAcc.value += content.length;
patterns.push(...parseIgnorePatterns(content));
} catch (err) {
- console.warn(`[content-filter] Failed to read ${label} at ${path}:`, err);
+ log.warn({ path, err }, `Failed to read ${label} at ${path}`);
}
}
@@ -520,7 +522,7 @@ async function appendExcludeFileIfExistsAsync(
bytesAcc.value += content.length;
patterns.push(...parseIgnorePatterns(content));
} catch (err) {
- console.warn(`[content-filter] Failed to read ${label} at ${path}:`, err);
+ log.warn({ path, err }, `Failed to read ${label} at ${path}`);
}
}
@@ -719,7 +721,7 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
newRootPatterns.push(...patterns);
newIg.add(patterns);
} catch (err) {
- console.warn(`[content-filter] Failed to read ${name} at ${path}:`, err);
+ log.warn({ path, err }, `Failed to read ${name} at ${path}`);
}
}
@@ -736,7 +738,7 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
const prefixed = patterns.map((p) => prefixPattern(p, contentRelPrefix));
newIg.add(prefixed);
} catch (err) {
- console.warn(`[content-filter] Failed to read ${name} at ${path}:`, err);
+ log.warn({ path, err }, `Failed to read ${name} at ${path}`);
}
}
}
@@ -1032,7 +1034,7 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
refreshDirCount();
} catch (err) {
for (const [k, v] of prev) dirCount.set(k, v);
- getLogger('content-filter').warn(
+ log.warn(
{ err: err instanceof Error ? err : new Error(String(err)) },
'content-filter rebuildDirCount walk failed — retaining previous counts',
);
@@ -1040,8 +1042,6 @@ export function createContentFilter(opts: ContentFilterOptions): ContentFilter {
},
async rebuildIgnorePatterns(): Promise<RebuildResult> {
- const log = getLogger('content-filter');
-
// Snapshot for rollback. dirCount is too large to snapshot — we re-walk
// it from the rolled-back ig instance if rebuild fails partway.
const prevIg = ig;
@@ -1152,7 +1152,7 @@ function populateDirCount(
// Mirror the diagnostic surface of `loadNestedIgnoreFiles` for the same
// failure mode: silent skip would leave the sibling-asset refcount
// under-counted with no operator trail.
- console.warn(`[content-filter] Failed to read directory for dir-count: ${dir}`, err);
+ log.warn({ dir, err }, `Failed to read directory for dir-count: ${dir}`);
return;
}
for (const entry of entries) {
@@ -1226,7 +1226,7 @@ function loadNestedIgnoreFiles(
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch (err) {
- console.warn(`[content-filter] Failed to read directory ${dir}:`, err);
+ log.warn({ dir, err }, `Failed to read directory ${dir}`);
return 0;
}
@@ -1258,7 +1258,7 @@ function loadNestedIgnoreFiles(
ig.add(prefixed);
count++;
} catch (err) {
- console.warn(`[content-filter] Failed to read nested ${name} at ${filePath}:`, err);
+ log.warn({ path: filePath, err }, `Failed to read nested ${name} at ${filePath}`);
}
}
@@ -1292,7 +1292,7 @@ async function initContentDirStateAsync(
try {
entries = await readdir(dir, { withFileTypes: true });
} catch (err) {
- console.warn(`[content-filter] Failed to read directory ${dir}:`, err);
+ log.warn({ dir, err }, `Failed to read directory ${dir}`);
return;
}
@@ -1317,7 +1317,7 @@ async function initContentDirStateAsync(
const patterns = parseIgnorePatterns(await readFileAsync(filePath, 'utf-8'));
ig.add(patterns.map((p) => prefixPattern(p, relToProject)));
} catch (err) {
- console.warn(`[content-filter] Failed to read nested ${name} at ${filePath}:`, err);
+ log.warn({ path: filePath, err }, `Failed to read nested ${name} at ${filePath}`);
}
}
}
@@ -1410,7 +1410,7 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
newRootPatterns.push(...patterns);
newIg.add(patterns);
} catch (err) {
- console.warn(`[content-filter] Failed to read ${name} at ${path}:`, err);
+ log.warn({ path, err }, `Failed to read ${name} at ${path}`);
}
}
@@ -1422,7 +1422,7 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
const patterns = parseIgnorePatterns(await readFileAsync(path, 'utf-8'));
newIg.add(patterns.map((p) => prefixPattern(p, contentRelPrefix)));
} catch (err) {
- console.warn(`[content-filter] Failed to read ${name} at ${path}:`, err);
+ log.warn({ path, err }, `Failed to read ${name} at ${path}`);
}
}
}
@@ -1581,7 +1581,7 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
refreshDirCount();
} catch (err) {
for (const [k, v] of prev) dirCount.set(k, v);
- getLogger('content-filter').warn(
+ log.warn(
{ err: err instanceof Error ? err : new Error(String(err)) },
'content-filter rebuildDirCount walk failed — retaining previous counts',
);
@@ -1589,7 +1589,6 @@ export async function createContentFilterAsync(opts: ContentFilterOptions): Prom
},
async rebuildIgnorePatterns(): Promise<RebuildResult> {
- const log = getLogger('content-filter');
const prevIg = ig;
const prevWatcherGlobs = watcherIgnoreGlobs;
const prevDirCount = new Map(dirCount);
diff --git a/packages/server/src/content/enrichment.ts b/packages/server/src/content/enrichment.ts
index 1e433bc79..eca3a7ff5 100644
--- a/packages/server/src/content/enrichment.ts
+++ b/packages/server/src/content/enrichment.ts
@@ -16,6 +16,7 @@ import type { Dirent } from 'node:fs';
import { readdir, readFile, stat } from 'node:fs/promises';
import { basename, relative, resolve } from 'node:path';
import { OK_DIR, parseFrontmatterRecord } from '@inkeep/open-knowledge-core';
+import { getLogger } from '../logger.ts';
import { resolveWithinRoot } from '../mcp/tools/path-safety.ts';
import { httpGet } from '../mcp/tools/shared.ts';
import { readFolderFrontmatter } from './nested-folder-rules.ts';
@@ -287,9 +288,9 @@ async function readFrontmatter(absPath: string): Promise<Record<string, unknown>
if (code !== 'ENOENT' && !fmReadWarnedPaths.has(absPath)) {
fmReadWarnedPaths.add(absPath);
const reason = err instanceof Error ? err.message : String(err);
- // eslint-disable-next-line no-console -- ad-hoc operator-facing diagnostic
- console.warn(
- `[ok-enrich] failed to read frontmatter at ${absPath} — enrichment degraded for this file. Reason: ${reason}`,
+ getLogger('enrichment').warn(
+ { path: absPath, reason },
+ `failed to read frontmatter at ${absPath} — enrichment degraded for this file. Reason: ${reason}`,
);
}
return null;
diff --git a/packages/server/src/content/nested-folder-rules.ts b/packages/server/src/content/nested-folder-rules.ts
index a3afc4a84..d32ebdd73 100644
--- a/packages/server/src/content/nested-folder-rules.ts
+++ b/packages/server/src/content/nested-folder-rules.ts
@@ -15,6 +15,7 @@
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { parse as parseYaml } from 'yaml';
+import { getLogger } from '../logger.ts';
/**
* Folder frontmatter — open shape. Any YAML-representable key is
@@ -98,9 +99,9 @@ function readFrontmatterYaml(absYamlPath: string): Record<string, unknown> | nul
if (!warnedPaths.has(absYamlPath)) {
warnedPaths.add(absYamlPath);
const reason = err instanceof Error ? err.message : String(err);
- // eslint-disable-next-line no-console -- ad-hoc operator-facing diagnostic
- console.warn(
- `[ok-folder-frontmatter] malformed YAML at ${absYamlPath} — folder metadata skipped. Fix the file or delete it. Reason: ${reason}`,
+ getLogger('folder-frontmatter').warn(
+ { path: absYamlPath, reason },
+ `malformed YAML at ${absYamlPath} — folder metadata skipped. Fix the file or delete it. Reason: ${reason}`,
);
}
return null;
diff --git a/packages/server/src/content/templates-resolver.ts b/packages/server/src/content/templates-resolver.ts
index 99627edb9..a272627b0 100644
--- a/packages/server/src/content/templates-resolver.ts
+++ b/packages/server/src/content/templates-resolver.ts
@@ -23,6 +23,7 @@
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { join, posix } from 'node:path';
import { parseTemplateFile } from '@inkeep/open-knowledge-core';
+import { getLogger } from '../logger.ts';
type TemplateScope = 'local' | 'inherited';
@@ -132,8 +133,9 @@ export function resolveProjectTemplates(projectDir: string): ProjectTemplatesRes
const folderRel = queue.shift() ?? '';
if (visited++ >= PROJECT_TEMPLATE_SCAN_CAP) {
truncated = true;
- console.warn(
- `[ok-templates] project scan hit the ${PROJECT_TEMPLATE_SCAN_CAP}-directory cap at ${projectDir}; deeper templates were not enumerated. Queue depth at break: ${queue.length}.`,
+ getLogger('templates').warn(
+ { projectDir, cap: PROJECT_TEMPLATE_SCAN_CAP, queueDepth: queue.length },
+ `project scan hit the ${PROJECT_TEMPLATE_SCAN_CAP}-directory cap at ${projectDir}; deeper templates were not enumerated. Queue depth at break: ${queue.length}.`,
);
break;
}
@@ -161,8 +163,9 @@ export function resolveProjectTemplates(projectDir: string): ProjectTemplatesRes
if (code !== 'ENOENT' && !templateMetaWarnedPaths.has(absDir)) {
templateMetaWarnedPaths.add(absDir);
const reason = err instanceof Error ? err.message : String(err);
- console.warn(
- `[ok-templates] failed to read directory ${absDir} during project scan — skipped. Reason: ${reason}`,
+ getLogger('templates').warn(
+ { dir: absDir, reason },
+ `failed to read directory ${absDir} during project scan — skipped. Reason: ${reason}`,
);
}
continue;
@@ -282,8 +285,9 @@ function readTemplateMeta(absPath: string): TemplateMeta {
if (code !== 'ENOENT' && !templateMetaWarnedPaths.has(absPath)) {
templateMetaWarnedPaths.add(absPath);
const reason = err instanceof Error ? err.message : String(err);
- console.warn(
- `[ok-templates] failed to read template at ${absPath} — metadata skipped. Reason: ${reason}`,
+ getLogger('templates').warn(
+ { path: absPath, reason },
+ `failed to read template at ${absPath} — metadata skipped. Reason: ${reason}`,
);
}
return {};
@@ -300,8 +304,9 @@ function readTemplateMeta(absPath: string): TemplateMeta {
// operator-facing diagnostic the previous YAML-parse path emitted.
if (typeof identity.title !== 'string' && !templateMetaWarnedPaths.has(absPath)) {
templateMetaWarnedPaths.add(absPath);
- console.warn(
- `[ok-templates] template at ${absPath} has no title — YAML may be malformed or the title is missing.`,
+ getLogger('templates').warn(
+ { path: absPath },
+ `template at ${absPath} has no title — YAML may be malformed or the title is missing.`,
);
}
const result: TemplateMeta = {};
diff --git a/packages/server/src/external-change.test.ts b/packages/server/src/external-change.test.ts
index e400c6ded..004c099d5 100644
--- a/packages/server/src/external-change.test.ts
+++ b/packages/server/src/external-change.test.ts
@@ -9,15 +9,17 @@
*
* Plus the factory wrapper's error-swallowing contract.
*/
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
+
import { Hocuspocus } from '@hocuspocus/server';
import {
BridgeInvariantViolationError,
BridgeMergeContentLossError,
stripFrontmatter,
} from '@inkeep/open-knowledge-core';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
import type * as Y from 'yjs';
import { applyExternalChange, createExternalChangeHandler } from './external-change.ts';
+import { getLogger } from './logger.ts';
import { getReconciledBase, setReconciledBase } from './persistence.ts';
type Conn = Awaited<ReturnType<Hocuspocus['openDirectConnection']>>;
@@ -272,9 +274,7 @@ describe('createExternalChangeHandler — error-swallowing factory', () => {
});
test('factory wrapper catches and logs when applyExternalChange throws', async () => {
- const errorSpy = mock(() => {});
- const originalError = console.error;
- console.error = errorSpy;
+ const errorSpy = vi.spyOn(getLogger('file-watcher'), 'error');
try {
const handler = createExternalChangeHandler(hp);
@@ -293,16 +293,16 @@ describe('createExternalChangeHandler — error-swallowing factory', () => {
await expect(handler(docName, '# Content\n')).resolves.toBeUndefined();
expect(errorSpy).toHaveBeenCalled();
- const callArgs = errorSpy.mock.calls[0];
- expect(callArgs[0]).toContain('Failed to apply external change');
- expect(callArgs[0]).toContain(docName);
+ const callArgs = errorSpy.mock.calls[0] ?? [];
+ expect(String(callArgs[1])).toContain('Failed to apply external change');
+ expect(String(callArgs[1])).toContain(docName);
expect(doc.getText('source').toString()).toBe(textBefore);
doc.getXmlFragment = originalGetXmlFragment;
await conn.disconnect();
} finally {
- console.error = originalError;
+ errorSpy.mockRestore();
}
});
@@ -311,9 +311,7 @@ describe('createExternalChangeHandler — error-swallowing factory', () => {
// OK_BRIDGE_THROW_ON_VIOLATION=1). Swallowing them here would silently
// subvert the test gate and let real bridge bugs land green. The wrapper
// must let them propagate.
- const errorSpy = mock(() => {});
- const originalError = console.error;
- console.error = errorSpy;
+ const errorSpy = vi.spyOn(getLogger('file-watcher'), 'error');
try {
const handler = createExternalChangeHandler(hp);
@@ -347,7 +345,7 @@ describe('createExternalChangeHandler — error-swallowing factory', () => {
doc.getXmlFragment = originalGetXmlFragment;
await conn.disconnect();
} finally {
- console.error = originalError;
+ errorSpy.mockRestore();
}
});
@@ -356,7 +354,7 @@ describe('createExternalChangeHandler — error-swallowing factory', () => {
// signals from Path B must reach the test runner under
// OK_RETHROW_BRIDGE_LOSS=1 / NODE_ENV=test, not get swallowed by the
// dev-plugin file-watcher wrapper.
- const errorSpy = mock(() => {});
+ const errorSpy = vi.fn(() => {});
const originalError = console.error;
console.error = errorSpy;
diff --git a/packages/server/src/external-change.ts b/packages/server/src/external-change.ts
index fda5b12c9..a567a0913 100644
--- a/packages/server/src/external-change.ts
+++ b/packages/server/src/external-change.ts
@@ -250,7 +250,10 @@ export function createExternalChangeHandler(
// overwrite the external edit with the unadvanced Y.Doc bytes, so the
// failure mode is silent data-loss-on-disk-edit unless surfaced here.
incrementExternalChangeHandlerErrors();
- console.error(`[file-watcher] Failed to apply external change for ${docName}:`, err);
+ getLogger('file-watcher').error(
+ { docName, err },
+ `Failed to apply external change for ${docName}`,
+ );
}
};
}
diff --git a/packages/server/src/file-watcher.ts b/packages/server/src/file-watcher.ts
index 6f7d91a85..c830b9b01 100644
--- a/packages/server/src/file-watcher.ts
+++ b/packages/server/src/file-watcher.ts
@@ -35,6 +35,8 @@ import { isWithinContentDir } from './persistence.ts';
import { containsConflictMarkers } from './reconciliation.ts';
import { getMeter, withSpan } from './telemetry.ts';
+const log = getLogger('file-watcher');
+
/** Subscription handle compatible with both @parcel/watcher and chokidar backends. */
export interface AsyncSubscription {
unsubscribe(): Promise<void>;
@@ -345,8 +347,9 @@ function eventEscapesContentDir(rawPath: string, contentDir: string): boolean {
} catch (e) {
const code = (e as NodeJS.ErrnoException).code;
if (code === 'ENOENT') return false; // deleted between event and check
- console.warn(
- `[file-watcher] lstat failed for escape check on ${rawPath} (${code}), dropping event`,
+ log.warn(
+ { path: rawPath, code },
+ `lstat failed for escape check on ${rawPath} (${code}), dropping event`,
);
return true; // fail closed on unexpected errors
}
@@ -357,8 +360,9 @@ function eventEscapesContentDir(rawPath: string, contentDir: string): boolean {
} catch (e) {
const code = (e as NodeJS.ErrnoException).code;
if (code !== 'ENOENT' && code !== 'ELOOP') {
- console.warn(
- `[file-watcher] realpath failed for escape check on ${rawPath} (${code}), dropping event`,
+ log.warn(
+ { path: rawPath, code },
+ `realpath failed for escape check on ${rawPath} (${code}), dropping event`,
);
}
return true;
@@ -507,7 +511,7 @@ export async function classifyEvents(
createContents.set(event.path, await readFile(event.path, 'utf-8'));
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
- console.warn(`[file-watcher] Failed to read ${event.path}:`, e);
+ log.warn({ path: event.path, err: e }, `Failed to read ${event.path}`);
}
}
}
@@ -516,7 +520,7 @@ export async function classifyEvents(
updateContents.set(event.path, await readFile(event.path, 'utf-8'));
} catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') {
- console.warn(`[file-watcher] Failed to read ${event.path}:`, e);
+ log.warn({ path: event.path, err: e }, `Failed to read ${event.path}`);
}
}
}
@@ -533,7 +537,7 @@ export async function classifyEvents(
} catch (e) {
const code = (e as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
- console.warn(`[file-watcher] resolveDocName lstat failed for ${rawPath}:`, e);
+ log.warn({ path: rawPath, err: e }, `resolveDocName lstat failed for ${rawPath}`);
}
if (aliasMap.has(raw)) {
aliasMap.delete(raw);
@@ -555,7 +559,7 @@ export async function classifyEvents(
} catch (e) {
const code = (e as NodeJS.ErrnoException).code;
if (code !== 'ENOENT' && code !== 'ELOOP') {
- console.warn(`[file-watcher] resolveDocName realpath failed for ${rawPath}:`, e);
+ log.warn({ path: rawPath, err: e }, `resolveDocName realpath failed for ${rawPath}`);
}
aliasMap.delete(raw);
return raw;
@@ -717,7 +721,7 @@ async function seedLastKnownHashes(
} catch (e) {
const code = (e as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
- console.warn(`[file-watcher] Failed to lstat ${fullPath}, skipping:`, e);
+ log.warn({ path: fullPath, err: e }, `Failed to lstat ${fullPath}, skipping`);
}
continue;
}
@@ -729,15 +733,18 @@ async function seedLastKnownHashes(
} catch (e) {
const code = (e as NodeJS.ErrnoException).code;
if (code === 'ENOENT' || code === 'ELOOP') {
- console.warn(`[file-watcher] Broken/cyclic symlink at ${fullPath}, skipping`);
+ log.warn({ path: fullPath, code }, `Broken/cyclic symlink at ${fullPath}, skipping`);
} else {
- console.warn(`[file-watcher] Failed to resolve symlink ${fullPath}:`, e);
+ log.warn({ path: fullPath, err: e }, `Failed to resolve symlink ${fullPath}`);
}
continue;
}
if (!isWithinContentDir(canonical, contentDir)) {
- console.warn(`[file-watcher] Symlink escape: ${fullPath} → ${canonical}, skipping`);
+ log.warn(
+ { path: fullPath, canonical },
+ `Symlink escape: ${fullPath} → ${canonical}, skipping`,
+ );
continue;
}
@@ -809,8 +816,9 @@ async function seedLastKnownHashes(
if (ext) {
const reg = registerDocExtension(canonicalDocName, ext);
if (reg.shadowed) {
- console.warn(
- `[file-watcher] docName "${canonicalDocName}" has both "${reg.effective}" and "${reg.shadowed}" on disk; "${reg.effective}" wins (industry convention). Rename or delete one to disambiguate.`,
+ log.warn(
+ { docName: canonicalDocName, effective: reg.effective, shadowed: reg.shadowed },
+ `docName "${canonicalDocName}" has both "${reg.effective}" and "${reg.shadowed}" on disk; "${reg.effective}" wins (industry convention). Rename or delete one to disambiguate.`,
);
if (!reg.changed) continue;
}
@@ -827,7 +835,7 @@ async function seedLastKnownHashes(
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
- console.warn(`[file-watcher] Failed to seed hash for ${canonical}:`, err);
+ log.warn({ path: canonical, err }, `Failed to seed hash for ${canonical}`);
}
}
} else if (canonStat.isFile()) {
@@ -857,7 +865,7 @@ async function seedLastKnownHashes(
});
}
} catch (e) {
- console.warn(`[file-watcher] Failed to stat symlink target ${canonical}:`, e);
+ log.warn({ path: canonical, err: e }, `Failed to stat symlink target ${canonical}`);
}
} else if (lst.isDirectory()) {
const relPath = contentRelativePath(contentDir, fullPath);
@@ -892,8 +900,9 @@ async function seedLastKnownHashes(
if (ext) {
const reg = registerDocExtension(docName, ext);
if (reg.shadowed) {
- console.warn(
- `[file-watcher] docName "${docName}" has both "${reg.effective}" and "${reg.shadowed}" on disk; "${reg.effective}" wins (industry convention). Rename or delete one to disambiguate.`,
+ log.warn(
+ { docName, effective: reg.effective, shadowed: reg.shadowed },
+ `docName "${docName}" has both "${reg.effective}" and "${reg.shadowed}" on disk; "${reg.effective}" wins (industry convention). Rename or delete one to disambiguate.`,
);
// When .md is shadowed by an already-registered .mdx (or vice-versa),
// skip registering this file in the index — the winning entry remains.
@@ -912,11 +921,12 @@ async function seedLastKnownHashes(
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code === 'EACCES') {
- console.warn(
- `[file-watcher] Permission denied reading ${fullPath}, file excluded from index`,
+ log.warn(
+ { path: fullPath, code },
+ `Permission denied reading ${fullPath}, file excluded from index`,
);
} else if (code !== 'ENOENT') {
- console.warn(`[file-watcher] Failed to seed hash for ${fullPath}:`, err);
+ log.warn({ path: fullPath, err }, `Failed to seed hash for ${fullPath}`);
}
}
} else if (lst.isFile()) {
@@ -947,7 +957,7 @@ async function seedLastKnownHashes(
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
- console.warn(`[file-watcher] Failed to read directory ${dir}:`, err);
+ log.warn({ dir, err }, `Failed to read directory ${dir}`);
}
}
}
@@ -1091,7 +1101,7 @@ function updateFolderIndexFromRawEvents(
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
- console.warn(`[file-watcher] folder lstat failed for ${raw.path} (${code})`);
+ log.warn({ path: raw.path, code }, `folder lstat failed for ${raw.path} (${code})`);
}
continue;
}
@@ -1109,7 +1119,10 @@ function updateFolderIndexFromRawEvents(
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
- console.warn(`[file-watcher] folder symlink resolve failed for ${raw.path} (${code})`);
+ log.warn(
+ { path: raw.path, code },
+ `folder symlink resolve failed for ${raw.path} (${code})`,
+ );
}
folderStat = null;
}
@@ -1166,7 +1179,7 @@ function scanForUntrackedSubfolders(
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
- console.warn(`[file-watcher] folder rescan readdir failed for ${dir} (${code})`);
+ log.warn({ dir, code }, `folder rescan readdir failed for ${dir} (${code})`);
}
continue;
}
@@ -1197,7 +1210,10 @@ function scanForUntrackedSubfolders(
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
- console.warn(`[file-watcher] folder rescan lstat failed for ${fullPath} (${code})`);
+ log.warn(
+ { path: fullPath, code },
+ `folder rescan lstat failed for ${fullPath} (${code})`,
+ );
}
continue;
}
@@ -1239,7 +1255,7 @@ export async function handleRawEvents(
// content as a contentDir-scoped DiskEvent.
const safeEvents = rawEvents.filter((e) => {
if (!eventEscapesContentDir(e.path, contentDir)) return true;
- console.warn(`[file-watcher] Symlink escape: ${e.path}, dropping ${e.type} event`);
+ log.warn({ path: e.path, type: e.type }, `Symlink escape: ${e.path}, dropping ${e.type} event`);
return false;
});
@@ -1272,7 +1288,7 @@ export async function handleRawEvents(
.filter((path) => !eventEscapesContentDir(path, contentDir))
.map((path) => ({ type: 'create' as const, path }));
if (rescuedCreates.length > 0) {
- getLogger('file-watcher').debug(
+ log.debug(
{
count: rescuedCreates.length,
paths: rescuedCreates.map((e) => toPosix(relative(contentDir, e.path))),
@@ -1331,8 +1347,9 @@ export async function handleRawEvents(
} catch (e) {
const code = (e as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
- console.warn(
- `[file-watcher] realpathSync failed for self-write check on ${event.path} (${code})`,
+ log.warn(
+ { path: event.path, code },
+ `realpathSync failed for self-write check on ${event.path} (${code})`,
);
}
}
@@ -1345,8 +1362,9 @@ export async function handleRawEvents(
} catch (e) {
const code = (e as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
- console.warn(
- `[file-watcher] realpathSync failed for self-write check on ${event.newPath} (${code})`,
+ log.warn(
+ { path: event.newPath, code },
+ `realpathSync failed for self-write check on ${event.newPath} (${code})`,
);
}
}
@@ -1388,7 +1406,7 @@ export async function handleRawEvents(
}
if (isSelf) {
- getLogger('file-watcher').debug(
+ log.debug(
{
kind: event.kind,
path: event.kind === 'rename' ? event.newPath : event.path,
@@ -1400,7 +1418,7 @@ export async function handleRawEvents(
continue;
}
- getLogger('file-watcher').debug(
+ log.debug(
{
kind: event.kind,
path: event.kind === 'rename' ? event.newPath : event.path,
@@ -1425,10 +1443,7 @@ export async function handleRawEvents(
}
for (const event of folderEvents) {
- getLogger('file-watcher').debug(
- { kind: event.kind, path: event.path },
- `[file-watcher] Dispatching: ${event.kind}`,
- );
+ log.debug({ kind: event.kind, path: event.path }, `[file-watcher] Dispatching: ${event.kind}`);
_fileWatcherEventsCounter().add(1, { 'disk.kind': event.kind, self: false });
await withSpan(
'file_watcher.process_event',
@@ -1494,7 +1509,7 @@ export async function handleRawEvents(
} catch (e) {
const code = (e as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
- console.warn(`[file-watcher] file-event lstat failed for ${raw.path} (${code})`);
+ log.warn({ path: raw.path, code }, `file-event lstat failed for ${raw.path} (${code})`);
}
continue;
}
@@ -1550,7 +1565,7 @@ async function startParcelWatcher(
// isn't bundled, so we fall back to chokidar. The `watching … backend:
// chokidar` info line records the outcome — this is debug-only so the
// terminal stays clean (it's a routine fallback, not an error).
- getLogger('file-watcher').debug(
+ log.debug(
{ err: err instanceof Error ? err.message : String(err) },
'[file-watcher] @parcel/watcher import failed; falling back to chokidar',
);
@@ -1566,7 +1581,7 @@ async function startParcelWatcher(
contentDir,
async (err, events) => {
if (err) {
- console.error('[file-watcher]', err);
+ log.error({ err }, 'parcel watcher callback error');
return;
}
try {
@@ -1584,7 +1599,7 @@ async function startParcelWatcher(
// `getFileIndex()` call rebuilds the cached snapshot.
onAfterMutation();
} catch (handleErr) {
- console.error('[file-watcher] parcel batch error:', handleErr);
+ log.error({ err: handleErr }, 'parcel batch error');
}
},
subscribeOpts,
@@ -1592,7 +1607,7 @@ async function startParcelWatcher(
return subscription;
} catch (err) {
- console.warn('[file-watcher] @parcel/watcher subscribe failed, falling back to chokidar:', err);
+ log.warn({ err }, '@parcel/watcher subscribe failed, falling back to chokidar');
return null;
}
}
@@ -1629,7 +1644,7 @@ async function startChokidarWatcher(
: undefined,
});
- watcher.on('error', (err) => console.error('[file-watcher] chokidar error:', err));
+ watcher.on('error', (err) => log.error({ err }, 'chokidar error'));
// Batch chokidar events to match @parcel/watcher's coalescing behavior.
// Without batching, a file rename (mv old.md new.md) produces separate
@@ -1655,7 +1670,7 @@ async function startChokidarWatcher(
aliasMap,
)
.then(onAfterMutation)
- .catch((err) => console.error('[file-watcher] chokidar batch error:', err));
+ .catch((err) => log.error({ err }, 'chokidar batch error'));
}, BATCH_WINDOW_MS);
}
@@ -1772,7 +1787,7 @@ export async function startWatcher(
const originalUnsubscribe = subscription.unsubscribe.bind(subscription);
- getLogger('file-watcher').info({ contentDir, backend }, 'watching for external .md changes');
+ log.info({ contentDir, backend }, 'watching for external .md changes');
return {
async unsubscribe() {
diff --git a/packages/server/src/git-branch-info.ts b/packages/server/src/git-branch-info.ts
index e9fb36771..7b8a4ac00 100644
--- a/packages/server/src/git-branch-info.ts
+++ b/packages/server/src/git-branch-info.ts
@@ -11,6 +11,7 @@ import { isValidBranchName } from '@inkeep/open-knowledge-core';
import { truncateError } from './error-format.ts';
import { type DirtyOverlapResult, dirtyFilesOverlapWith } from './git-dirty.ts';
import { createGitInstance } from './git-handle.ts';
+import { getLogger } from './logger.ts';
// Re-export from core so existing callers (`api-extension.ts`,
// `git-branch-info.test.ts`) keep their import paths. Single source of
@@ -186,9 +187,9 @@ export async function computeBranchInfo(
// conflict signal is preferable to crashing the whole branch-info
// endpoint when only one of its four probes fails for an unrelated
// reason (the other three may still be intact).
- const truncated = truncateError(err);
- console.warn(
- `[git-branch-info] action=dirty-overlap-failed branch=${targetBranch} error=${truncated}`,
+ getLogger('git-branch-info').warn(
+ { branch: targetBranch, err },
+ `action=dirty-overlap-failed branch=${targetBranch} error=${truncateError(err)}`,
);
return { conflicts: false, files: [] };
},
diff --git a/packages/server/src/git-checkout.ts b/packages/server/src/git-checkout.ts
index c9609c6c4..35ff57acf 100644
--- a/packages/server/src/git-checkout.ts
+++ b/packages/server/src/git-checkout.ts
@@ -19,6 +19,9 @@ import { type CheckoutFailureReason, isBranchNotFoundGitError } from '@inkeep/op
import { truncateError } from './error-format.ts';
import { dirtyFilesOverlapWith } from './git-dirty.ts';
import { createGitInstance } from './git-handle.ts';
+import { getLogger } from './logger.ts';
+
+const log = getLogger('git-checkout');
/**
* Block timeout for the fast-forward fetches. These run inside `withParentLock`,
@@ -199,8 +202,9 @@ export async function runCheckoutFlow(
// `checkout-failed` catch-all without functional regression.
const heldElsewhere = isBranchInOtherWorktreeError(err);
if (heldElsewhere.held) {
- console.warn(
- `[git-checkout] reason=branch-in-other-worktree branch=${branch} held_at=${heldElsewhere.path}`,
+ log.warn(
+ { branch, heldAt: heldElsewhere.path },
+ `reason=branch-in-other-worktree branch=${branch} held_at=${heldElsewhere.path}`,
);
return {
ok: false,
@@ -212,8 +216,10 @@ export async function runCheckoutFlow(
// gates (rev-parse, fetch, dirty-overlap) all passed, so the most likely
// causes are lock contention, filesystem permissions, or partial merge
// state — which are the hardest to reproduce without a stderr breadcrumb.
- const truncated = truncateError(err);
- console.warn(`[git-checkout] action=checkout-failed branch=${branch} error=${truncated}`);
+ log.warn(
+ { branch, err },
+ `action=checkout-failed branch=${branch} error=${truncateError(err)}`,
+ );
return { ok: false, reason: 'checkout-failed' };
}
}
@@ -274,8 +280,10 @@ export async function fastForwardBranchToOrigin(
try {
await git.raw(['fetch', 'origin', branch]);
} catch (err) {
- const truncated = truncateError(err);
- console.warn(`[git-checkout] action=ff-fetch-failed branch=${branch} error=${truncated}`);
+ log.warn(
+ { branch, err },
+ `action=ff-fetch-failed branch=${branch} error=${truncateError(err)}`,
+ );
return 'unavailable';
}
@@ -301,8 +309,10 @@ export async function fastForwardBranchToOrigin(
try {
await git.raw(['fetch', 'origin', `${branch}:${branch}`]);
} catch (err) {
- const truncated = truncateError(err);
- console.warn(`[git-checkout] action=ff-advance-failed branch=${branch} error=${truncated}`);
+ log.warn(
+ { branch, err },
+ `action=ff-advance-failed branch=${branch} error=${truncateError(err)}`,
+ );
return 'unavailable';
}
const after = await revParse(`refs/heads/${branch}`);
diff --git a/packages/server/src/handoff-api.ts b/packages/server/src/handoff-api.ts
index 3884d7e72..da0eb33ef 100644
--- a/packages/server/src/handoff-api.ts
+++ b/packages/server/src/handoff-api.ts
@@ -26,6 +26,7 @@ import { InstalledAgentsSuccessSchema } from '@inkeep/open-knowledge-core';
import { withHiddenWindowsConsole } from './child-process-windows-hide.ts';
import { errorResponse } from './http/error-response.ts';
import { successResponse } from './http/success-response.ts';
+import { getLogger } from './logger.ts';
export const INSTALLED_AGENTS_SCHEMES = ['claude', 'codex', 'cursor'] as const;
export type InstalledAgentScheme = (typeof INSTALLED_AGENTS_SCHEMES)[number];
@@ -226,7 +227,7 @@ export async function handleInstalledAgents(
handler: 'installed-agents',
});
} catch (e) {
- console.error('[installed-agents]', e);
+ getLogger('handoff').error({ err: e }, '[installed-agents] handler failed');
errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Internal server error.', {
handler: 'installed-agents',
cause: e,
diff --git a/packages/server/src/head-watcher.ts b/packages/server/src/head-watcher.ts
index e79a76075..db7e15e35 100644
--- a/packages/server/src/head-watcher.ts
+++ b/packages/server/src/head-watcher.ts
@@ -13,6 +13,8 @@ import { resolve } from 'node:path';
import { resolveGitDir } from '@inkeep/open-knowledge-core/shadow-repo-layout';
import { getLogger } from './logger.ts';
+const log = getLogger('head-watcher');
+
// ─── Types ───────────────────────────────────────────────────────────────────
type BatchKind = 'within-branch' | 'cross-branch' | 'detached-head';
@@ -131,7 +133,7 @@ async function tryStartParcelHeadWatcher(
try {
parcel = await import('@parcel/watcher');
} catch (err) {
- getLogger('head-watcher').debug(
+ log.debug(
{ err: err instanceof Error ? err.message : String(err) },
'[head-watcher] @parcel/watcher unavailable; falling back to chokidar',
);
@@ -140,14 +142,14 @@ async function tryStartParcelHeadWatcher(
try {
const subscription = await parcel.subscribe(gitDir, (err, events) => {
if (err) {
- getLogger('head-watcher').warn({ err }, '[head-watcher] parcel subscription error');
+ log.warn({ err }, '[head-watcher] parcel subscription error');
return;
}
for (const event of events) dispatch(event.path);
});
return () => subscription.unsubscribe();
} catch (err) {
- getLogger('head-watcher').debug(
+ log.debug(
{ err: err instanceof Error ? err.message : String(err) },
'[head-watcher] @parcel/watcher subscribe failed; falling back to chokidar',
);
@@ -180,7 +182,7 @@ async function startChokidarHeadWatcher(
// the server. Log + swallow: a HEAD-watch hiccup must not take the process
// down; branch-switch detection simply pauses.
watcher.on('error', (err) => {
- getLogger('head-watcher').warn({ err }, '[head-watcher] chokidar watcher error');
+ log.warn({ err }, '[head-watcher] chokidar watcher error');
});
return () => watcher.close();
}
@@ -259,7 +261,7 @@ export async function startHeadWatcher(
newBranch,
});
} catch (e) {
- console.error('[head-watcher] onBatchEnd callback failed:', e);
+ log.error({ err: e }, 'onBatchEnd callback failed');
} finally {
// Set inBatch = false AFTER the async callback completes
// so new file events stay buffered during branch-switch orchestration
@@ -294,7 +296,7 @@ export async function startHeadWatcher(
try {
await onBatchBegin({ trigger });
} catch (e) {
- console.error('[head-watcher] onBatchBegin callback failed:', e);
+ log.error({ err: e }, 'onBatchBegin callback failed');
}
})();
beginInFlight = beginPromise;
@@ -340,7 +342,7 @@ export async function startHeadWatcher(
oldHead = readHeadSha(gitDir);
lastKnownBranch = readBranchFromHead(gitDir);
- getLogger('head-watcher').info({ gitDir, backend }, 'watching for HEAD changes');
+ log.info({ gitDir, backend }, 'watching for HEAD changes');
return {
unsubscribe: async () => {
diff --git a/packages/server/src/init-project.test.ts b/packages/server/src/init-project.test.ts
index 20432c60a..67679a0ee 100644
--- a/packages/server/src/init-project.test.ts
+++ b/packages/server/src/init-project.test.ts
@@ -1,4 +1,3 @@
-import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import {
existsSync,
lstatSync,
@@ -15,6 +14,7 @@ import {
PROJECT_SKILL_PROJECTION_IGNORE_PATHS,
RESERVED_PROJECT_SKILL_NAME,
} from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
buildConfigYmlContent,
ensureProjectSkillGitignore,
@@ -304,10 +304,13 @@ describe.runIf(COMMITTED_OK_GITIGNORE !== null)(
},
);
-// Drift guard: the committed project-root `.okignore` in this repo MUST stay
-// in sync with `OK_OKIGNORE_TEMPLATE`.
+// Drift guard: the committed project-root `.okignore` in this repo MUST keep
+// `OK_OKIGNORE_TEMPLATE` as its opening block, byte-for-byte. The repo file
+// may append temporary repo-local exclusions BELOW the scaffold block (those
+// are dogfood-only and must never be folded into the template — the scaffold
+// ships to every new user project).
describe.runIf(COMMITTED_OKIGNORE !== null)('committed .okignore matches scaffold output', () => {
- it('matches OK_OKIGNORE_TEMPLATE byte-for-byte', () => {
+ it('starts with OK_OKIGNORE_TEMPLATE byte-for-byte', () => {
const tmp = resolve(
tmpdir(),
`okignore-mirror-${Date.now()}-${Math.random().toString(36).slice(2)}`,
@@ -318,7 +321,11 @@ describe.runIf(COMMITTED_OKIGNORE !== null)('committed .okignore matches scaffol
const scaffolded = readFileSync(join(tmp, '.okignore'), 'utf-8');
expect(scaffolded).toBe(OK_OKIGNORE_TEMPLATE);
const committed = readFileSync(COMMITTED_OKIGNORE as string, 'utf-8');
- expect(committed).toBe(OK_OKIGNORE_TEMPLATE);
+ expect(
+ committed.startsWith(OK_OKIGNORE_TEMPLATE),
+ `committed .okignore (${COMMITTED_OKIGNORE}) must start with OK_OKIGNORE_TEMPLATE ` +
+ 'byte-for-byte; repo-local exclusions may only be appended below the scaffold block',
+ ).toBe(true);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
diff --git a/packages/server/src/live-derived-index.test.ts b/packages/server/src/live-derived-index.test.ts
index 8ff32bb20..8f1b719be 100644
--- a/packages/server/src/live-derived-index.test.ts
+++ b/packages/server/src/live-derived-index.test.ts
@@ -1,9 +1,10 @@
-import { beforeEach, describe, expect, mock, test } from 'bun:test';
import { setTimeout as wait } from 'node:timers/promises';
import { Hocuspocus } from '@hocuspocus/server';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
import type * as Y from 'yjs';
import { applyExternalChange } from './external-change.ts';
import { createLiveDerivedIndexExtension } from './live-derived-index.ts';
+import { getLogger } from './logger.ts';
type Conn = Awaited<ReturnType<Hocuspocus['openDirectConnection']>>;
@@ -42,8 +43,8 @@ describe('createLiveDerivedIndexExtension', () => {
});
test('skips file-watcher origin transactions', async () => {
- const updateDocumentFromMarkdown = mock(() => {});
- const signalChannel = mock(() => {});
+ const updateDocumentFromMarkdown = vi.fn(() => {});
+ const signalChannel = vi.fn(() => {});
const extension = createLiveDerivedIndexExtension({
backlinkIndex: { updateDocumentFromMarkdown } as unknown as never,
debounceMs: 5,
@@ -67,8 +68,8 @@ describe('createLiveDerivedIndexExtension', () => {
});
test('debounces rapid changes to a single update and preserves frontmatter', async () => {
- const updateDocumentFromMarkdown = mock(() => {});
- const signalChannel = mock(() => {});
+ const updateDocumentFromMarkdown = vi.fn(() => {});
+ const signalChannel = vi.fn(() => {});
const extension = createLiveDerivedIndexExtension({
backlinkIndex: { updateDocumentFromMarkdown } as unknown as never,
debounceMs: 5,
@@ -99,9 +100,9 @@ describe('createLiveDerivedIndexExtension', () => {
});
test('feeds tagIndex with the same markdown and signals the tags channel', async () => {
- const updateBacklink = mock(() => {});
- const updateTag = mock(() => {});
- const signalChannel = mock(() => {});
+ const updateBacklink = vi.fn(() => {});
+ const updateTag = vi.fn(() => {});
+ const signalChannel = vi.fn(() => {});
const extension = createLiveDerivedIndexExtension({
backlinkIndex: { updateDocumentFromMarkdown: updateBacklink } as unknown as never,
tagIndex: { updateDocumentFromMarkdown: updateTag } as unknown as never,
@@ -128,7 +129,7 @@ describe('createLiveDerivedIndexExtension', () => {
});
test('beforeUnloadDocument cancels pending timers', async () => {
- const updateDocumentFromMarkdown = mock(() => {});
+ const updateDocumentFromMarkdown = vi.fn(() => {});
const extension = createLiveDerivedIndexExtension({
backlinkIndex: { updateDocumentFromMarkdown } as unknown as never,
debounceMs: 20,
@@ -155,7 +156,7 @@ describe('createLiveDerivedIndexExtension', () => {
});
test('onDestroy clears pending timers across documents', async () => {
- const updateDocumentFromMarkdown = mock(() => {});
+ const updateDocumentFromMarkdown = vi.fn(() => {});
const extension = createLiveDerivedIndexExtension({
backlinkIndex: { updateDocumentFromMarkdown } as unknown as never,
debounceMs: 20,
@@ -197,7 +198,7 @@ describe('createLiveDerivedIndexExtension', () => {
// serializer never emits them back). Under contract, body source is
// `Y.Text('source').toString()` — CRLF survives byte-equal. Discriminating
// because CRLF is not preserved through parse → serialize (parser strips).
- const updateDocumentFromMarkdown = mock(() => {});
+ const updateDocumentFromMarkdown = vi.fn(() => {});
const extension = createLiveDerivedIndexExtension({
backlinkIndex: { updateDocumentFromMarkdown } as unknown as never,
debounceMs: 5,
@@ -233,7 +234,7 @@ describe('createLiveDerivedIndexExtension', () => {
// doc starting with `---\n# H\n` would round-trip through
// serialize(fragment) as `***\n\n# H\n`. Under contract, ytext keeps
// the user's typed `---\n` byte-equal — discriminating.
- const updateDocumentFromMarkdown = mock(() => {});
+ const updateDocumentFromMarkdown = vi.fn(() => {});
const extension = createLiveDerivedIndexExtension({
backlinkIndex: { updateDocumentFromMarkdown } as unknown as never,
debounceMs: 5,
@@ -263,7 +264,7 @@ describe('createLiveDerivedIndexExtension', () => {
// paths in steady state. It still validates the spec acceptance: the
// SNIPPET CONTENT (what consumers see) reflects what the user typed.
// '<https://x>' in snippet text, not '[https://x](https://x)'.
- const updateDocumentFromMarkdown = mock(() => {});
+ const updateDocumentFromMarkdown = vi.fn(() => {});
const extension = createLiveDerivedIndexExtension({
backlinkIndex: { updateDocumentFromMarkdown } as unknown as never,
debounceMs: 5,
@@ -288,10 +289,10 @@ describe('createLiveDerivedIndexExtension', () => {
});
test('logs and swallows callback errors', async () => {
- const updateDocumentFromMarkdown = mock(() => {
+ const updateDocumentFromMarkdown = vi.fn(() => {
throw new Error('boom');
});
- const signalChannel = mock(() => {});
+ const signalChannel = vi.fn(() => {});
const extension = createLiveDerivedIndexExtension({
backlinkIndex: { updateDocumentFromMarkdown } as unknown as never,
debounceMs: 5,
@@ -299,9 +300,7 @@ describe('createLiveDerivedIndexExtension', () => {
});
const conn = await hp.openDirectConnection('error-doc');
const doc = getDoc(conn);
- const originalError = console.error;
- const errorSpy = mock(() => {});
- console.error = errorSpy;
+ const errorSpy = vi.spyOn(getLogger('live-derived-index'), 'error');
try {
applyExternalChange(hp, 'error-doc', '# Error\n');
@@ -316,11 +315,11 @@ describe('createLiveDerivedIndexExtension', () => {
expect(updateDocumentFromMarkdown).toHaveBeenCalledTimes(1);
expect(signalChannel).not.toHaveBeenCalled();
expect(errorSpy).toHaveBeenCalled();
- expect(errorSpy.mock.calls[0]?.[0]).toContain(
- '[live-derived-index] Failed to update derived views for error-doc:',
+ expect(String(errorSpy.mock.calls[0]?.[1])).toContain(
+ 'Failed to update derived views for error-doc',
);
} finally {
- console.error = originalError;
+ errorSpy.mockRestore();
await conn.disconnect();
}
});
diff --git a/packages/server/src/live-derived-index.ts b/packages/server/src/live-derived-index.ts
index 339c53729..8014f4c64 100644
--- a/packages/server/src/live-derived-index.ts
+++ b/packages/server/src/live-derived-index.ts
@@ -1,6 +1,7 @@
import type { Document, Extension } from '@hocuspocus/server';
import type { BacklinkIndex } from './backlink-index.ts';
import { isLinkIndexExcludedDoc } from './cc1-broadcast.ts';
+import { getLogger } from './logger.ts';
import type { TagIndex } from './tag-index.ts';
export const LIVE_DERIVED_INDEX_DEBOUNCE_MS = 100;
@@ -71,7 +72,10 @@ export function createLiveDerivedIndexExtension(options: LiveDerivedIndexOptions
signalChannel?.('tags');
}
} catch (err) {
- console.error(`[live-derived-index] Failed to update derived views for ${docName}:`, err);
+ getLogger('live-derived-index').error(
+ { docName, err },
+ `Failed to update derived views for ${docName}`,
+ );
}
}, debounceMs),
);
diff --git a/packages/server/src/local-op-security.ts b/packages/server/src/local-op-security.ts
index 9fd76bceb..ad9521586 100644
--- a/packages/server/src/local-op-security.ts
+++ b/packages/server/src/local-op-security.ts
@@ -16,6 +16,9 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
import { homedir } from 'node:os';
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { errorResponse } from './http/error-response.ts';
+import { getLogger } from './logger.ts';
+
+const log = getLogger('local-op-security');
// ─── Protocol checks ─────────────────────────────────────────────────────────
@@ -73,13 +76,14 @@ function ancestorChainHasSymlink(start: string, root: string): boolean {
stats = lstatSync(cursor);
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
- console.warn(
- `[local-op-security] ancestorChainHasSymlink: lstat failed on ${cursor} (${code ?? 'unknown'}); treating as symlink (fail-closed)`,
+ log.warn(
+ { path: cursor, code: code ?? 'unknown' },
+ `ancestorChainHasSymlink: lstat failed on ${cursor} (${code ?? 'unknown'}); treating as symlink (fail-closed)`,
);
return true;
}
if (stats.isSymbolicLink()) {
- console.warn(`[local-op-security] ancestorChainHasSymlink: symlink detected at ${cursor}`);
+ log.warn({ path: cursor }, `ancestorChainHasSymlink: symlink detected at ${cursor}`);
return true;
}
cursor = dirname(cursor);
@@ -100,8 +104,9 @@ export function isPathWithinHome(dirPath: string, home: string): boolean {
realHome = realpathSync(home);
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
- console.warn(
- `[local-op-security] realpath failed on home dir ${home} (${code ?? 'unknown'}); rejecting all paths`,
+ log.warn(
+ { path: home, code: code ?? 'unknown' },
+ `realpath failed on home dir ${home} (${code ?? 'unknown'}); rejecting all paths`,
);
return false;
}
@@ -117,8 +122,9 @@ export function isPathWithinHome(dirPath: string, home: string): boolean {
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
- console.warn(
- `[local-op-security] lstat error at ${current} (${code ?? 'unknown'}); rejecting`,
+ log.warn(
+ { path: current, code: code ?? 'unknown' },
+ `lstat error at ${current} (${code ?? 'unknown'}); rejecting`,
);
return false;
}
@@ -141,25 +147,29 @@ export function isPathWithinHome(dirPath: string, home: string): boolean {
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (stats.isSymbolicLink()) {
- console.warn(
- `[local-op-security] realpath failed on symlink leaf at ${current} (${code ?? 'unknown'}); rejecting`,
+ log.warn(
+ { path: current, code: code ?? 'unknown' },
+ `realpath failed on symlink leaf at ${current} (${code ?? 'unknown'}); rejecting`,
);
return false;
}
if (code === 'EPERM' || code === 'EACCES') {
if (ancestorChainHasSymlink(current, home)) {
- console.warn(
- `[local-op-security] EPERM accept-branch refused at ${current}: symlinked ancestor in chain; rejecting`,
+ log.warn(
+ { path: current },
+ `EPERM accept-branch refused at ${current}: symlinked ancestor in chain; rejecting`,
);
return false;
}
- console.warn(
- `[local-op-security] realpath denied on non-symlink leaf at ${current} (${code ?? 'unknown'}); trusting lexical path (TCC-class)`,
+ log.warn(
+ { path: current, code: code ?? 'unknown' },
+ `realpath denied on non-symlink leaf at ${current} (${code ?? 'unknown'}); trusting lexical path (TCC-class)`,
);
resolvedCurrent = current;
} else {
- console.warn(
- `[local-op-security] realpath failed on non-symlink leaf at ${current} (${code ?? 'unknown'}); rejecting`,
+ log.warn(
+ { path: current, code: code ?? 'unknown' },
+ `realpath failed on non-symlink leaf at ${current} (${code ?? 'unknown'}); rejecting`,
);
return false;
}
diff --git a/packages/server/src/machine-id.ts b/packages/server/src/machine-id.ts
index 02ffd2a19..c639e7293 100644
--- a/packages/server/src/machine-id.ts
+++ b/packages/server/src/machine-id.ts
@@ -30,6 +30,7 @@ import { randomUUID } from 'node:crypto';
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, join } from 'node:path';
+import { getLogger } from './logger.ts';
/**
* Accepts UUIDs and other short opaque tokens; rejects whitespace/control
@@ -72,8 +73,9 @@ export function getMachineId(homedirOverride?: string): string {
// judgments fail closed on pid liveness, so this degrades safely — but
// loudly: every collision error this process later hits will blame
// "already running" while the real root cause is this write failure.
- console.warn(
- `[machine-id] Failed to persist ${filePath} — using an ephemeral per-process id; ` +
+ getLogger('machine-id').warn(
+ { path: filePath, err },
+ `Failed to persist ${filePath} — using an ephemeral per-process id; ` +
`lock ownership checks will fail closed (collision) instead of recognizing this machine: ` +
`${err instanceof Error ? err.message : String(err)}`,
);
diff --git a/packages/server/src/managed-rename-journal.ts b/packages/server/src/managed-rename-journal.ts
index 52d829e5b..ef5256559 100644
--- a/packages/server/src/managed-rename-journal.ts
+++ b/packages/server/src/managed-rename-journal.ts
@@ -8,8 +8,11 @@ import {
tracedRmSync,
tracedWriteFileSync,
} from './fs-traced.ts';
+import { getLogger } from './logger.ts';
import { safeContentPath } from './persistence.ts';
+const log = getLogger('managed-rename');
+
const MANAGED_RENAME_JOURNAL_FILENAME = 'managed-rename.json';
export interface ManagedRenameSnapshot {
@@ -309,14 +312,14 @@ function pruneEmptyAncestors(filePath: string, contentDir: string): void {
try {
entries = readdirSync(cur);
} catch (err) {
- console.warn(`[managed-rename] pruneEmptyAncestors: cannot read ${cur}:`, err);
+ log.warn({ path: cur, err }, `pruneEmptyAncestors: cannot read ${cur}`);
return;
}
if (entries.length > 0) return;
try {
tracedRmdirSync(cur);
} catch (err) {
- console.warn(`[managed-rename] pruneEmptyAncestors: cannot rmdir ${cur}:`, err);
+ log.warn({ path: cur, err }, `pruneEmptyAncestors: cannot rmdir ${cur}`);
return;
}
cur = dirname(cur);
@@ -343,14 +346,15 @@ export function recoverPendingManagedRename(
restoredDocNames.add(snapshot.docName);
} catch (err) {
restoreFailures.push({ docName: snapshot.docName, cause: err });
- console.warn(`[managed-rename] Failed to restore ${snapshot.docName}:`, err);
+ log.warn({ docName: snapshot.docName, err }, `Failed to restore ${snapshot.docName}`);
}
}
if (restoreFailures.length > 0) {
const failedNames = restoreFailures.map((f) => f.docName).join(', ');
- console.warn(
- `[managed-rename] Recovery incomplete; keeping journal for retry (${failedNames})`,
+ log.warn(
+ { failed: failedNames },
+ `Recovery incomplete; keeping journal for retry (${failedNames})`,
);
const causes = restoreFailures.map((f) =>
f.cause instanceof Error ? f.cause : new Error(String(f.cause)),
@@ -371,14 +375,15 @@ export function recoverPendingManagedRename(
restoredPaths.add(snapshot.path);
} catch (err) {
pathRestoreFailures.push({ path: snapshot.path, cause: err });
- console.warn(`[managed-rename] Failed to restore path ${snapshot.path}:`, err);
+ log.warn({ path: snapshot.path, err }, `Failed to restore path ${snapshot.path}`);
}
}
if (pathRestoreFailures.length > 0) {
const failedPaths = pathRestoreFailures.map((f) => f.path).join(', ');
- console.warn(
- `[managed-rename] Recovery incomplete; keeping journal for retry (${failedPaths})`,
+ log.warn(
+ { failed: failedPaths },
+ `Recovery incomplete; keeping journal for retry (${failedPaths})`,
);
const causes = pathRestoreFailures.map((f) =>
f.cause instanceof Error ? f.cause : new Error(String(f.cause)),
@@ -401,13 +406,14 @@ export function recoverPendingManagedRename(
pruneEmptyAncestors(destinationPath, contentDir);
} catch (err) {
if (existsSync(destinationPath)) {
- console.warn(
- `[managed-rename] Both source and destination files exist after partial recovery for ${destination}`,
+ log.warn(
+ { destination },
+ `Both source and destination files exist after partial recovery for ${destination}`,
);
}
- console.warn(
- `[managed-rename] Recovery incomplete; failed to clean destination ${destination}:`,
- err,
+ log.warn(
+ { destination, err },
+ `Recovery incomplete; failed to clean destination ${destination}`,
);
cleanupFailures.push({ destination, cause: err });
}
@@ -423,13 +429,14 @@ export function recoverPendingManagedRename(
pruneEmptyAncestors(destinationPath, contentDir);
} catch (err) {
if (destinationPath && existsSync(destinationPath)) {
- console.warn(
- `[managed-rename] Both source and destination paths exist after partial recovery for ${destination}`,
+ log.warn(
+ { destination },
+ `Both source and destination paths exist after partial recovery for ${destination}`,
);
}
- console.warn(
- `[managed-rename] Recovery incomplete; failed to clean destination path ${destination}:`,
- err,
+ log.warn(
+ { destination, err },
+ `Recovery incomplete; failed to clean destination path ${destination}`,
);
cleanupFailures.push({ destination, cause: err });
}
diff --git a/packages/server/src/map-driven-observer-a.test.ts b/packages/server/src/map-driven-observer-a.test.ts
index 652afe089..c55fd7a18 100644
--- a/packages/server/src/map-driven-observer-a.test.ts
+++ b/packages/server/src/map-driven-observer-a.test.ts
@@ -9,13 +9,15 @@
* Hocuspocus), populate XmlFragment via `updateYFragment`, observe the
* Y.Text delta to assert splice shape directly.
*/
-import { describe, expect, spyOn, test } from 'bun:test';
+
import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { updateYFragment } from '@tiptap/y-tiptap';
+import { describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
import { AGENT_WRITE_ORIGIN } from './agent-sessions.ts';
import { composeAndWriteRawBody } from './bridge-intake.ts';
+import { getLogger } from './logger.ts';
import { computeMapDrivenBodySplice } from './map-driven-splice.ts';
import { getMetrics } from './metrics.ts';
import {
@@ -390,7 +392,7 @@ describe('map-driven Observer A — default Path A behavior', () => {
},
});
__resetMapDrivenParseErrorWarnForTests();
- const warnSpy = spyOn(console, 'warn');
+ const warnSpy = vi.spyOn(getLogger('server-observers'), 'warn');
const cleanup = setupServerObservers({
doc,
xmlFragment,
@@ -415,10 +417,12 @@ describe('map-driven Observer A — default Path A behavior', () => {
).toBeGreaterThanOrEqual(2);
// ...but the breadcrumb fired exactly once, carrying the message.
const spliceWarns = warnSpy.mock.calls.filter((args) =>
- String(args[0]).includes('Map-driven splice'),
+ String(args[1]).includes('Map-driven splice'),
);
expect(spliceWarns).toHaveLength(1);
- expect(spliceWarns[0]?.[1]).toBe('synthetic parser regression');
+ expect((spliceWarns[0]?.[0] as { err?: Error }).err?.message).toBe(
+ 'synthetic parser regression',
+ );
warnSpy.mockRestore();
cleanup();
diff --git a/packages/server/src/persistence-tripwire-read-failure.test.ts b/packages/server/src/persistence-tripwire-read-failure.test.ts
index 256a049b4..ac2cd1d9d 100644
--- a/packages/server/src/persistence-tripwire-read-failure.test.ts
+++ b/packages/server/src/persistence-tripwire-read-failure.test.ts
@@ -22,12 +22,14 @@
* watcher) so the file-watcher's lifecycle handling can't short-circuit the
* tripwire path before it runs.
*/
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
import { composeAndWriteRawBody } from './bridge-intake.ts';
+import { getLogger } from './logger.ts';
import {
createPersistenceExtension,
setReconciledBase,
@@ -90,7 +92,7 @@ describe('tripwire reset readFileSync failure', () => {
composeAndWriteRawBody(document, doubledMarkdown, 'agent');
setReconciledBase(docName, baseMarkdown);
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(getLogger('persistence'), 'warn');
try {
// First tripwire fire: the read throws but the inner try/catch
// recovers to currentBase; the breaker is then cleared via the
@@ -116,7 +118,7 @@ describe('tripwire reset readFileSync failure', () => {
// the doc would remain at the doubled state.
expect(document.getText('source').toString()).toBe(baseMarkdown);
const breakerActiveSkips = warnSpy.mock.calls
- .map((call) => String(call[0] ?? ''))
+ .map((call) => String(call[1] ?? ''))
.filter((s) => s.includes('Tripwire breaker active'));
expect(breakerActiveSkips.length).toBe(0);
} finally {
diff --git a/packages/server/src/persistence-tripwire-symlink.test.ts b/packages/server/src/persistence-tripwire-symlink.test.ts
index 9255fc305..9db1853dc 100644
--- a/packages/server/src/persistence-tripwire-symlink.test.ts
+++ b/packages/server/src/persistence-tripwire-symlink.test.ts
@@ -17,7 +17,7 @@
* watcher) so the file-watcher's lifecycle/delete handling can't
* short-circuit the tripwire path before it runs.
*/
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+
import {
mkdtempSync,
readFileSync,
@@ -28,8 +28,10 @@ import {
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
import { composeAndWriteRawBody } from './bridge-intake.ts';
+import { getLogger } from './logger.ts';
import {
createPersistenceExtension,
setReconciledBase,
@@ -106,7 +108,7 @@ describe('tripwire reset symlink-escape', () => {
composeAndWriteRawBody(document, doubledMarkdown, 'agent');
setReconciledBase(docName, baseMarkdown);
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(getLogger('persistence'), 'warn');
try {
await storeDocument(persistence, document, docName);
@@ -120,7 +122,7 @@ describe('tripwire reset symlink-escape', () => {
// A symlink-escape warning should have fired so operators can spot a
// hostile-symlink-planting attempt in the logs.
const escapeWarning = warnSpy.mock.calls
- .map((call) => String(call[0] ?? ''))
+ .map((call) => String(call[1] ?? ''))
.find((s) => s.includes('symlink-escape on tripwire reset'));
expect(escapeWarning).toBeDefined();
} finally {
diff --git a/packages/server/src/persistence.ts b/packages/server/src/persistence.ts
index 444f9912f..196d8cfd0 100644
--- a/packages/server/src/persistence.ts
+++ b/packages/server/src/persistence.ts
@@ -1645,14 +1645,14 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
}
} else {
if (canonical) {
- console.warn(
- `[persistence] symlink-escape on tripwire reset: ${requestedDiskPath} → ${canonical}, using currentBase`,
+ log.warn(
{
docName: documentName,
originalPath: requestedDiskPath,
canonical,
contentDir,
},
+ `[persistence] symlink-escape on tripwire reset: ${requestedDiskPath} → ${canonical}, using currentBase`,
);
}
diskContent = currentBase;
@@ -1717,14 +1717,14 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
}
}
if (isBrokenSymlink) {
- console.warn(`[persistence] broken-symlink fallback`, {
- docName: documentName,
- reason: 'broken-symlink',
- });
+ log.warn(
+ { docName: documentName, reason: 'broken-symlink' },
+ '[persistence] broken-symlink fallback',
+ );
}
canonicalPath = requestedPath;
} else if (code === 'ELOOP') {
- console.error(`[persistence] Symlink cycle at ${requestedPath}`);
+ log.error({ path: requestedPath }, `[persistence] Symlink cycle at ${requestedPath}`);
throw new Error(`Symlink cycle detected at ${requestedPath}`);
} else {
throw e;
@@ -1733,12 +1733,15 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
if (!isWithinContentDir(canonicalPath, contentDir)) {
const msg = `symlink-escape: ${requestedPath} resolves to ${canonicalPath} outside ${contentDir}`;
- console.error(`[persistence] ${msg}`, {
- docName: documentName,
- originalPath: requestedPath,
- canonical: canonicalPath,
- contentDir,
- });
+ log.error(
+ {
+ docName: documentName,
+ originalPath: requestedPath,
+ canonical: canonicalPath,
+ contentDir,
+ },
+ `[persistence] ${msg}`,
+ );
throw new Error(msg);
}
@@ -2104,7 +2107,8 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
try {
const resolvedCanonical = realpathSync(filePath);
if (!isWithinContentDir(resolvedCanonical, contentDir)) {
- console.warn(
+ log.warn(
+ { path: filePath, canonical: resolvedCanonical },
`[persistence] symlink-escape on load: ${filePath} → ${resolvedCanonical}, refusing`,
);
return;
@@ -2113,7 +2117,10 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
} catch (e) {
const code = (e as NodeJS.ErrnoException).code;
if (code === 'ELOOP') {
- console.warn(`[persistence] Symlink cycle on load: ${filePath}, refusing`);
+ log.warn(
+ { path: filePath },
+ `[persistence] Symlink cycle on load: ${filePath}, refusing`,
+ );
return;
}
// Preserve the historical fallback: stat/read the requested path when realpath fails.
diff --git a/packages/server/src/process-lock.ts b/packages/server/src/process-lock.ts
index 0c79cfab2..24444aeb6 100644
--- a/packages/server/src/process-lock.ts
+++ b/packages/server/src/process-lock.ts
@@ -21,10 +21,13 @@ import {
} from 'node:fs';
import { hostname } from 'node:os';
import { resolve } from 'node:path';
+import { getLogger } from './logger.ts';
import { getMachineId } from './machine-id.ts';
import { isProcessAlive, isValidLockPid } from './process-alive.ts';
import { PROTOCOL_VERSION, RUNTIME_VERSION } from './version-constants.ts';
+const log = getLogger('process-lock');
+
export type LockName = 'server' | 'ui';
/**
@@ -233,10 +236,10 @@ function parseLock(lockPath: string, logPrefix: string): ProcessLockMetadata | n
if (parsed && typeof parsed === 'object' && isValidLockPid((parsed as { pid?: unknown }).pid)) {
return parsed as ProcessLockMetadata;
}
- console.warn(`${logPrefix} Corrupt lock file at ${lockPath} — replacing`);
+ log.warn({ lockPath }, `${logPrefix} Corrupt lock file at ${lockPath} — replacing`);
return null;
} catch {
- console.warn(`${logPrefix} Corrupt lock file at ${lockPath} — replacing`);
+ log.warn({ lockPath }, `${logPrefix} Corrupt lock file at ${lockPath} — replacing`);
return null;
}
}
@@ -349,7 +352,8 @@ export function acquireProcessLock(opts: {
if (isProcessAlive(existing.pid)) {
throw new ProcessLockCollisionError(existing, lockPath, lockName);
}
- console.warn(
+ log.warn(
+ { pid: existing.pid, host: existing.hostname },
`${logPrefix} Stale lock detected (pid=${existing.pid}, host=${existing.hostname}) — replacing`,
);
}
@@ -396,7 +400,10 @@ export function updateProcessLockPort(opts: {
const lockPath = lockFilePath(lockDir, lockName);
if (!existsSync(lockPath)) {
- console.warn(`${logPrefix} Lock file missing at ${lockPath} during port update — skipping`);
+ log.warn(
+ { lockPath },
+ `${logPrefix} Lock file missing at ${lockPath} during port update — skipping`,
+ );
return;
}
@@ -408,12 +415,18 @@ export function updateProcessLockPort(opts: {
typeof parsed !== 'object' ||
!isValidLockPid((parsed as { pid?: unknown }).pid)
) {
- console.warn(`${logPrefix} Corrupt lock at ${lockPath} during port update — skipping`);
+ log.warn(
+ { lockPath },
+ `${logPrefix} Corrupt lock at ${lockPath} during port update — skipping`,
+ );
return;
}
existing = parsed as ProcessLockMetadata;
} catch {
- console.warn(`${logPrefix} Unreadable lock at ${lockPath} during port update — skipping`);
+ log.warn(
+ { lockPath },
+ `${logPrefix} Unreadable lock at ${lockPath} during port update — skipping`,
+ );
return;
}
if (existing.pid !== process.pid) return;
@@ -430,7 +443,8 @@ export function updateProcessLockPort(opts: {
mode: 0o600,
});
} catch (err) {
- console.warn(
+ log.warn(
+ { lockPath, err },
`${logPrefix} Failed to update port in ${lockPath}: ${err instanceof Error ? err.message : String(err)}`,
);
}
@@ -463,7 +477,10 @@ export function markProcessLockDraining(opts: { lockName: LockName; lockDir: str
typeof parsed !== 'object' ||
!isValidLockPid((parsed as { pid?: unknown }).pid)
) {
- console.warn(`${logPrefix} Corrupt lock at ${lockPath} during draining mark — skipping`);
+ log.warn(
+ { lockPath },
+ `${logPrefix} Corrupt lock at ${lockPath} during draining mark — skipping`,
+ );
return;
}
existing = parsed as ProcessLockMetadata;
@@ -473,7 +490,8 @@ export function markProcessLockDraining(opts: { lockName: LockName; lockDir: str
// failed WRITE (server keeps looking live during teardown), so it must be
// as attributable as the write-failure warn below.
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {
- console.warn(
+ log.warn(
+ { lockPath, err },
`${logPrefix} Unreadable lock at ${lockPath} during draining mark — skipping: ${err instanceof Error ? err.message : String(err)}`,
);
}
@@ -490,7 +508,8 @@ export function markProcessLockDraining(opts: { lockName: LockName; lockDir: str
mode: 0o600,
});
} catch (err) {
- console.warn(
+ log.warn(
+ { lockPath, err },
`${logPrefix} Failed to mark ${lockPath} draining: ${err instanceof Error ? err.message : String(err)}`,
);
}
@@ -725,7 +744,8 @@ export function releaseProcessLock(opts: {
unlinkSync(lockPath);
exitUnlinkPaths.delete(lockPath);
} catch (err) {
- console.warn(
+ log.warn(
+ { lockPath, err },
`${logPrefix} Failed to release ${lockPath}: ${err instanceof Error ? err.message : String(err)}`,
);
}
diff --git a/packages/server/src/rename-log.test.ts b/packages/server/src/rename-log.test.ts
index 3f2b7d41d..055dd82fa 100644
--- a/packages/server/src/rename-log.test.ts
+++ b/packages/server/src/rename-log.test.ts
@@ -1,9 +1,10 @@
-import { afterEach, beforeEach, describe, expect, mock, test, vi } from 'bun:test';
import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { getLogger } from './logger.ts';
import {
appendRenameLogEntry,
backfillRenameLogCommitSha,
@@ -281,14 +282,15 @@ describe('appendRenameLogEntry', () => {
const index = createEmptyIndex();
let warned = false;
- const orig = console.warn;
- console.warn = (msg: unknown) => {
- if (typeof msg === 'string' && msg.includes('exceeds hard cap')) warned = true;
- };
+ const warnSpy = vi
+ .spyOn(getLogger('rename-log'), 'warn')
+ .mockImplementation((_data: unknown, msg: string) => {
+ if (msg.includes('exceeds hard cap')) warned = true;
+ });
try {
appendRenameLogEntry(shadowDir, entry(), index);
} finally {
- console.warn = orig;
+ warnSpy.mockRestore();
}
expect(warned).toBe(true);
});
@@ -351,16 +353,17 @@ describe('expandPredecessors', () => {
index,
);
let warned = false;
- const orig = console.warn;
- console.warn = (msg: unknown) => {
- if (typeof msg === 'string' && msg.includes('cycle detected')) warned = true;
- };
+ const warnSpy = vi
+ .spyOn(getLogger('rename-log'), 'warn')
+ .mockImplementation((_data: unknown, msg: string) => {
+ if (msg.includes('cycle detected')) warned = true;
+ });
try {
const { chain } = expandPredecessors('a', 'main', index);
// Cycle detection truncates: a → b → (cycle on a) breaks. Returns at least the current doc.
expect(chain[chain.length - 1]).toEqual({ path: 'a', renameCommit: null });
} finally {
- console.warn = orig;
+ warnSpy.mockRestore();
}
expect(warned).toBe(true);
});
@@ -429,17 +432,18 @@ describe('expandPredecessors', () => {
}
let warned = false;
- const origWarn = console.warn;
- console.warn = (msg: unknown) => {
- if (typeof msg === 'string' && msg.includes('chain depth exceeded')) warned = true;
- };
+ const warnSpy = vi
+ .spyOn(getLogger('rename-log'), 'warn')
+ .mockImplementation((_data: unknown, msg: string) => {
+ if (msg.includes('chain depth exceeded')) warned = true;
+ });
try {
const { chain } = expandPredecessors(`step-${depth}`, 'main', index);
// Walk produced MAX_PREDECESSOR_CHAIN_DEPTH predecessors + 1 trailing current doc.
expect(chain.length).toBe(MAX_PREDECESSOR_CHAIN_DEPTH + 1);
expect(chain[chain.length - 1]).toEqual({ path: `step-${depth}`, renameCommit: null });
} finally {
- console.warn = origWarn;
+ warnSpy.mockRestore();
}
expect(warned).toBe(true);
});
@@ -589,7 +593,7 @@ describe('rename-log read primitives (shadow-repo backed)', () => {
const { spawn: realSpawn, ...realCp } =
await vi.importActual<typeof import('node:child_process')>('node:child_process');
const spawnCalls: unknown[][] = [];
- mock.module('node:child_process', () => ({
+ vi.doMock('node:child_process', () => ({
...realCp,
spawn: (...args: Parameters<typeof realSpawn>) => {
spawnCalls.push(args);
@@ -629,16 +633,17 @@ describe('rename-log read primitives (shadow-repo backed)', () => {
// still have something to feed `buildAncestorShaSet` (which itself
// returns empty on rev-list failure — graceful end-to-end degradation).
const bogusSha = '0123456789abcdef0123456789abcdef01234567';
- const orig = console.warn;
let warned = false;
- console.warn = (msg: unknown) => {
- if (typeof msg === 'string' && msg.includes('buildSeeds: git show failed')) warned = true;
- };
+ const warnSpy = vi
+ .spyOn(getLogger('rename-log'), 'warn')
+ .mockImplementation((_data: unknown, msg: string) => {
+ if (msg.includes('buildSeeds: git show failed')) warned = true;
+ });
try {
const seeds = await buildSeeds(shadow, bogusSha, 'main');
expect(seeds).toEqual([bogusSha]);
} finally {
- console.warn = orig;
+ warnSpy.mockRestore();
}
expect(warned).toBe(true);
});
@@ -796,11 +801,12 @@ describe('rename-log read primitives (shadow-repo backed)', () => {
expect(sizeBefore).toBeGreaterThan(RENAME_LOG_HARD_CAP_BYTES);
const index = createEmptyIndex();
- const orig = console.warn;
let warned = false;
- console.warn = (msg: unknown) => {
- if (typeof msg === 'string' && msg.includes('exceeds hard cap')) warned = true;
- };
+ const warnSpy = vi
+ .spyOn(getLogger('rename-log'), 'warn')
+ .mockImplementation((_data: unknown, msg: string) => {
+ if (msg.includes('exceeds hard cap')) warned = true;
+ });
try {
// Pass `shadow` so scheduleHardCapGc fires. The entry has a fake-but-
// syntactically-valid commitSha that is unreachable from any ref — gc
@@ -817,7 +823,7 @@ describe('rename-log read primitives (shadow-repo backed)', () => {
shadow,
);
} finally {
- console.warn = orig;
+ warnSpy.mockRestore();
}
expect(warned).toBe(true);
expect(index.byTo.size).toBe(1);
@@ -871,15 +877,16 @@ describe('batchCheckExistence timeout fallback (FR16 / D-T7)', () => {
process.env.PATH = `${fakeBinDir}:${origPath}`;
process.env.OK_GIT_TIMEOUT_MS = '200';
- const orig = console.warn;
let warnedTimeout = false;
let warnMsg: string | null = null;
- console.warn = (msg: unknown) => {
- if (typeof msg === 'string' && msg.includes('timed out')) {
- warnedTimeout = true;
- warnMsg = msg;
- }
- };
+ const warnSpy = vi
+ .spyOn(getLogger('rename-log'), 'warn')
+ .mockImplementation((_data: unknown, msg: string) => {
+ if (msg.includes('timed out')) {
+ warnedTimeout = true;
+ warnMsg = msg;
+ }
+ });
try {
const t0 = performance.now();
@@ -898,7 +905,7 @@ describe('batchCheckExistence timeout fallback (FR16 / D-T7)', () => {
// Anything > 2s means the timeout branch didn't fire.
expect(elapsed).toBeLessThan(2000);
} finally {
- console.warn = orig;
+ warnSpy.mockRestore();
process.env.PATH = origPath;
if (origTimeout !== undefined) process.env.OK_GIT_TIMEOUT_MS = origTimeout;
else process.env.OK_GIT_TIMEOUT_MS = undefined;
@@ -1235,12 +1242,12 @@ describe('gcRenameLog (US-008 reachability + rebuild)', () => {
workTree: shadow.workTree,
};
- const origWarn = console.warn;
let warned = false;
- console.warn = (...args: unknown[]) => {
- const msg = args.map(String).join(' ');
- if (msg.includes('aborted')) warned = true;
- };
+ const warnSpy = vi
+ .spyOn(getLogger('rename-log'), 'warn')
+ .mockImplementation((_data: unknown, msg: string) => {
+ if (msg.includes('aborted')) warned = true;
+ });
try {
const result = await gcRenameLog(brokenShadow, index);
// Aborted: scanned/dropped/retained all 0 — function bailed before any work.
@@ -1248,7 +1255,7 @@ describe('gcRenameLog (US-008 reachability + rebuild)', () => {
expect(result.dropped).toBe(0);
expect(result.retained).toBe(0);
} finally {
- console.warn = origWarn;
+ warnSpy.mockRestore();
}
expect(warned).toBe(true);
// Entry preserved in memory (not wiped by aborted GC).
@@ -1287,18 +1294,18 @@ describe('gcRenameLog (US-008 reachability + rebuild)', () => {
`${'0123456789abcdef0123456789abcdef01234567'}\n`,
);
- const origWarn = console.warn;
let warned = false;
- console.warn = (...args: unknown[]) => {
- const msg = args.map(String).join(' ');
- if (msg.includes('aborted')) warned = true;
- };
+ const warnSpy = vi
+ .spyOn(getLogger('rename-log'), 'warn')
+ .mockImplementation((_data: unknown, msg: string) => {
+ if (msg.includes('aborted')) warned = true;
+ });
try {
const result = await gcRenameLog(shadow, index);
// Aborted: must not drop the legitimate entry even though rev-list failed.
expect(result.dropped).toBe(0);
} finally {
- console.warn = origWarn;
+ warnSpy.mockRestore();
}
expect(warned).toBe(true);
expect(index.byTo.get('b')?.commitSha).toBe(realSha);
@@ -1558,17 +1565,18 @@ describe('validateEntry self-rename rejection', () => {
const body = `${JSON.stringify(selfRename)}\n${JSON.stringify(valid)}\n`;
writeFileSync(renameLogPath(shadowDir), body);
let warned = false;
- const orig = console.warn;
- console.warn = (msg: unknown) => {
- if (typeof msg === 'string' && msg.includes('corrupt entry at line 1')) warned = true;
- };
+ const warnSpy = vi
+ .spyOn(getLogger('rename-log'), 'warn')
+ .mockImplementation((_data: unknown, msg: string) => {
+ if (msg.includes('corrupt entry at line 1')) warned = true;
+ });
try {
const index = loadRenameLogIndex(shadowDir);
// Self-rename was rejected; the legitimate rename loaded.
expect(index.byTo.has('x')).toBe(false);
expect(index.byTo.get('b')).toBeDefined();
} finally {
- console.warn = orig;
+ warnSpy.mockRestore();
}
expect(warned).toBe(true);
});
@@ -1583,17 +1591,18 @@ describe('backfillRenameLogCommitSha SHA validation', () => {
index,
);
let warned = false;
- const orig = console.warn;
- console.warn = (msg: unknown) => {
- if (typeof msg === 'string' && msg.includes('rejected invalid commitSha')) warned = true;
- };
+ const warnSpy = vi
+ .spyOn(getLogger('rename-log'), 'warn')
+ .mockImplementation((_data: unknown, msg: string) => {
+ if (msg.includes('rejected invalid commitSha')) warned = true;
+ });
try {
const result = backfillRenameLogCommitSha(shadowDir, 'agent-x', '', index);
expect(result.updated).toBe(0);
// Entry stays in lazy-pop state — recoverable on a subsequent valid backfill.
expect(index.byTo.get('essays/auth')?.commitSha).toBe('');
} finally {
- console.warn = orig;
+ warnSpy.mockRestore();
}
expect(warned).toBe(true);
});
@@ -1605,13 +1614,12 @@ describe('backfillRenameLogCommitSha SHA validation', () => {
entry({ commitSha: '', actor: { writerId: 'agent-x', displayName: 'X' } }),
index,
);
- const orig = console.warn;
- console.warn = () => {};
+ const warnSpy = vi.spyOn(getLogger('rename-log'), 'warn').mockImplementation(() => {});
try {
const result = backfillRenameLogCommitSha(shadowDir, 'agent-x', 'abc123', index);
expect(result.updated).toBe(0);
} finally {
- console.warn = orig;
+ warnSpy.mockRestore();
}
expect(index.byTo.get('essays/auth')?.commitSha).toBe('');
});
@@ -1623,14 +1631,13 @@ describe('backfillRenameLogCommitSha SHA validation', () => {
entry({ commitSha: '', actor: { writerId: 'agent-x', displayName: 'X' } }),
index,
);
- const orig = console.warn;
- console.warn = () => {};
+ const warnSpy = vi.spyOn(getLogger('rename-log'), 'warn').mockImplementation(() => {});
try {
// 40 chars but contains a 'g' — not a valid hex SHA
const result = backfillRenameLogCommitSha(shadowDir, 'agent-x', 'g'.repeat(40), index);
expect(result.updated).toBe(0);
} finally {
- console.warn = orig;
+ warnSpy.mockRestore();
}
});
});
diff --git a/packages/server/src/rename-log.ts b/packages/server/src/rename-log.ts
index abda1c2f9..d40bf55c3 100644
--- a/packages/server/src/rename-log.ts
+++ b/packages/server/src/rename-log.ts
@@ -25,10 +25,13 @@ import {
tracedUnlinkSync,
tracedWriteFileSync,
} from './fs-traced.ts';
+import { getLogger } from './logger.ts';
import type { ShadowHandle } from './shadow-repo.ts';
import { shadowGit } from './shadow-repo.ts';
import { getMeter, withSpan } from './telemetry.ts';
+const log = getLogger('rename-log');
+
let _liveEntriesGauge: ReturnType<ReturnType<typeof getMeter>['createUpDownCounter']> | null = null;
function liveEntriesGauge(): ReturnType<ReturnType<typeof getMeter>['createUpDownCounter']> {
_liveEntriesGauge ||= getMeter().createUpDownCounter('rename.log_entries_total', {
@@ -200,7 +203,7 @@ export function loadRenameLogIndex(shadowDir: string): RenameLogIndex {
try {
raw = readFileSync(path, 'utf-8');
} catch (err) {
- console.warn(`[rename-log] WARN: failed to read ${path}, treating as empty:`, err);
+ log.warn({ path, err }, `[rename-log] WARN: failed to read ${path}, treating as empty`);
return index;
}
@@ -211,7 +214,8 @@ export function loadRenameLogIndex(shadowDir: string): RenameLogIndex {
// Well-formed jsonl ends with a newline → trailing is ''. Anything else is
// an incomplete final line (mid-write crash, disk full).
if (trailing !== '') {
- console.warn(
+ log.warn(
+ { bytes: trailing.length },
`[rename-log] WARN: trailing line missing newline (${trailing.length} bytes); dropped`,
);
}
@@ -226,14 +230,15 @@ export function loadRenameLogIndex(shadowDir: string): RenameLogIndex {
} catch (parseErr) {
const sample = line.slice(0, 80);
const errMsg = (parseErr as Error).message;
- console.warn(
+ log.warn(
+ { line: i + 1, errMsg },
`[rename-log] WARN: corrupt entry at line ${i + 1} skipped (${errMsg}): ${sample}${line.length > 80 ? '…' : ''}`,
);
continue;
}
const entry = validateEntry(parsed);
if (!entry) {
- console.warn(`[rename-log] WARN: corrupt entry at line ${i + 1} skipped`);
+ log.warn({ line: i + 1 }, `[rename-log] WARN: corrupt entry at line ${i + 1} skipped`);
continue;
}
indexInsert(index, entry);
@@ -286,7 +291,8 @@ export function appendRenameLogEntry(
const size = statSync(path).size;
if (size > RENAME_LOG_HARD_CAP_BYTES) {
overCap = true;
- console.warn(
+ log.warn(
+ { size, cap: RENAME_LOG_HARD_CAP_BYTES },
`[rename-log] WARN: file size ${size} exceeds hard cap ${RENAME_LOG_HARD_CAP_BYTES}; forcing GC sweep`,
);
}
@@ -321,7 +327,7 @@ function scheduleHardCapGc(shadow: ShadowHandle, index: RenameLogIndex): void {
// gcRenameLog itself enforces the gitDir-scoped dedup invariant.
queueMicrotask(() => {
gcRenameLog(shadow, index).catch((err) => {
- console.warn('[rename-log] WARN: hard-cap forced GC failed:', err);
+ log.warn({ err }, '[rename-log] WARN: hard-cap forced GC failed');
});
});
}
@@ -442,13 +448,15 @@ export function expandPredecessors(
// predecessor of `cursor`?" by looking up `index.byTo.get(cursor)`.
while (true) {
if (chain.length >= MAX_PREDECESSOR_CHAIN_DEPTH) {
- console.warn(
+ log.warn(
+ { docName: currentDocName, maxDepth: MAX_PREDECESSOR_CHAIN_DEPTH },
`[rename-log] WARN: predecessor chain depth exceeded ${MAX_PREDECESSOR_CHAIN_DEPTH} while expanding "${currentDocName}"; truncating`,
);
break;
}
if (visited.has(cursor)) {
- console.warn(
+ log.warn(
+ { cursor, docName: currentDocName },
`[rename-log] WARN: cycle detected at "${cursor}" while expanding predecessors of "${currentDocName}"; truncating`,
);
break;
@@ -530,9 +538,9 @@ export async function buildSeeds(
try {
renameAuthorDate = (await sg.raw('show', '-s', '--format=%aI', renameCommit)).trim();
} catch (err) {
- console.warn(
- `[rename-log] WARN: buildSeeds: git show failed for rename commit ${renameCommit}; falling back to single-seed:`,
- err,
+ log.warn(
+ { renameCommit, err },
+ `[rename-log] WARN: buildSeeds: git show failed for rename commit ${renameCommit}; falling back to single-seed`,
);
span.setAttribute('rename.seeds_count', 1);
return [renameCommit];
@@ -551,9 +559,9 @@ export async function buildSeeds(
`refs/checkpoints/${branch}/`,
);
} catch (err) {
- console.warn(
- `[rename-log] WARN: buildSeeds: for-each-ref failed for branch ${branch}; falling back to single-seed:`,
- err,
+ log.warn(
+ { branch, err },
+ `[rename-log] WARN: buildSeeds: for-each-ref failed for branch ${branch}; falling back to single-seed`,
);
span.setAttribute('rename.seeds_count', 1);
return [renameCommit];
@@ -774,9 +782,9 @@ export async function buildAncestorShaSet(
try {
raw = await revListReachable(shadow, seeds);
} catch (err) {
- console.warn(
- `[rename-log] WARN: buildAncestorShaSet: rev-list failed (${seeds.length} seeds); falling back to empty set:`,
- err,
+ log.warn(
+ { seeds: seeds.length, err },
+ `[rename-log] WARN: buildAncestorShaSet: rev-list failed (${seeds.length} seeds); falling back to empty set`,
);
span.setAttribute('rename.ancestor_shas_count', 0);
return new Set();
@@ -840,7 +848,8 @@ export function batchCheckExistence(
};
const timer = setTimeout(() => {
- console.warn(
+ log.warn(
+ { timeoutMs, probes: probes.length },
`[rename-log] WARN: batchCheckExistence timed out after ${timeoutMs}ms (${probes.length} probes); returning all-false`,
);
try {
@@ -853,7 +862,7 @@ export function batchCheckExistence(
child.on('error', (err) => {
clearTimeout(timer);
- console.warn(`[rename-log] WARN: batchCheckExistence spawn error: ${err.message}`);
+ log.warn({ err }, `[rename-log] WARN: batchCheckExistence spawn error: ${err.message}`);
settle(allFalse());
});
@@ -867,7 +876,8 @@ export function batchCheckExistence(
// might be safe to drop (rare), while a false positive (treating a
// crashed batch as "all missing") would silently drop live entries.
if ((code !== null && code !== 0) || (signal && !settled)) {
- console.warn(
+ log.warn(
+ { code, signal: signal ?? 'none' },
`[rename-log] WARN: batchCheckExistence exited code=${code} signal=${signal ?? 'none'}; returning all-false`,
);
settle(allFalse());
@@ -892,7 +902,8 @@ export function batchCheckExistence(
child.stdin.end(`${stdin}\n`);
} catch (err) {
clearTimeout(timer);
- console.warn(
+ log.warn(
+ { err },
`[rename-log] WARN: batchCheckExistence stdin write failed: ${(err as Error).message}`,
);
settle(allFalse());
@@ -944,7 +955,8 @@ export function batchResolveBlobOids(
};
const timer = setTimeout(() => {
- console.warn(
+ log.warn(
+ { timeoutMs, probes: probes.length },
`[rename-log] WARN: batchResolveBlobOids timed out after ${timeoutMs}ms (${probes.length} probes); returning all-null`,
);
try {
@@ -957,14 +969,15 @@ export function batchResolveBlobOids(
child.on('error', (err) => {
clearTimeout(timer);
- console.warn(`[rename-log] WARN: batchResolveBlobOids spawn error: ${err.message}`);
+ log.warn({ err }, `[rename-log] WARN: batchResolveBlobOids spawn error: ${err.message}`);
settle(allNull());
});
child.on('close', (code, signal) => {
clearTimeout(timer);
if ((code !== null && code !== 0) || (signal && !settled)) {
- console.warn(
+ log.warn(
+ { code, signal: signal ?? 'none' },
`[rename-log] WARN: batchResolveBlobOids exited code=${code} signal=${signal ?? 'none'}; returning all-null`,
);
settle(allNull());
@@ -988,7 +1001,8 @@ export function batchResolveBlobOids(
child.stdin.end(`${stdin}\n`);
} catch (err) {
clearTimeout(timer);
- console.warn(
+ log.warn(
+ { err },
`[rename-log] WARN: batchResolveBlobOids stdin write failed: ${(err as Error).message}`,
);
settle(allNull());
@@ -1010,7 +1024,7 @@ function rewriteJsonlAtomically(shadowDir: string, index: RenameLogIndex): void
try {
tracedWriteFileSync(path, '');
} catch (err) {
- console.warn('[rename-log] WARN: failed to truncate empty jsonl:', err);
+ log.warn({ err }, '[rename-log] WARN: failed to truncate empty jsonl');
}
}
return;
@@ -1026,7 +1040,7 @@ function rewriteJsonlAtomically(shadowDir: string, index: RenameLogIndex): void
tracedWriteFileSync(tmp, serialized);
tracedRenameSync(tmp, path);
} catch (err) {
- console.warn('[rename-log] WARN: atomic rewrite failed; index ahead of disk:', err);
+ log.warn({ err }, '[rename-log] WARN: atomic rewrite failed; index ahead of disk');
// Best-effort cleanup of the orphaned tmp file. If this throws too, the
// next rewrite will overwrite it.
try {
@@ -1057,7 +1071,8 @@ export function backfillRenameLogCommitSha(
// one: `sweepLazyPopOrphans` would no longer match (commitSha non-empty)
// and reachability GC would silently drop them as unreachable.
if (!/^[0-9a-f]{40}$/.test(commitSha)) {
- console.warn(
+ log.warn(
+ { commitSha },
`[rename-log] WARN: backfill rejected invalid commitSha: ${JSON.stringify(commitSha)}`,
);
return { updated: 0 };
@@ -1109,7 +1124,8 @@ export function sweepLazyPopOrphans(shadowDir: string, index: RenameLogIndex): {
}
rewriteJsonlAtomically(shadowDir, index);
liveEntriesGauge().add(-orphans.length);
- console.warn(
+ log.warn(
+ { orphans: orphans.length },
`[rename-log] gc swept ${orphans.length} orphan entries (lazy-pop residue from mid-rename crash)`,
);
return { dropped: orphans.length };
@@ -1216,7 +1232,7 @@ async function gcRenameLogInner(
.map((l) => l.trim())
.filter(Boolean);
} catch (err) {
- console.warn('[rename-log] WARN: gcRenameLog aborted — failed to enumerate refs:', err);
+ log.warn({ err }, '[rename-log] WARN: gcRenameLog aborted — failed to enumerate refs');
return result;
}
@@ -1226,7 +1242,7 @@ async function gcRenameLogInner(
try {
raw = await revListReachable(shadow, refLines);
} catch (err) {
- console.warn('[rename-log] WARN: gcRenameLog aborted — rev-list failed:', err);
+ log.warn({ err }, '[rename-log] WARN: gcRenameLog aborted — rev-list failed');
return result;
}
for (const line of raw.split('\n')) {
@@ -1273,9 +1289,9 @@ async function gcRenameLogInner(
// jsonl, so an unobservable failure of the recovery itself is the
// worst-case shape. Warn so the operator sees that rebuild was
// attempted but git rejected it.
- console.warn(
- '[rename-log] WARN: gcRenameLog rebuild: git log --grep failed; skipping reconstruction:',
- err,
+ log.warn(
+ { err },
+ '[rename-log] WARN: gcRenameLog rebuild: git log --grep failed; skipping reconstruction',
);
logRaw = '';
}
@@ -1346,7 +1362,8 @@ async function gcRenameLogInner(
}
if (result.dropped > 0) {
- console.warn(
+ log.warn(
+ { dropped: result.dropped, retained: result.retained },
`[rename-log] gc swept ${result.dropped} dead entries (${result.retained} live remain)`,
);
gcDroppedCounter().add(result.dropped);
@@ -1395,9 +1412,9 @@ async function buildBranchReachabilityMap(
try {
raw = await revListReachable(shadow, refs);
} catch (err) {
- console.warn(
- `[rename-log] WARN: gcRenameLog rebuild: rev-list failed for branch ${branch}; reconstructed entries on this branch will fall back to 'main':`,
- err,
+ log.warn(
+ { branch, err },
+ `[rename-log] WARN: gcRenameLog rebuild: rev-list failed for branch ${branch}; reconstructed entries on this branch will fall back to 'main'`,
);
continue;
}
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 816010342..9dffdd283 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -925,7 +925,7 @@ export function createServer(options: ServerOptions): ServerInstance {
backlinkSaveTimer = setTimeout(() => {
backlinkSaveTimer = null;
void backlinkIndex.saveToDisk().catch((err) => {
- console.warn('[backlinks] Failed to persist debounced cache:', err);
+ getLogger('backlinks').warn({ err }, 'Failed to persist debounced cache');
});
}, BACKLINK_SAVE_DEBOUNCE_MS);
}
@@ -3380,7 +3380,10 @@ export function createServer(options: ServerOptions): ServerInstance {
log.warn({ err, branch }, '[backlinks] global skill bundle ingest failed');
}
void backlinkIndex.saveToDisk().catch((err) => {
- console.warn(`[backlinks] Failed to persist startup cache for ${branch}:`, err);
+ getLogger('backlinks').warn(
+ { branch, err },
+ `Failed to persist startup cache for ${branch}`,
+ );
});
} catch (err) {
log.error(
@@ -3816,7 +3819,10 @@ export function createServer(options: ServerOptions): ServerInstance {
);
}
void backlinkIndex.saveToDisk(newBranch).catch((err) => {
- console.warn(`[backlinks] Failed to persist branch cache for ${newBranch}:`, err);
+ getLogger('backlinks').warn(
+ { branch: newBranch, err },
+ `Failed to persist branch cache for ${newBranch}`,
+ );
});
} catch (err) {
log.error(
diff --git a/packages/server/src/server-observer-extension.ts b/packages/server/src/server-observer-extension.ts
index c173ef10e..0fbe064af 100644
--- a/packages/server/src/server-observer-extension.ts
+++ b/packages/server/src/server-observer-extension.ts
@@ -13,10 +13,13 @@ import type { MarkdownManager } from '@inkeep/open-knowledge-core';
import type { Schema } from '@tiptap/pm/model';
import type * as Y from 'yjs';
import { isConfigDoc, isMermaidDoc, isSystemDoc } from './cc1-broadcast.ts';
+import { getLogger } from './logger.ts';
import { incrementServerObserverError } from './metrics.ts';
import { setupServerObservers } from './server-observers.ts';
import type { ShadowRef } from './shadow-repo.ts';
+const log = getLogger('server-observers');
+
export interface ServerObserverExtensionOptions {
mdManager: MarkdownManager;
schema: Schema;
@@ -97,9 +100,9 @@ export function createServerObserverExtension(opts: ServerObserverExtensionOptio
// Do NOT re-throw: Hocuspocus afterLoadDocument is not try/catch guarded
// (unlike onLoadDocument). Re-throwing would break the document setup
// pipeline (beforeBroadcastStateless, awareness wiring) for ALL clients.
- console.error(
- `[ServerObserverExtension] Failed to attach observers for '${documentName}':`,
- err,
+ log.error(
+ { docName: documentName, err },
+ `[ServerObserverExtension] Failed to attach observers for '${documentName}'`,
);
incrementServerObserverError('a');
incrementServerObserverError('b');
@@ -117,7 +120,8 @@ export function createServerObserverExtension(opts: ServerObserverExtensionOptio
const retryId = setTimeout(() => {
pendingRetries.delete(documentName);
if (cleanups.has(documentName)) return; // already attached (e.g., unload+reload)
- console.warn(
+ log.warn(
+ { docName: documentName },
`[ServerObserverExtension] Retrying observer attachment for '${documentName}'`,
);
attach();
@@ -148,7 +152,7 @@ export function createServerObserverExtension(opts: ServerObserverExtensionOptio
try {
cleanup();
} catch (err) {
- console.error(`[ServerObserverExtension] Cleanup failed for '${docName}':`, err);
+ log.error({ docName, err }, `[ServerObserverExtension] Cleanup failed for '${docName}'`);
}
}
cleanups.clear();
diff --git a/packages/server/src/server-observers.producer-guard.test.ts b/packages/server/src/server-observers.producer-guard.test.ts
index ab969a683..9e2a522c1 100644
--- a/packages/server/src/server-observers.producer-guard.test.ts
+++ b/packages/server/src/server-observers.producer-guard.test.ts
@@ -15,7 +15,7 @@
* silent checkpoint of the pre-loss source, never a throw, never a
* corrective write.
*/
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+
import { mkdirSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
@@ -24,7 +24,9 @@ import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import simpleGit from 'simple-git';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
+import { getLogger } from './logger.ts';
import { getMetrics } from './metrics.ts';
import {
ProducerGuardViolationError,
@@ -182,7 +184,7 @@ describe('Producer guard (FR6) — dev/test posture throws (M2)', () => {
// and no producer-guard-violation event.
const { doc, xmlFragment, ytext } = createDoc();
const shattering = makeContainerShatteringManager();
- const warn = spyOn(console, 'warn').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const cleanup = setupServerObservers(
baseOpts({ doc, xmlFragment, ytext, mdManager: shattering, docName: 'shatter.md' }),
);
@@ -234,7 +236,7 @@ describe('Producer guard (FR6) — packaged posture logs + checkpoints, never th
test('detects content-loss without throwing: structured log + silent checkpoint, no corrective write', async () => {
const { doc, xmlFragment, ytext } = createDoc();
const losing = makeContentLosingManager(LOSS_SENTINEL);
- const warn = spyOn(console, 'warn').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const cleanup = setupServerObservers(
baseOpts({
doc,
@@ -286,12 +288,12 @@ describe('Producer guard (FR6) — packaged posture logs + checkpoints, never th
test('two distinct losses in the cooldown: one log suppressed, BOTH checkpointed, next emit carries the suppressed count', async () => {
const { doc, xmlFragment, ytext } = createDoc();
const losing = makeContentLosingManager(LOSS_SENTINEL);
- const warn = spyOn(console, 'warn').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
// Controllable clock so the cooldown window is deterministic (the throttle
// reads Date.now); the checkpoint label uses `new Date()`, unaffected. The
// checkpoint poll below is Date.now-independent, so the mock can stay live.
let clock = 1_000_000;
- const nowSpy = spyOn(Date, 'now').mockImplementation(() => clock);
+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => clock);
const cleanup = setupServerObservers(
baseOpts({
doc,
@@ -363,7 +365,7 @@ describe('Producer guard (FR6) — packaged posture logs + checkpoints, never th
// fire regardless, or a shadow-less session loses the signal entirely.
const { doc, xmlFragment, ytext } = createDoc();
const losing = makeContentLosingManager(LOSS_SENTINEL);
- const warn = spyOn(console, 'warn').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const cleanup = setupServerObservers(
baseOpts({ doc, xmlFragment, ytext, mdManager: losing, docName: 'no-shadow.md' }),
);
@@ -401,14 +403,14 @@ describe('Producer guard (FR6) — packaged posture logs + checkpoints, never th
test('an identical pre-loss source is checkpointed once — the dedup map holds (one ref, one counter)', async () => {
const { doc, xmlFragment, ytext } = createDoc();
const losing = makeContentLosingManager(LOSS_SENTINEL);
- const warn = spyOn(console, 'warn').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
// The external Y.Text restore below resets the freshness-quiescence clock,
// which also defers the producer guard (a suppressed drain's emission is
// knowingly historical). Advance a controlled clock past the window so the
// post-restore drain is guard-adjudicated and the dedup map is what
// decides — the semantics this test pins.
let clock = 1_000_000;
- const nowSpy = spyOn(Date, 'now').mockImplementation(() => clock);
+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => clock);
const cleanup = setupServerObservers(
baseOpts({
doc,
@@ -473,7 +475,8 @@ describe('Producer guard (FR6) — packaged posture logs + checkpoints, never th
// permanently closes the recovery window for that pre-loss content.
const { doc, xmlFragment, ytext } = createDoc();
const losing = makeContentLosingManager(LOSS_SENTINEL);
- const warn = spyOn(console, 'warn').mockImplementation(() => {});
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const logWarn = vi.spyOn(getLogger('server-observers'), 'warn');
// A shadow whose backing directory is gone: every git op (and thus the
// checkpoint write) rejects. Swapped for the good shadow after the failure.
const brokenRoot = await mkdtemp(resolve(tmpdir(), 'ok-producer-guard-broken-'));
@@ -499,8 +502,8 @@ describe('Producer guard (FR6) — packaged posture logs + checkpoints, never th
);
const failureLogged = async (tries = 120): Promise<boolean> => {
for (let i = 0; i < tries; i++) {
- const hit = warn.mock.calls
- .map((call) => String(call[0]))
+ const hit = logWarn.mock.calls
+ .map((call) => String(call[1]))
.some((line) => line.includes('checkpoint write failed'));
if (hit) return true;
await new Promise((r) => setTimeout(r, 25));
@@ -521,7 +524,7 @@ describe('Producer guard (FR6) — packaged posture logs + checkpoints, never th
// retry drain must be guard-adjudicated for the re-write to be
// attempted at all.
const retryClockBase = Date.now();
- const retryNowSpy = spyOn(Date, 'now').mockImplementation(() => retryClockBase + 2_001);
+ const retryNowSpy = vi.spyOn(Date, 'now').mockImplementation(() => retryClockBase + 2_001);
try {
seedFragment(doc, xmlFragment, cellBody('keepB'));
} finally {
@@ -531,6 +534,7 @@ describe('Producer guard (FR6) — packaged posture logs + checkpoints, never th
// window is permanently closed and the assertion fails.
expect((await waitForCheckpointRefs(shadow)).length).toBeGreaterThanOrEqual(1);
} finally {
+ logWarn.mockRestore();
warn.mockRestore();
cleanup();
}
diff --git a/packages/server/src/server-observers.test.ts b/packages/server/src/server-observers.test.ts
index ad6abba14..924114c66 100644
--- a/packages/server/src/server-observers.test.ts
+++ b/packages/server/src/server-observers.test.ts
@@ -18,7 +18,7 @@
* `afterAllTransactions` settlement listener — tests assert post-transact
* state directly with no scheduler flushing.
*/
-import { describe, expect, test } from 'bun:test';
+
import type { LocalTransactionOrigin } from '@hocuspocus/server';
import {
MarkdownManager,
@@ -30,12 +30,14 @@ import {
} from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
+import { describe, expect, test, vi } from 'vitest';
import * as Y from 'yjs';
import { AGENT_WRITE_ORIGIN } from './agent-sessions.ts';
import { MANAGED_RENAME_ORIGIN, ROLLBACK_ORIGIN } from './api-extension.ts';
import { composeAndWriteRawBody } from './bridge-intake.ts';
import { __resetBridgeWatchdogForTests } from './bridge-watchdog.ts';
import { FILE_WATCHER_ORIGIN } from './external-change.ts';
+import { getLogger } from './logger.ts';
import { getMetrics, resetMetrics } from './metrics.ts';
import {
OBSERVER_SYNC_ORIGIN,
@@ -1037,14 +1039,10 @@ describe('Server Observer B — error recovery paths', () => {
const errorsBefore = getMetrics().serverObserverErrorsB;
- // Capture the originals — we'll restore after the throw fires so the
- // post-sync serialize path exercises the fallback branch without
- // breaking subsequent reads.
- const originalWarn = console.warn;
- const warnings: string[] = [];
- console.warn = (...args: unknown[]) => {
- warnings.push(args.map(String).join(' '));
- };
+ // Capture the warn through the subsystem logger — restored after the
+ // throw fires so the post-sync serialize path exercises the fallback
+ // branch without breaking subsequent reads.
+ const warnSpy = vi.spyOn(getLogger('server-observers'), 'warn');
// Arm: serialize() will throw exactly once during the post-sync watchdog
// setup inside runObserverBSync. Under contract, the post-sync
@@ -1074,7 +1072,8 @@ describe('Server Observer B — error recovery paths', () => {
// Restore before any subsequent assertions that serialize.
stub.mdManager.serialize = originalSerialize;
- console.warn = originalWarn;
+ const warnings = warnSpy.mock.calls.map((call) => String(call[1] ?? ''));
+ warnSpy.mockRestore();
// The warn-branch (post-sync re-serialization failed) fired.
expect(warnings.some((w) => w.includes('Post-sync re-serialization failed'))).toBe(true);
diff --git a/packages/server/src/server-observers.ts b/packages/server/src/server-observers.ts
index 688a4a0f4..10001217b 100644
--- a/packages/server/src/server-observers.ts
+++ b/packages/server/src/server-observers.ts
@@ -83,11 +83,13 @@ import { registerBridgeDirtyProbe } from './server-workload-telemetry.ts';
import { type ShadowHandle, saveInMemoryCheckpoint } from './shadow-repo.ts';
import { setActiveSpanAttributes, withSpanSync } from './telemetry.ts';
+const log = getLogger('server-observers');
+
/**
- * Pino line for checkpoint-write failures, alongside the existing
- * console.warn: a failed checkpoint means the recovery snapshot for a
- * detected content-loss event was NOT persisted, and the pino sink is what
- * reaches the local log files (and, through them, diagnostics bundles).
+ * Structured record for checkpoint-write failures, alongside the
+ * human-readable observer warn: a failed checkpoint means the recovery
+ * snapshot for a detected content-loss event was NOT persisted, and the
+ * kind-tagged fields are what diagnostics bundles key on.
*/
const checkpointLog = getLogger('server-observers');
@@ -289,9 +291,9 @@ export function __resetMapDrivenParseErrorWarnForTests(): void {
function warnOnceMapDrivenParseError(docName: string | undefined, err: unknown): void {
if (mapDrivenParseErrorWarned) return;
mapDrivenParseErrorWarned = true;
- console.warn(
- `[Server Observer A] Map-driven splice parse/serialize threw (doc: ${docName ?? 'unknown'}); drains fall back to the incremental diff (warned once; further failures count in mapDrivenSpliceFallback only):`,
- err instanceof Error ? err.message : String(err),
+ log.warn(
+ { docName: docName ?? 'unknown', err: err instanceof Error ? err : new Error(String(err)) },
+ `[Server Observer A] Map-driven splice parse/serialize threw (doc: ${docName ?? 'unknown'}); drains fall back to the incremental diff (warned once; further failures count in mapDrivenSpliceFallback only)`,
);
}
@@ -680,11 +682,7 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
.catch((checkpointErr: unknown) => {
const err =
checkpointErr instanceof Error ? checkpointErr : new Error(String(checkpointErr));
- console.warn('[Server Observer A] Silent checkpoint write failed:', {
- name: err.name,
- message: err.message,
- stack: err.stack?.split('\n').slice(0, 4).join('\n'),
- });
+ log.warn({ err }, '[Server Observer A] Silent checkpoint write failed');
checkpointLog.warn(
{ err, 'doc.name': opts.docName ?? null, branch, kind: 'bridge-merge-loss' },
'checkpoint write failed',
@@ -726,7 +724,7 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
);
}
} catch (telErr) {
- console.warn('[Server Observer A] Split-brain telemetry failed:', telErr);
+ log.warn({ err: telErr }, '[Server Observer A] Split-brain telemetry failed');
}
};
@@ -767,12 +765,7 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
.catch((checkpointErr: unknown) => {
const e =
checkpointErr instanceof Error ? checkpointErr : new Error(String(checkpointErr));
- console.warn('[Server Observer A] Duplication checkpoint write failed:', {
- docName,
- name: e.name,
- message: e.message,
- stack: e.stack?.split('\n').slice(0, 4).join('\n'),
- });
+ log.warn({ docName, err: e }, '[Server Observer A] Duplication checkpoint write failed');
checkpointLog.warn(
{ err: e, 'doc.name': docName, branch, kind: 'observer-a-duplication' },
'checkpoint write failed',
@@ -989,9 +982,9 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
}
} catch (err) {
incrementServerObserverError('a');
- console.warn(
- '[Server Observer A] Baseline init failed — starting from empty snapshot:',
- err instanceof Error ? err.message : String(err),
+ log.warn(
+ { err: err instanceof Error ? err : new Error(String(err)) },
+ '[Server Observer A] Baseline init failed — starting from empty snapshot',
);
// Canonical '' fails gate 1 open (no short-circuit until a real
// settlement); the raw witness still snapshots Y.Text so a Path B fire
@@ -1113,11 +1106,7 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
}
const e =
checkpointErr instanceof Error ? checkpointErr : new Error(String(checkpointErr));
- console.warn('[Server Observer A] Producer-guard checkpoint write failed:', {
- name: e.name,
- message: e.message,
- stack: e.stack?.split('\n').slice(0, 4).join('\n'),
- });
+ log.warn({ err: e }, '[Server Observer A] Producer-guard checkpoint write failed');
checkpointLog.warn(
{ err: e, 'doc.name': docName, branch, kind: 'producer-guard-loss' },
'checkpoint write failed',
@@ -1596,7 +1585,7 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
throw err;
}
incrementServerObserverError('a');
- console.error('[Server Observer A] Failed to sync tree→text:', err);
+ log.error({ err }, '[Server Observer A] Failed to sync tree→text');
// Reset the witnesses so the next retry computes a fresh delta instead
// of re-applying the stale diff that just failed. The naive reset
// records the raw Y.Text as a settled witness, but if the throw
@@ -1635,13 +1624,13 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
// B's byte-protective merge instead of an unguarded rewrite. An
// operator triaging the double failure needs the doc and the original
// error correlated in one line, not two disconnected ones.
- console.warn(
- '[Server Observer A] Baseline recovery also failed',
- JSON.stringify({
- 'doc.name': opts.docName ?? null,
+ log.warn(
+ {
+ docName: opts.docName ?? null,
originalError: err instanceof Error ? err.message : String(err),
recoveryError: innerErr instanceof Error ? innerErr.message : String(innerErr),
- }),
+ },
+ '[Server Observer A] Baseline recovery also failed',
);
// Last-resort unknown-baseline sentinel: no canonical form is
// computable (the recovery serialize threw too), so the divergence
@@ -1715,9 +1704,9 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
priorFmForTelemetry = frontmatter;
} catch (err) {
incrementServerObserverError('a');
- console.warn(
- '[Server Observer A] Paired-write baseline refresh failed — falling through to settlement:',
- err instanceof Error ? err.message : String(err),
+ log.warn(
+ { err: err instanceof Error ? err : new Error(String(err)) },
+ '[Server Observer A] Paired-write baseline refresh failed — falling through to settlement',
);
// Fall through to the settlement path so the next afterAllTransactions
// dispatch can recover. The runObserverASync catch block resets the
@@ -1745,7 +1734,7 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
recordSettledBaselines(md);
} catch (err) {
incrementServerObserverError('a');
- console.error('[Server Observer A] Failed initial sync:', err);
+ log.error({ err }, '[Server Observer A] Failed initial sync');
// Reset baselines to match Y.Text's actual state (still empty) so the
// next Observer A firing treats the entire XmlFragment as new content
// via Path A (incremental diff from empty → full doc). Without this,
@@ -1863,9 +1852,9 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
if (reserializeErr instanceof BridgeInvariantViolationError) {
throw reserializeErr;
}
- console.warn(
- '[Server Observer B] Post-sync re-serialization failed — using input body as baseline:',
- reserializeErr,
+ log.warn(
+ { err: reserializeErr },
+ '[Server Observer B] Post-sync re-serialization failed — using input body as baseline',
);
recordSettledBaselines(prependFrontmatter(frontmatter, body));
}
@@ -1877,7 +1866,7 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
throw err;
}
incrementServerObserverError('b');
- console.error('[Server Observer B] Failed to sync text→tree:', err);
+ log.error({ err }, '[Server Observer B] Failed to sync text→tree');
// Reset the canonical witness to current XmlFragment state so the next
// retry computes a fresh delta instead of re-applying the stale diff
// that just failed. The raw witness is deliberately NOT touched: this
@@ -1900,7 +1889,7 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
if (innerErr instanceof BridgeInvariantViolationError) {
throw innerErr;
}
- console.warn('[Server Observer B] Baseline recovery also failed:', innerErr);
+ log.warn({ err: innerErr }, '[Server Observer B] Baseline recovery also failed');
}
}
};
@@ -1947,9 +1936,9 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
priorFmForTelemetry = frontmatter;
} catch (err) {
incrementServerObserverError('b');
- console.warn(
- '[Server Observer B] Paired-write baseline refresh failed — falling through to settlement:',
- err instanceof Error ? err.message : String(err),
+ log.warn(
+ { err: err instanceof Error ? err : new Error(String(err)) },
+ '[Server Observer B] Paired-write baseline refresh failed — falling through to settlement',
);
// Fall through so the next afterAllTransactions can reconcile via
// runObserverBSync's own recovery branches.
diff --git a/packages/server/src/shadow-lock.ts b/packages/server/src/shadow-lock.ts
index b279e5db4..f08076f71 100644
--- a/packages/server/src/shadow-lock.ts
+++ b/packages/server/src/shadow-lock.ts
@@ -9,8 +9,11 @@
import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
import { hostname } from 'node:os';
import { resolve } from 'node:path';
+import { getLogger } from './logger.ts';
import { isProcessAlive, isValidLockPid } from './process-alive.ts';
+const log = getLogger('shadow-lock');
+
export interface LockMetadata {
pid: number;
hostname: string;
@@ -34,7 +37,7 @@ export function acquireLock(shadowDir: string, worktreeRoot: string): string {
existing = JSON.parse(readFileSync(lockPath, 'utf-8')) as LockMetadata;
} catch {
// Corrupt lock file — treat as stale
- console.warn(`[shadow-lock] Corrupt lock file at ${lockPath} — replacing`);
+ log.warn({ lockPath }, `Corrupt lock file at ${lockPath} — replacing`);
}
if (existing && !isValidLockPid(existing.pid)) {
@@ -42,8 +45,9 @@ export function acquireLock(shadowDir: string, worktreeRoot: string): string {
// isProcessAlive. The shadow-lock dir lives under user-writable `.git/ok/`,
// so the validator is the trust boundary between disk-supplied data and
// signal-delivery / liveness probes. Treat as stale.
- console.warn(
- `[shadow-lock] Invalid lock pid (${String(existing.pid)}) at ${lockPath} — replacing`,
+ log.warn(
+ { lockPath, pid: String(existing.pid) },
+ `Invalid lock pid (${String(existing.pid)}) at ${lockPath} — replacing`,
);
existing = null;
}
@@ -59,8 +63,9 @@ export function acquireLock(shadowDir: string, worktreeRoot: string): string {
`Only one active writer instance may mutate a given shadow root at a time.`,
);
} else {
- console.warn(
- `[shadow-lock] Stale lock detected (pid=${existing.pid}, host=${existing.hostname}) — replacing`,
+ log.warn(
+ { pid: existing.pid, host: existing.hostname },
+ `Stale lock detected (pid=${existing.pid}, host=${existing.hostname}) — replacing`,
);
}
}
diff --git a/packages/server/src/shadow-repo.test.ts b/packages/server/src/shadow-repo.test.ts
index 05ab745df..a4a2a12fb 100644
--- a/packages/server/src/shadow-repo.test.ts
+++ b/packages/server/src/shadow-repo.test.ts
@@ -10,6 +10,7 @@ import {
} from '@inkeep/open-knowledge-core/shadow-repo-layout';
import simpleGit from 'simple-git';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { getLogger } from './logger.ts';
import {
buildWipTree,
commitUpstreamImport,
@@ -145,7 +146,7 @@ describe('initShadowRepo', () => {
writeFileSync(resolve(legacyDir, 'LEGACY_SENTINEL'), 'legacy');
writeFileSync(resolve(newDir, 'NEW_SENTINEL'), 'new');
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(getLogger('shadow-repo'), 'warn');
try {
await initShadowRepo(projectRoot);
@@ -154,7 +155,7 @@ describe('initShadowRepo', () => {
expect(existsSync(resolve(newDir, 'NEW_SENTINEL'))).toBe(true);
// Warning was emitted
- const warnings = warnSpy.mock.calls.map((call) => String(call[0] ?? ''));
+ const warnings = warnSpy.mock.calls.map((call) => String(call[1] ?? ''));
expect(warnings.some((w) => w.includes('[shadow-repo] unexpected legacy + new shadow'))).toBe(
true,
);
@@ -236,11 +237,11 @@ describe('buildWipTree persistent fan-out index', () => {
const tree1 = await buildWipTree(shadow, 'content');
writeFileSync(resolve(shadow.gitDir, 'index-wip-fanout'), 'not a git index');
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(getLogger('shadow-repo'), 'warn');
try {
const tree2 = await buildWipTree(shadow, 'content');
expect(tree2).toBe(tree1);
- const warnings = warnSpy.mock.calls.map((call) => String(call[0] ?? ''));
+ const warnings = warnSpy.mock.calls.map((call) => String(call[1] ?? ''));
expect(warnings.some((w) => w.includes('persistent fan-out index failed'))).toBe(true);
} finally {
warnSpy.mockRestore();
@@ -254,11 +255,11 @@ describe('buildWipTree persistent fan-out index', () => {
const tree1 = await buildWipTree(shadow, 'content');
writeFileSync(resolve(shadow.gitDir, 'index-wip-fanout.lock'), '');
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(getLogger('shadow-repo'), 'warn');
try {
const tree2 = await buildWipTree(shadow, 'content');
expect(tree2).toBe(tree1);
- const warnings = warnSpy.mock.calls.map((call) => String(call[0] ?? ''));
+ const warnings = warnSpy.mock.calls.map((call) => String(call[1] ?? ''));
expect(warnings.some((w) => w.includes('persistent fan-out index failed'))).toBe(true);
} finally {
warnSpy.mockRestore();
diff --git a/packages/server/src/shadow-repo.ts b/packages/server/src/shadow-repo.ts
index 3c5641904..c7aaaa2d7 100644
--- a/packages/server/src/shadow-repo.ts
+++ b/packages/server/src/shadow-repo.ts
@@ -44,11 +44,14 @@ import {
import simpleGit from 'simple-git';
import { tracedMkdirSync, tracedRenameSync, tracedWriteFileSync } from './fs-traced.ts';
import { listTreeLongEntries } from './git-paths.ts';
+import { getLogger } from './logger.ts';
import { incrementShadowMigrationLegacyRefsDeleted } from './metrics.ts';
import { acquireLock, releaseLock } from './shadow-lock.ts';
import { releaseShadowOpGate, shadowOpGateFor } from './shadow-op-gate.ts';
import { withSpan } from './telemetry.ts';
+const log = getLogger('shadow-repo');
+
// ─── Types ───────────────────────────────────────────────────────────────────
export interface ShadowHandle {
@@ -224,7 +227,10 @@ export async function initShadowRepo(projectRoot: string): Promise<ShadowHandle>
if (legacyExists && !newExists) {
tracedRenameSync(legacyDir, shadowDir);
} else if (legacyExists && newExists) {
- console.warn('[shadow-repo] unexpected legacy + new shadow both present — no rename performed');
+ log.warn(
+ { legacyDir, shadowDir },
+ '[shadow-repo] unexpected legacy + new shadow both present — no rename performed',
+ );
}
// Skip init if already valid
@@ -250,7 +256,7 @@ export async function initShadowRepo(projectRoot: string): Promise<ShadowHandle>
try {
await configureShadowGc(handle);
} catch (e) {
- console.warn('[shadow-repo] failed to write gc config (non-fatal):', e);
+ log.warn({ err: e }, 'failed to write gc config (non-fatal)');
}
// Allowlist-based sweep of legacy WIP refs on every start.
@@ -337,12 +343,13 @@ export async function sweepLegacyShadowRefs(shadow: ShadowHandle): Promise<numbe
await sg.raw('update-ref', '-d', ref);
deleted++;
} catch (e) {
- console.warn(`[shadow-migration] failed to delete legacy ref ${ref}:`, e);
+ log.warn({ ref, err: e }, `[shadow-migration] failed to delete legacy ref ${ref}`);
}
}
});
incrementShadowMigrationLegacyRefsDeleted(deleted);
- console.warn(
+ log.warn(
+ { deleted, server: breakdown.server, human: breakdown['human-'], upstream: breakdown.upstream },
`[shadow-migration] deleted ${deleted} legacy refs: server=${breakdown.server} human-=${breakdown['human-']} upstream=${breakdown.upstream}`,
);
@@ -417,7 +424,7 @@ async function commitWipInner(
if (msg.includes('unknown revision') || msg.includes('bad revision')) {
// Expected: first commit on this ref — start fresh
} else {
- console.error(`[shadow-repo] Unexpected error seeding index for ${ref}:`, e);
+ log.error({ ref, err: e }, `Unexpected error seeding index for ${ref}`);
throw e;
}
}
@@ -441,7 +448,7 @@ async function commitWipInner(
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
if (!msg.includes('unknown revision') && !msg.includes('bad revision')) {
- console.error(`[shadow-repo] Unexpected error resolving ${ref}:`, e);
+ log.error({ ref, err: e }, `Unexpected error resolving ${ref}`);
throw e;
}
// Expected: no parent — first commit on this ref
@@ -576,9 +583,9 @@ async function buildWipTreeInner(shadow: ShadowHandle, contentRoot: string): Pro
try {
return await buildWipTreeWithIndex(shadow, contentRoot, persistentIndex);
} catch (e) {
- console.warn(
- '[shadow-repo] persistent fan-out index failed — rebuilding from a fresh index:',
- e,
+ log.warn(
+ { err: e },
+ '[shadow-repo] persistent fan-out index failed — rebuilding from a fresh index',
);
for (const stale of [persistentIndex, `${persistentIndex}.lock`]) {
try {
@@ -643,7 +650,7 @@ async function commitWipFromTreeInner(
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
if (!msg.includes('unknown revision') && !msg.includes('bad revision')) {
- console.error(`[shadow-repo] Unexpected error resolving ${ref}:`, e);
+ log.error({ ref, err: e }, `Unexpected error resolving ${ref}`);
throw e;
}
}
@@ -1337,7 +1344,7 @@ async function gcCheckpointRefsInner(
try {
await sg.raw('update-ref', '-d', ref);
} catch (err) {
- console.warn('[checkpoint-gc] failed to delete', ref, err);
+ log.warn({ ref, err }, `[checkpoint-gc] failed to delete ${ref}`);
}
}
@@ -1546,7 +1553,7 @@ export async function readParkedState(
const diskSnapshot = (await sg.raw('show', `${refSha}:.park-base/${docName}`)).trim();
return { markdown, diskSnapshot };
} catch (e) {
- console.error(`[shadow] Failed to read parked state for ${docName} from ${ref}:`, e);
+ log.error({ docName, ref, err: e }, `Failed to read parked state for ${docName} from ${ref}`);
throw e;
}
}
diff --git a/packages/server/src/showall-stream.test.ts b/packages/server/src/showall-stream.test.ts
index 9f58da864..2f9477e15 100644
--- a/packages/server/src/showall-stream.test.ts
+++ b/packages/server/src/showall-stream.test.ts
@@ -6,7 +6,7 @@
* abort-on-disconnect bails the generator, and partial consumption never
* materializes the whole tree.
*/
-import { afterEach, describe, expect, spyOn, test } from 'bun:test';
+
import {
chmodSync,
mkdirSync,
@@ -18,6 +18,7 @@ import {
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { ASSET_EXTENSIONS, type DocumentListEntry } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, test, vi } from 'vitest';
import {
__getShowAllWalkStatsForTesting,
__resetShowAllWalkStatsForTesting,
@@ -26,6 +27,7 @@ import {
walkContentDirForShowAll,
} from './api-extension.ts';
import { createContentFilter } from './content-filter.ts';
+import { getLogger } from './logger.ts';
function makeFlatFixture(fileCount: number): string {
const dir = realpathSync(mkdtempSync(join(tmpdir(), 'ok-showall-stream-')));
@@ -384,7 +386,7 @@ describe('streamShowAllEntries — unreadable directory mid-queue', () => {
writeFileSync(join(dir, 'open', 'visible.md'), '# visible\n');
chmodSync(join(dir, 'locked'), 0o000);
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(getLogger('api'), 'warn');
try {
const { entries, truncated } = await drain(
streamShowAllEntries(streamOptsFor(dir, 50_000)),
@@ -408,9 +410,9 @@ describe('streamShowAllEntries — unreadable directory mid-queue', () => {
// whichever guard (realpath/readdir) fired.
const lockedWarn = warnSpy.mock.calls.find(
(call) =>
- typeof call[0] === 'string' &&
- call[0].includes('failed for') &&
- call[0].includes('locked'),
+ typeof call[1] === 'string' &&
+ call[1].includes('failed for') &&
+ call[1].includes('locked'),
);
expect(lockedWarn).toBeDefined();
} finally {
diff --git a/packages/server/src/skill-install-events.ts b/packages/server/src/skill-install-events.ts
index 017a557f3..58a8e94aa 100644
--- a/packages/server/src/skill-install-events.ts
+++ b/packages/server/src/skill-install-events.ts
@@ -17,6 +17,7 @@
import { dirname, join } from 'node:path';
import type { BundleId } from './build-skill-zip.ts';
import { tracedMkdir, tracedWriteFile } from './fs-traced.ts';
+import { getLogger } from './logger.ts';
import type { SkillStateLogger, SkillStateTarget } from './skill-state.ts';
/** File path relative to `$HOME` where install-state events are appended. */
@@ -88,7 +89,7 @@ export async function recordSkillInstallEvent(
const warn =
deps?.warn ??
((data: unknown, message: string) => {
- console.warn(message, data);
+ getLogger('skills').warn(data, message);
});
const home = homedirFn();
diff --git a/packages/server/src/skill-install.ts b/packages/server/src/skill-install.ts
index 92fd482b1..db202c7ea 100644
--- a/packages/server/src/skill-install.ts
+++ b/packages/server/src/skill-install.ts
@@ -9,6 +9,7 @@ import {
} from './build-skill-zip.ts';
import { withHiddenWindowsConsole } from './child-process-windows-hide.ts';
import { tracedMkdir } from './fs-traced.ts';
+import { getLogger } from './logger.ts';
import { BUNDLE_SKILL_NAME, type BundleId } from './skill-bundles.ts';
import { recordSkillInstallEvent, type SkillInstallEventOutcome } from './skill-install-events.ts';
import {
@@ -291,8 +292,8 @@ export async function installUserSkill(
): Promise<InstallUserSkillResult> {
const home = opts.home ?? homedir();
const logger: SkillInstallLogger = opts.logger ?? {
- warn: (data, message) => console.warn(message, data),
- info: (data, message) => console.info(message, data),
+ warn: (data, message) => getLogger('skills').warn(data, message),
+ info: (data, message) => getLogger('skills').info(data, message),
};
const spawnFn = opts.spawn ?? (spawn as SpawnLike);
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
diff --git a/packages/server/src/skill-state.ts b/packages/server/src/skill-state.ts
index 1565b6812..cf2c080ef 100644
--- a/packages/server/src/skill-state.ts
+++ b/packages/server/src/skill-state.ts
@@ -45,6 +45,7 @@ import {
import { atomicWriteFile, withFileLock } from '@inkeep/open-knowledge-core/server';
import { type ParsedNode, parseDocument } from 'yaml';
import { tracedAtomicFs, tracedMkdir } from './fs-traced.ts';
+import { getLogger } from './logger.ts';
const readFileAsync = promisify(readFile);
@@ -96,13 +97,12 @@ export interface SkillStateLogger {
}
/**
- * Console-backed logger used as the default when callers don't pass one.
- * Emits structured payloads via `console.warn(message, data)` so the
- * `event` field stays observable in stdout/journald regardless of whether
- * a Pino logger is wired.
+ * Default sink when callers don't pass a logger. Routes through the shared
+ * pino factory so the `event` field lands on both the console stream and
+ * the file sink that bug-report bundles collect.
*/
const DEFAULT_LOGGER: SkillStateLogger = {
- warn: (data, message) => console.warn(message, data),
+ warn: (data, message) => getLogger('skills').warn(data, message),
};
/**
diff --git a/packages/server/src/spawn-cursor-api.ts b/packages/server/src/spawn-cursor-api.ts
index df163e810..107d6bde2 100644
--- a/packages/server/src/spawn-cursor-api.ts
+++ b/packages/server/src/spawn-cursor-api.ts
@@ -59,6 +59,7 @@ import {
readBoundedJsonBody,
} from './http/request-validation.ts';
import { successResponse } from './http/success-response.ts';
+import { getLogger } from './logger.ts';
import { spawnDetached as spawnDetachedReal } from './spawn-detached.ts';
const SPAWN_CURSOR_WHICH_TIMEOUT_MS = 500;
@@ -318,10 +319,9 @@ export async function resolveCursorBinaryDefault(timeoutMs: number): Promise<str
} catch (err) {
const code = (err as NodeJS.ErrnoException | undefined)?.code;
if (code !== 'ENOENT' && code !== 'EACCES' && code !== 'EPERM') {
- console.warn(
- '[spawn-cursor] unexpected fs.access error on bundle probe:',
- code,
- candidate,
+ getLogger('spawn-cursor').warn(
+ { code, candidate },
+ 'unexpected fs.access error on bundle probe',
);
}
}
@@ -438,7 +438,7 @@ export function isPathWithinDir(
// the root cause instead of investigating a phantom path-escape. Same
// narrow-and-log pattern as `resolveCursorBinaryDefault` and
// `spawnDetachedReal` in this file.
- console.warn('[spawn-cursor] unexpected path-resolution error:', err);
+ getLogger('spawn-cursor').warn({ err }, 'unexpected path-resolution error');
return false;
}
}
diff --git a/packages/server/src/spawn-detached.ts b/packages/server/src/spawn-detached.ts
index 992d708e3..943d6653d 100644
--- a/packages/server/src/spawn-detached.ts
+++ b/packages/server/src/spawn-detached.ts
@@ -21,6 +21,7 @@
import { spawn as nodeSpawn, type SpawnOptions } from 'node:child_process';
import { withHiddenWindowsConsole } from './child-process-windows-hide.ts';
+import { getLogger } from './logger.ts';
const DETACHED_IGNORED_STDIO_OPTIONS: Pick<SpawnOptions, 'detached' | 'stdio' | 'shell'> = {
detached: true,
@@ -79,7 +80,7 @@ export function spawnDetached(
settle({ ok: true });
});
} catch (err) {
- console.warn('[spawn-detached] synchronous spawn throw:', err);
+ getLogger('spawn-detached').warn({ err }, 'synchronous spawn throw');
clearTimeout(timer);
settle(classifySpawnError(err));
}
diff --git a/packages/server/src/sync-handshake-span-extension.ts b/packages/server/src/sync-handshake-span-extension.ts
index a7c2e06d3..a205c77a9 100644
--- a/packages/server/src/sync-handshake-span-extension.ts
+++ b/packages/server/src/sync-handshake-span-extension.ts
@@ -33,6 +33,7 @@
import type { Extension } from '@hocuspocus/server';
import type { Attributes } from '@opentelemetry/api';
import { isConfigDoc, isSystemDoc } from './cc1-broadcast.ts';
+import { getLogger } from './logger.ts';
import { withSpanSync } from './telemetry.ts';
/**
@@ -66,20 +67,12 @@ export function createSyncHandshakeSpanExtension(): Extension {
try {
withSpanSync('sync.handshake', { attributes }, () => {});
} catch (err) {
- // Bracket-prefix `console.warn` is intentional here: this is an ad-hoc
- // ops warning meant to
- // surface a misbehaving SDK to a human reading the console, not
- // an event counted in aggregate or asserted in tests. Promoting
- // to `getLogger('sync-handshake-span').warn` would require a
- // consumer that doesn't yet exist; revisit if telemetry analysis
- // grows a need to alert on OTel SDK fault rates.
- //
- // Pass the Error through so Node renders its `.stack` — coercing to
- // `.message` discards the call-frame info needed to triage a rare
- // OTel SDK fault.
- console.warn(
- '[sync-handshake-span] emission failed:',
- err instanceof Error ? err : String(err),
+ // Pass the Error through under `err` so the pino serializer keeps
+ // its `.stack` — coercing to `.message` discards the call-frame
+ // info needed to triage a rare OTel SDK fault.
+ getLogger('sync-handshake-span').warn(
+ { err: err instanceof Error ? err : new Error(String(err)) },
+ 'emission failed',
);
}
},
diff --git a/packages/server/src/tag-index.ts b/packages/server/src/tag-index.ts
index be099032d..43cf7f585 100644
--- a/packages/server/src/tag-index.ts
+++ b/packages/server/src/tag-index.ts
@@ -41,8 +41,11 @@ import {
import { isLinkIndexExcludedDoc } from './cc1-broadcast.ts';
import type { ContentFilter } from './content-filter.ts';
import { isSupportedDocFile, stripDocExtension } from './doc-extensions.ts';
+import { getLogger } from './logger.ts';
import { toPosix } from './path-utils.ts';
+const log = getLogger('tag-index');
+
/**
* Inline-tag pattern for server-side body scanning. Sourced from
* `core/markdown/tag-promotion.ts` via `createTagInTextRegex` so client-
@@ -210,7 +213,7 @@ export class TagIndex {
this.applyDocSnapshot(docName, authoredTags, expanded);
} catch (err) {
- console.warn(`[tag-index] Failed to scan ${docName} for tag extraction:`, err);
+ log.warn({ docName, err }, `Failed to scan ${docName} for tag extraction`);
this.deleteDocument(docName);
}
}
@@ -336,7 +339,7 @@ export class TagIndex {
// doesn't poison every subsequent init() call. The breadcrumb keeps a
// trace when a caller drops the returned promise without handling it.
this.initChain = run.catch((err) => {
- console.warn('[tag-index] init failed (chain cleared for next init):', err);
+ log.warn({ err }, 'init failed (chain cleared for next init)');
});
return run;
}
@@ -355,7 +358,7 @@ export class TagIndex {
try {
return { docName, markdown: await readFile(filePath, 'utf-8') };
} catch (err) {
- console.warn(`[tag-index] Failed to read ${docName} during init:`, err);
+ log.warn({ docName, err }, `Failed to read ${docName} during init`);
return null;
}
}),
@@ -365,7 +368,10 @@ export class TagIndex {
try {
this.updateDocumentFromMarkdown(result.docName, result.markdown);
} catch (err) {
- console.warn(`[tag-index] Failed to index ${result.docName} during init:`, err);
+ log.warn(
+ { docName: result.docName, err },
+ `Failed to index ${result.docName} during init`,
+ );
}
}
}
@@ -433,7 +439,7 @@ export class TagIndex {
try {
entries = await readdir(dir, { withFileTypes: true });
} catch (err) {
- console.warn(`[tag-index] Failed to read directory ${dir}:`, err);
+ log.warn({ dir, err }, `Failed to read directory ${dir}`);
return;
}
for (const entry of entries) {
diff --git a/packages/server/src/timeline-query.test.ts b/packages/server/src/timeline-query.test.ts
index be021a6c5..5b6522987 100644
--- a/packages/server/src/timeline-query.test.ts
+++ b/packages/server/src/timeline-query.test.ts
@@ -5,7 +5,8 @@ import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { formatOkActor, type OkActorEntry } from '@inkeep/open-knowledge-core/shadow-repo-layout';
import simpleGit from 'simple-git';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { getLogger } from './logger.ts';
import {
appendRenameLogEntry,
createEmptyIndex,
@@ -915,12 +916,12 @@ describe('getDocumentHistory — rename-history mitigation (US-004)', () => {
appendRenameLogEntry(shadow.gitDir, entry({ from: 'b', to: 'c', commitSha: renameBC }), index);
setRenameLogIndex(shadow.gitDir, index);
- const origWarn = console.warn;
let warnedSkip = false;
- console.warn = (...args: unknown[]) => {
- const msg = args.map(String).join(' ');
- if (msg.includes('predecessor walk failed for step')) warnedSkip = true;
- };
+ const warnSpy = vi
+ .spyOn(getLogger('timeline'), 'warn')
+ .mockImplementation((_data: unknown, msg: string) => {
+ if (msg.includes('predecessor walk failed for step')) warnedSkip = true;
+ });
try {
const result = await getDocumentHistory(shadow, { docName: 'c' }, 'content/docs');
const shas = result.entries.map((e) => e.sha);
@@ -934,7 +935,7 @@ describe('getDocumentHistory — rename-history mitigation (US-004)', () => {
// unbounded current-name walk and survive regardless of step 0's fate.
expect(shas).toContain(renameBC);
} finally {
- console.warn = origWarn;
+ warnSpy.mockRestore();
}
expect(warnedSkip).toBe(true);
}, 15_000);
diff --git a/packages/server/src/timeline-query.ts b/packages/server/src/timeline-query.ts
index d755cb6ae..757ebd260 100644
--- a/packages/server/src/timeline-query.ts
+++ b/packages/server/src/timeline-query.ts
@@ -24,6 +24,7 @@ import {
readContributors,
} from '@inkeep/open-knowledge-core/shadow-repo-layout';
import { getDocExtension } from './doc-extensions.ts';
+import { getLogger } from './logger.ts';
import { managedArtifactTimelinePaths } from './managed-artifact-persistence.ts';
import {
type AncestorShaSetCache,
@@ -44,6 +45,8 @@ import { shadowGit } from './shadow-repo.ts';
import { getMeter, withSpan } from './telemetry.ts';
import { recordTimelineQuery } from './timeline-telemetry.ts';
+const log = getLogger('timeline');
+
/**
* Depth bound for a history page. Sizing the git-level
* `-n` to 3×(offset+limit) gives the requested window plus slack to absorb
@@ -811,9 +814,9 @@ export async function getDocumentHistory(
if (predEntries.length >= walkCap) windowSaturated = true;
wipEntries = [...wipEntries, ...predEntries];
} catch (e) {
- console.warn(
- `[timeline] predecessor walk failed for step ${i} (${step.path}); skipping:`,
- e,
+ log.warn(
+ { step: i, path: step.path, err: e },
+ `predecessor walk failed for step ${i} (${step.path}); skipping`,
);
}
}
@@ -948,7 +951,7 @@ export async function getDocumentHistory(
hasMore: (windowSaturated && page.length > 0) || offset + limit < total,
};
} catch (e) {
- console.warn('[timeline] getDocumentHistory failed, returning empty result:', e);
+ log.warn({ err: e }, 'getDocumentHistory failed, returning empty result');
// Record the failure with its real elapsed duration AND error=true so a
// timeout storm is distinguishable in the metric
// from a burst of legitimately-empty docs — both otherwise land in
@@ -1062,7 +1065,7 @@ export async function getFolderTimeline(
hasMore: (windowSaturated && page.length > 0) || offset + limit < total,
};
} catch (e) {
- console.warn('[timeline] getFolderTimeline failed, returning empty result:', e);
+ log.warn({ err: e }, 'getFolderTimeline failed, returning empty result');
return EMPTY;
}
}
diff --git a/packages/server/src/tolerance-telemetry-writer.test.ts b/packages/server/src/tolerance-telemetry-writer.test.ts
index 04a0acbbc..4745d5928 100644
--- a/packages/server/src/tolerance-telemetry-writer.test.ts
+++ b/packages/server/src/tolerance-telemetry-writer.test.ts
@@ -1,11 +1,10 @@
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
-
import { emitToleranceFire } from '@inkeep/open-knowledge-core';
-
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { getLogger } from './logger.ts';
import {
initToleranceTelemetryWriter,
isToleranceTelemetryEnabled,
@@ -127,7 +126,7 @@ describe('initToleranceTelemetryWriter', () => {
const logPath = resolve(tmpProjectDir, '.ok', 'local', 'tolerance-telemetry.jsonl');
mkdirSync(logPath, { recursive: true });
- const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(getLogger('tolerance-telemetry'), 'warn');
try {
initToleranceTelemetryWriter(tmpProjectDir);
emitToleranceFire(['crlf'], 'a\r\n', 'a\n', 'doc');
diff --git a/packages/server/src/tolerance-telemetry-writer.ts b/packages/server/src/tolerance-telemetry-writer.ts
index 06e6eae21..df777011c 100644
--- a/packages/server/src/tolerance-telemetry-writer.ts
+++ b/packages/server/src/tolerance-telemetry-writer.ts
@@ -3,6 +3,7 @@ import { resolve } from 'node:path';
import { setToleranceTelemetryHook, type ToleranceFireRecord } from '@inkeep/open-knowledge-core';
import { getLocalDir } from './config/paths.ts';
+import { getLogger } from './logger.ts';
import { RotatingAppender } from './telemetry-file-sink.ts';
const TELEMETRY_FILENAME = 'tolerance-telemetry.jsonl';
@@ -84,9 +85,9 @@ export function initToleranceTelemetryWriter(projectDir: string): void {
void appender?.append(`${JSON.stringify(fireLine)}\n`).catch((err: unknown) => {
if (!appendFailureWarned) {
appendFailureWarned = true;
- console.warn(
- '[tolerance-telemetry] append failed; further failures are silent:',
- err instanceof Error ? err.message : String(err),
+ getLogger('tolerance-telemetry').warn(
+ { err: err instanceof Error ? err : new Error(String(err)) },
+ 'append failed; further failures are silent',
);
}
});