fix(cli): pin @claude-flow/memory exactly and warn in doctor on a stale copy (#3392)

`npx @claude-flow/cli@latest` reuses one npx cache directory across CLI
versions, and npm keeps an already-installed dependency that still satisfies
its range. With memory declared as `^3.0.0-alpha.23`, a cached alpha.24 was
never replaced by alpha.25, so a fix that shipped in both packages (#3390)
only half-applied, with no error and `agentdb_health` still reporting healthy.

- Pin `@claude-flow/memory` to `3.0.0-alpha.25` in both `dependencies` and
  `optionalDependencies` (npm resolves the optional entry; they must agree).
  A stale copy can no longer satisfy the spec, so npm has to replace it.
- `doctor` gains a `@claude-flow/memory version` check that compares the copy
  the CLI actually loads (its own module context, not cwd) against its declared
  range and fails with a cache-clear remediation when they diverge. It runs in
  the default suite, `--component memory` and `--component memory-package`.
- v3/pnpm-lock.yaml: minimal hand edit (importer specifier/version plus one
  new registry snapshot); proven with `pnpm@8 install --frozen-lockfile`
  passing on the new lock and failing on the old one.

Verified by reproduction: with memory alpha.24 already installed, adding the
registry cli@3.44.0 (caret) leaves alpha.24; adding a tarball of this branch
upgrades it to alpha.25.

Co-Authored-By: RuFlo <ruv@ruv.net>
This commit is contained in:
ruv committed 2026-09-24 18:07:54 -04:00
1 parent 0a96fb8857
commit 6ff6fded33
4 files changed
+163 -4

No files matched your search

@@ -0,0 +1,69 @@
/**
* #3392: `npx @claude-flow/cli@latest` reuses one npx cache directory across CLI
* versions, and npm keeps an installed dependency that still satisfies a caret
* range — so a stale @claude-flow/memory survived a CLI upgrade with no error.
* The fix is twofold: cli pins memory exactly (so a stale copy can no longer
* satisfy the spec), and doctor reports when the loaded copy drifts from it.
*/
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { evaluateMemoryPackageVersion, checkMemoryPackageVersion } from '../src/commands/doctor.js';
const pkg = JSON.parse(
readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf-8'),
) as { dependencies?: Record<string, string>; optionalDependencies?: Record<string, string> };
describe('#3392 evaluateMemoryPackageVersion', () => {
it('passes when the installed version satisfies an exact pin', () => {
expect(evaluateMemoryPackageVersion('3.0.0-alpha.25', '3.0.0-alpha.25').status).toBe('pass');
});
it('fails on a stale copy that a caret range would have accepted', () => {
const check = evaluateMemoryPackageVersion('3.0.0-alpha.25', '3.0.0-alpha.24');
expect(check.status).toBe('fail');
expect(check.message).toContain('3.0.0-alpha.24');
expect(check.fix).toContain('_npx');
expect(check.fix).toContain('@claude-flow/memory@3.0.0-alpha.25');
});
it('treats prerelease versions inside a prerelease range as satisfying', () => {
expect(evaluateMemoryPackageVersion('^3.0.0-alpha.23', '3.0.0-alpha.25').status).toBe('pass');
});
it('warns, not fails, when the optional package is absent', () => {
const check = evaluateMemoryPackageVersion('3.0.0-alpha.25', null);
expect(check.status).toBe('warn');
expect(check.fix).toContain('--include=optional');
});
it('warns when the declared range cannot be read or compared', () => {
expect(evaluateMemoryPackageVersion(null, '3.0.0-alpha.25').status).toBe('warn');
expect(evaluateMemoryPackageVersion('not a range', '3.0.0-alpha.25').status).toBe('warn');
expect(evaluateMemoryPackageVersion('3.0.0-alpha.25', 'garbage').status).toBe('warn');
});
});
describe('#3392 cli declares an exact @claude-flow/memory pin', () => {
it.each(['dependencies', 'optionalDependencies'] as const)('%s pins memory to one exact version', (field) => {
const spec = pkg[field]?.['@claude-flow/memory'];
expect(spec, `${field} should declare @claude-flow/memory`).toBeDefined();
// Exact semver: no range operators, so a cached older copy cannot satisfy it.
expect(spec).toMatch(/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/);
});
it('declares the same pin in both fields (npm lets optionalDependencies win)', () => {
expect(pkg.optionalDependencies?.['@claude-flow/memory']).toBe(pkg.dependencies?.['@claude-flow/memory']);
});
});
describe('#3392 checkMemoryPackageVersion (real resolution)', () => {
it('reports the copy this CLI actually loads against its own pin', async () => {
const check = await checkMemoryPackageVersion();
expect(check.name).toBe('@claude-flow/memory version');
// In a healthy install the loaded copy satisfies the pin; a warn is only
// acceptable when the optional package is genuinely not installed.
expect(['pass', 'warn']).toContain(check.status);
if (check.status === 'pass') expect(check.message).toContain(pkg.dependencies!['@claude-flow/memory']);
});
});
+2 -2
View File
@@ -125,11 +125,11 @@
"ws": "^8.21.0",
"yaml": "^2.8.0",
"zod": "^3.22.0",
"@claude-flow/memory": "^3.0.0-alpha.23"
"@claude-flow/memory": "3.0.0-alpha.25"
},
"optionalDependencies": {
"@agntcy/slim-bindings": "2.0.0-alpha.5",
"@claude-flow/memory": "^3.0.0-alpha.23",
"@claude-flow/memory": "3.0.0-alpha.25",
"@metaharness/darwin": "~0.10.2",
"@metaharness/flywheel": "~0.1.10",
"@metaharness/radio": "~0.1.0",
@@ -15,8 +15,10 @@ import { execSync, exec } from 'child_process';
import { promisify } from 'util';
import { decodeKey, isEncryptionEnabled } from '../encryption/vault.js';
import { isEncryptedBlob } from '../encryption/vault.js';
import * as semver from 'semver';
import {
resolveMemoryPackageFromProject,
resolveMemoryPackageFromCli,
readMemoryPackageVersion,
recordMemoryPackagePath,
} from '../init/memory-package-resolver.js';
@@ -1040,6 +1042,72 @@ async function checkLearningBridge(): Promise<HealthCheck> {
};
}
/**
* #3392: pure verdict for "does the @claude-flow/memory the CLI loads satisfy
* the range the CLI declares?". `npx @claude-flow/cli@latest` reuses one npx
* cache directory across CLI versions, and npm keeps an already-installed
* dependency that still satisfies a caret range, so a stale memory could
* survive a CLI upgrade with no error. Exported for unit testing.
*/
export function evaluateMemoryPackageVersion(declared: string | null, installed: string | null): HealthCheck {
const NAME = '@claude-flow/memory version';
if (!declared) {
return { name: NAME, status: 'warn', message: 'could not read the @claude-flow/memory range declared by @claude-flow/cli' };
}
if (!installed) {
return {
name: NAME,
status: 'warn',
message: `@claude-flow/memory is not resolvable from the CLI (declared ${declared}) — memory features fall back to degraded paths`,
fix: `npm install @claude-flow/memory@${declared} --include=optional`,
};
}
if (!semver.validRange(declared) || !semver.valid(installed)) {
return { name: NAME, status: 'warn', message: `cannot compare installed ${installed} against declared ${declared}` };
}
if (semver.satisfies(installed, declared, { includePrerelease: true })) {
return { name: NAME, status: 'pass', message: `v${installed} satisfies declared ${declared}` };
}
return {
name: NAME,
status: 'fail',
message: `installed v${installed} does not satisfy declared ${declared} — a stale cached copy is running, so fixes shipped in a newer @claude-flow/memory are silently absent`,
fix: `rm -rf "$(npm config get cache)/_npx" && npx @claude-flow/cli@latest doctor # or: npm install @claude-flow/memory@${declared}`,
};
}
export async function checkMemoryPackageVersion(): Promise<HealthCheck> {
try {
// Walk up from this module to the CLI package root (npx cache, global,
// project-local and monorepo dev all resolve the same way).
let declared: string | null = null;
let dir = dirname(fileURLToPath(import.meta.url));
for (let i = 0; i < 8 && declared === null; i++) {
const pj = join(dir, 'package.json');
if (existsSync(pj)) {
try {
const pkg = JSON.parse(readFileSync(pj, 'utf-8')) as {
name?: string;
dependencies?: Record<string, string>;
optionalDependencies?: Record<string, string>;
};
if (pkg.name === '@claude-flow/cli') {
declared = pkg.optionalDependencies?.['@claude-flow/memory'] ?? pkg.dependencies?.['@claude-flow/memory'] ?? null;
break;
}
} catch { /* keep walking */ }
}
dir = dirname(dir);
}
// Resolve exactly as the CLI's own runtime does (its module context),
// not from process.cwd() — that would report the project's copy instead.
const distPath = resolveMemoryPackageFromCli();
return evaluateMemoryPackageVersion(declared, distPath ? readMemoryPackageVersion(distPath) : null);
} catch (err) {
return { name: '@claude-flow/memory version', status: 'warn', message: `check failed: ${err instanceof Error ? err.message : String(err)}` };
}
}
// Check API keys
async function checkApiKeys(): Promise<HealthCheck> {
const keys = ['ANTHROPIC_API_KEY', 'CLAUDE_API_KEY', 'OPENAI_API_KEY'];
@@ -2439,6 +2507,7 @@ export const doctorCommand: Command = {
checkMemoryStructuralIntegrity, // #2737 — bounded, native quick_check on every default run
checkMemoryPersistenceDriver, // #2968/#3321 — read-only native capability probe
checkLearningBridge, // #2545 — can the auto-memory hook actually load @claude-flow/memory?
checkMemoryPackageVersion, // #3392 — loaded @claude-flow/memory must satisfy the CLI's declared range
checkApiKeys,
checkMcpServers,
checkMcpSchemaOverhead, // #2726 — fixed tools/list prompt cost
@@ -2477,11 +2546,13 @@ export const doctorCommand: Command = {
checkMemoryDatabase, // existing: exists + statable (unchanged)
checkMemoryIntegrity, // #2677 check 1: sql.js open + PRAGMA integrity_check
checkMemoryPersistenceDriver, // #2968/#3321: read-only native capability probe
checkMemoryPackageVersion, // #3392: loaded memory package satisfies the declared range
checkMemoryContent, // #2677 check 2: memory_entries content coverage
checkMemoryEmbeddingCoverage, // #2677 check 3: vector coverage on populated rows
checkMemoryReflexionCoverage, // #2677 check 6: episodes are retrievable
checkMemoryCritiqueCoverage, // #2677 check 6: feedback carries lessons
],
'memory-package': checkMemoryPackageVersion, // #3392
'learning': checkLearningBridge, // #2545
'learning-bridge': checkLearningBridge, // #2545
'api': checkApiKeys,
+21 -2
View File
@@ -209,8 +209,8 @@ importers:
specifier: 2.0.0-alpha.5
version: 2.0.0-alpha.5
'@claude-flow/memory':
specifier: ^3.0.0-alpha.23
version: 3.0.0-alpha.24(@types/node@20.19.27)(zod@3.25.76)
specifier: 3.0.0-alpha.25
version: 3.0.0-alpha.25(@types/node@20.19.27)(zod@3.25.76)
'@metaharness/darwin':
specifier: ~0.10.2
version: 0.10.2
@@ -936,6 +936,25 @@ packages:
- supports-color
- zod
/@claude-flow/memory@3.0.0-alpha.25(@types/node@20.19.27)(zod@3.25.76):
resolution: {integrity: sha512-yjeFlIlUkAE0jBUTx4ocvqWm71CsJEhps8gz0tU1Kl0POelxOsLsEUVQUCQ2E4ZEuQ0xii12K8+3tzK2hvWD3g==}
cpu: [x64, arm64]
os: [darwin, linux, win32]
dependencies:
'@claude-flow/security': 3.0.0-alpha.12
agentdb: 3.0.0-alpha.17(@types/node@20.19.27)(zod@3.25.76)
sql.js: 1.14.1
optionalDependencies:
better-sqlite3: 12.9.0
transitivePeerDependencies:
- '@cfworker/json-schema'
- '@types/node'
- bare-abort-controller
- bare-buffer
- react-native-b4a
- supports-color
- zod
/@claude-flow/security@3.0.0-alpha.12:
resolution: {integrity: sha512-/b1V6zXOhFSs+Y8UztyPFHqkNjDKslwpAn9+KJFWHqZMwnnPnBnW0WQHoZAGx+5+rewI619pVT9gIANkyt3luQ==}
dependencies: