Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 12 additions & 9 deletions src/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -749,22 +749,25 @@ async function recallShapeCheck(config: RuntimeConfig): Promise<DoctorCheck> {
if (result.exitCode !== 0) {
return {name: 'recall shape', status: 'warn', detail: 'search failed; run threadnote repair'};
}
let parsed: unknown;
// Mirror parseRecallHits: `ov find/search --output json` prints a `cmd: ...`
// preamble line before the JSON, and the buckets live under the `result`
// envelope (`{ok, result: {memories, resources, skills}}`). Start at the
// first line beginning with `{`, exactly as recall parsing does — otherwise
// this probe false-warns on a perfectly healthy OpenViking.
const start = result.stdout.search(/^\{/m);
let envelope: unknown;
try {
parsed = JSON.parse(result.stdout.trim());
const parsed: unknown = start >= 0 ? JSON.parse(result.stdout.slice(start)) : undefined;
envelope = isJsonObject(parsed) ? parsed.result : undefined;
} catch {
return {
name: 'recall shape',
status: 'warn',
detail: 'search output is not JSON; recall may silently return nothing',
};
envelope = undefined;
}
const buckets = ['memories', 'resources', 'skills'];
if (!isJsonObject(parsed) || !buckets.some(key => Array.isArray(parsed[key]))) {
if (!isJsonObject(envelope) || !buckets.some(key => Array.isArray(envelope[key]))) {
return {
name: 'recall shape',
status: 'warn',
detail: `search JSON missing ${buckets.join('/')} buckets; recall parsing is out of sync with this OpenViking`,
detail: `search JSON missing the result.{${buckets.join(',')}} buckets recall parsing depends on`,
};
}
return {name: 'recall shape', status: 'ok', detail: 'memories/resources/skills buckets present'};
Expand Down
70 changes: 56 additions & 14 deletions src/mcp_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,10 @@ import {
import {
buildRecallSections,
collectExactMatches,
currentPackageVersion,
type ExactMatch,
errorMessage,
formatStaleVersionNotice,
enrichRecallQueryWithWorkspaceContext,
enrichRecallQueryWithWorkspaceProjectContext,
exactMemoryScopeUris,
Expand Down Expand Up @@ -120,8 +122,44 @@ type CheckedTextArray =
readonly ok: false;
};

// Version this MCP server process started from, captured at startup. A later
// `threadnote update` overwrites the package on disk, but this resident stdio
// process keeps running the old code (clients don't respawn an MCP server on
// update), so we compare against the on-disk version and nudge the caller to
// reconnect — otherwise they silently keep hitting stale code.
let mcpStartupVersion: string | undefined;
let staleNoticeCache: {readonly checkedAtMs: number; readonly notice: string | undefined} | undefined;
const STALE_NOTICE_TTL_MS = 60_000;

async function staleVersionNotice(): Promise<string | undefined> {
if (mcpStartupVersion === undefined) {
return undefined;
}
const nowMs = Date.now();
if (staleNoticeCache && nowMs - staleNoticeCache.checkedAtMs < STALE_NOTICE_TTL_MS) {
return staleNoticeCache.notice;
}
let notice: string | undefined;
try {
notice = formatStaleVersionNotice(mcpStartupVersion, await currentPackageVersion());
} catch {
notice = undefined;
}
staleNoticeCache = {checkedAtMs: nowMs, notice};
return notice;
}

async function withStaleVersionNotice(result: CallToolResult): Promise<CallToolResult> {
const notice = await staleVersionNotice();
if (notice === undefined) {
return result;
}
return {...result, content: [...(result.content ?? []), {type: 'text', text: `⚠ ${notice}`}]};
}

async function main(): Promise<void> {
const config = getRuntimeConfig();
mcpStartupVersion = await currentPackageVersion().catch(() => undefined);
const server = new McpServer(
{name: 'threadnote-local-adapter', version: '0.2.0'},
{
Expand Down Expand Up @@ -336,7 +374,7 @@ function registerTools(server: McpServer, config: RuntimeConfig): void {
description: 'Check OpenViking server health through the CLI.',
inputSchema: {},
},
async () => runOpenVikingMcpTool(config, 'health', {}),
async () => withStaleVersionNotice(await runOpenVikingMcpTool(config, 'health', {})),
);

registerOpenVikingParityTools(server, config);
Expand Down Expand Up @@ -894,14 +932,16 @@ function registerSearchTool(server: McpServer, config: RuntimeConfig, name: stri
if (!checkedUri.ok) {
return checkedUri.error;
}
return runRecallTool(config, {
callerCwd,
query: checkedQuery.value,
pinnedUri: checkedUri.value,
nodeLimit,
includeArchived: includeArchived === true,
threshold: threshold === undefined ? undefined : String(threshold),
});
return withStaleVersionNotice(
await runRecallTool(config, {
callerCwd,
query: checkedQuery.value,
pinnedUri: checkedUri.value,
nodeLimit,
includeArchived: includeArchived === true,
threshold: threshold === undefined ? undefined : String(threshold),
}),
);
},
);
}
Expand Down Expand Up @@ -1179,11 +1219,13 @@ function registerStoreTool(server: McpServer, config: RuntimeConfig, name: strin
timestamp: new Date().toISOString(),
topic: normalizeOptionalMetadata(topic),
};
return writeDurableMemory(config, {
bodyText: checkedText.value,
metadata,
replaceUri: checkedReplaceUri.value,
});
return withStaleVersionNotice(
await writeDurableMemory(config, {
bodyText: checkedText.value,
metadata,
replaceUri: checkedReplaceUri.value,
}),
);
},
);
}
Expand Down
12 changes: 3 additions & 9 deletions src/update.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {constants as fsConstants} from 'node:fs';
import {access, readFile, writeFile} from 'node:fs/promises';
import {access, writeFile} from 'node:fs/promises';
import {homedir} from 'node:os';
import {join} from 'node:path';
import {createInterface} from 'node:readline/promises';
Expand All @@ -13,6 +13,7 @@ import {
ensureDirectory,
errorMessage,
findExecutable,
currentPackageVersion,
findOpenVikingCli,
isExecutable,
isTcpPortOpen,
Expand Down Expand Up @@ -420,14 +421,7 @@ async function getUpdateInfo(
};
}

export async function currentPackageVersion(): Promise<string> {
const rawPackage = await readFile(join(toolRoot(), 'package.json'), 'utf8');
const parsed: unknown = JSON.parse(rawPackage);
if (!isJsonObject(parsed) || typeof parsed.version !== 'string') {
throw new Error('Could not read current threadnote package version.');
}
return parsed.version;
}
export {currentPackageVersion};

export async function fetchLatestVersion(registry: string): Promise<string> {
const url = new URL(`${NPM_PACKAGE_NAME}/latest`, normalizeRegistry(registry));
Expand Down
31 changes: 31 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,28 @@ function safeVersionNumber(value: number | undefined): number {
return typeof value === 'number' && Number.isInteger(value) && value >= 0 ? value : 0;
}

/**
* Returns a reconnect notice when a newer threadnote is installed on disk than
* the version a long-lived process started from — undefined when they match,
* the disk is older, or either version is unknown. Used by the MCP server to
* tell callers their resident stdio server is running stale code.
*/
export function formatStaleVersionNotice(
runningVersion: string | undefined,
diskVersion: string | undefined,
): string | undefined {
if (runningVersion === undefined || diskVersion === undefined) {
return undefined;
}
if (compareVersions(diskVersion, runningVersion) <= 0) {
return undefined;
}
return (
`threadnote ${diskVersion} is installed but this MCP server is still running ${runningVersion}. ` +
'Reconnect the threadnote MCP server (e.g. /mcp) to load the update.'
);
}

export async function readHttpStatus(url: string, timeoutMs: number): Promise<number | undefined> {
return new Promise(resolvePromise => {
const request = httpGet(url, response => {
Expand Down Expand Up @@ -1428,6 +1450,15 @@ export function toolRoot(): string {
return resolve(__dirname, '..');
}

export async function currentPackageVersion(): Promise<string> {
const rawPackage = await readFile(join(toolRoot(), 'package.json'), 'utf8');
const parsed: unknown = JSON.parse(rawPackage);
if (!isJsonObject(parsed) || typeof parsed.version !== 'string') {
throw new Error('Could not read current threadnote package version.');
}
return parsed.version;
}

export function errorMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
20 changes: 20 additions & 0 deletions test/unit/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
formatExactMatchPointers,
formatRecallHits,
formatShellCommand,
formatStaleVersionNotice,
getGlobBase,
globToRegExp,
grepUrisFromJson,
Expand Down Expand Up @@ -113,6 +114,25 @@ describe('reindexWaitTimeoutMs', () => {
});
});

describe('formatStaleVersionNotice', () => {
it('returns a reconnect notice naming both versions when disk is newer', () => {
const notice = formatStaleVersionNotice('1.4.0', '1.4.1');
expect(notice).toContain('1.4.1');
expect(notice).toContain('1.4.0');
expect(notice).toMatch(/reconnect/i);
});

it('returns undefined when versions match or disk is older or equal', () => {
expect(formatStaleVersionNotice('1.4.1', '1.4.1')).toBeUndefined();
expect(formatStaleVersionNotice('1.4.1', '1.4.0')).toBeUndefined();
});

it('returns undefined when either version is unknown', () => {
expect(formatStaleVersionNotice(undefined, '1.4.1')).toBeUndefined();
expect(formatStaleVersionNotice('1.4.0', undefined)).toBeUndefined();
});
});

describe('parseJsonConfigObject', () => {
it('returns the parsed object for valid JSON objects', () => {
expect(parseJsonConfigObject('{"a":1}')).toEqual({a: 1});
Expand Down