claude-mem-lite 4.0.4 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +18 -72
  4. package/README.zh-CN.md +24 -74
  5. package/adopt-content.mjs +0 -1
  6. package/cli/common.mjs +0 -17
  7. package/cli.mjs +19 -3
  8. package/commands/mem.md +3 -3
  9. package/commands/update.md +5 -12
  10. package/format-utils.mjs +0 -21
  11. package/haiku-client.mjs +36 -5
  12. package/hash-utils.mjs +21 -0
  13. package/hook-episode.mjs +7 -1
  14. package/hook-optimize.mjs +103 -50
  15. package/hook-shared.mjs +8 -2
  16. package/hook-update.mjs +56 -14
  17. package/hook.mjs +21 -29
  18. package/hooks/hooks.json +0 -10
  19. package/install.mjs +100 -678
  20. package/lib/atomic-write.mjs +16 -0
  21. package/lib/deferred-work.mjs +7 -3
  22. package/lib/doctor-drift.mjs +0 -1
  23. package/lib/frontmatter.mjs +1 -2
  24. package/lib/get-core.mjs +27 -1
  25. package/lib/hook-prune.mjs +133 -0
  26. package/lib/hook-stdin.mjs +1 -1
  27. package/lib/hook-telemetry.mjs +1 -1
  28. package/lib/install-shape.mjs +45 -4
  29. package/lib/maintain-core.mjs +9 -0
  30. package/lib/metrics.mjs +2 -2
  31. package/lib/proc-lock.mjs +111 -13
  32. package/lib/proxy-fetch.mjs +26 -2
  33. package/lib/scrub-record.mjs +8 -0
  34. package/lib/shard-gc.mjs +11 -7
  35. package/lib/tmp-fixture-sweep.mjs +9 -0
  36. package/mem-cli.mjs +46 -434
  37. package/nlp.mjs +1 -1
  38. package/npm-shrinkwrap.json +6 -2
  39. package/package.json +9 -16
  40. package/project-utils.mjs +43 -15
  41. package/schema.mjs +112 -50
  42. package/scripts/hook-launcher.mjs +9 -3
  43. package/scripts/prompt-search-utils.mjs +0 -30
  44. package/scripts/setup.sh +5 -0
  45. package/scripts/user-prompt-search.js +3 -125
  46. package/secret-scrub.mjs +32 -3
  47. package/server.mjs +19 -451
  48. package/source-files.mjs +12 -29
  49. package/synonyms.mjs +2 -1
  50. package/tool-schemas.mjs +23 -91
  51. package/utils.mjs +5 -13
  52. package/commands/tools.md +0 -67
  53. package/install-metadata.mjs +0 -2193
  54. package/lib/registry-core.mjs +0 -264
  55. package/registry/preinstalled.json +0 -2419
  56. package/registry-enricher.mjs +0 -124
  57. package/registry-github.mjs +0 -86
  58. package/registry-importer.mjs +0 -569
  59. package/registry-recommend.mjs +0 -503
  60. package/registry-retriever.mjs +0 -611
  61. package/registry-scanner.mjs +0 -261
  62. package/registry.mjs +0 -665
  63. package/resource-discovery.mjs +0 -199
  64. package/scripts/pre-skill-bridge.js +0 -146
@@ -37,6 +37,15 @@ export const TEST_FIXTURE_PREFIXES = [
37
37
  'err-sampler-',
38
38
  'cml-preflight-',
39
39
  'cli-audit-',
40
+ // R10 P2-18. Three prefixes the suite leaked with no reclamation path at all. Each is
41
+ // also cleaned deterministically at its source now; these are the backstop for the cases
42
+ // that cannot be — a detached llm-episode worker recreating a directory after afterEach,
43
+ // and a crashed run. `bom-` and `d202-` were deliberately NOT added: they are cleaned in
44
+ // a finally / afterAll, and both are generic enough that an unrelated /tmp directory
45
+ // could match, which is the collateral-deletion risk the note above this list warns about.
46
+ 'stop-fallback-',
47
+ 'audit-metrics-selfcheck-',
48
+ 'hook-ctx-test-',
40
49
  ];
41
50
 
42
51
  export const DEFAULT_FIXTURE_AGE_MS = 60 * 60 * 1000; // 1h — wide margin over the longest test
package/mem-cli.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  // No MCP SDK or heavy deps — only imports schema.mjs and utils.mjs
4
4
 
5
5
  import { homedir } from 'os';
6
- import { ensureDbWithWalRecovery, DB_PATH, DB_DIR, REGISTRY_DB_PATH } from './schema.mjs';
6
+ import { ensureDbWithWalRecovery, DB_PATH, DB_DIR } from './schema.mjs';
7
7
  import { resolveRuntimeDir } from './lib/resolve-data-dir.mjs';
8
8
  import { truncate, typeIcon, inferProject, scrubSecrets, COMPRESSED_PENDING_PURGE } from './utils.mjs';
9
9
  import { resolveProject } from './project-utils.mjs';
@@ -36,32 +36,6 @@ import {
36
36
  BROWSE_TIER_LABELS,
37
37
  } from './lib/browse-core.mjs';
38
38
  import { deepSearch, resolveDeepMode, shouldEscalateToDeep, autoDeepLlmReady } from './deep-search.mjs';
39
- import {
40
- ensureRegistryDb,
41
- collectRegistryStats,
42
- listResourcesRanked,
43
- formatRegistryListLine,
44
- } from './registry.mjs';
45
- import {
46
- IMPORT_STRING_FIELDS,
47
- importResource,
48
- removeResource,
49
- reindexResources,
50
- enrichResourceRow,
51
- enrichImportedResources,
52
- enrichNamedResource,
53
- REGISTRY_CONFINE_ENV,
54
- resourceUseHint,
55
- } from './lib/registry-core.mjs';
56
- import { searchResources } from './registry-retriever.mjs';
57
- import {
58
- computeFunnel,
59
- formatFunnel,
60
- computeSweep,
61
- formatSweep,
62
- DEFAULT_SWEEP_FLOORS,
63
- DEFAULT_SWEEP_MARGINS,
64
- } from './registry-recommend.mjs';
65
39
  import { selectCompressionCandidates, groupByProjectWeek, compressGroup } from './lib/compress-core.mjs';
66
40
  import {
67
41
  runMaintainOps,
@@ -91,7 +65,7 @@ import {
91
65
  bucketIdTokens,
92
66
  splitDeferredTokens,
93
67
  } from './lib/id-routing.mjs';
94
- import { join, sep, dirname } from 'path';
68
+ import { join, dirname } from 'path';
95
69
  import { spawnSync } from 'child_process';
96
70
  import { readFileSync, existsSync, readdirSync, statSync } from 'fs';
97
71
 
@@ -1202,7 +1176,9 @@ function cmdSave(db, args) {
1202
1176
  fail(`[mem] Invalid importance "${flags.importance}". Must be 1, 2, or 3.`);
1203
1177
  return;
1204
1178
  }
1205
- const project = flags.project ? resolveProject(db, flags.project) : inferProject();
1179
+ // R10 P2-3: write mode — exact matching only, so `--project api` cannot land the row in
1180
+ // `mono--api-gateway` where the caller's own next `--project api` read will not find it.
1181
+ const project = flags.project ? resolveProject(db, flags.project, { mode: 'write' }) : inferProject();
1206
1182
  const saveFiles = flags.files
1207
1183
  ? flags.files
1208
1184
  .split(',')
@@ -1389,7 +1365,9 @@ function cmdDeferAdd(db, args) {
1389
1365
  fail(`[mem] Invalid --priority "${flags.priority}". Must be 1 (low), 2 (normal), or 3 (urgent).`);
1390
1366
  return;
1391
1367
  }
1392
- const project = flags.project ? resolveProject(db, flags.project) : inferProject();
1368
+ // R10 P2-3: write mode — exact matching only, so `--project api` cannot land the row in
1369
+ // `mono--api-gateway` where the caller's own next `--project api` read will not find it.
1370
+ const project = flags.project ? resolveProject(db, flags.project, { mode: 'write' }) : inferProject();
1393
1371
  const detail = typeof flags.detail === 'string' ? flags.detail : null;
1394
1372
  const files = flags.files
1395
1373
  ? flags.files
@@ -2683,235 +2661,6 @@ function cmdMaintain(db, args) {
2683
2661
  // cmdFtsCheck extracted to cli/fts-check.mjs (v2.41 split).
2684
2662
  import { cmdFtsCheck } from './cli/fts-check.mjs';
2685
2663
 
2686
- // ─── Registry ─────────────────────────────────────────────────────────────────
2687
-
2688
- function cmdRegistry(_memDb, args) {
2689
- const { positional, flags } = parseArgs(args);
2690
- const action = positional[0];
2691
- if (
2692
- !action ||
2693
- !['list', 'stats', 'search', 'import', 'remove', 'reindex', 'recommend-stats'].includes(action)
2694
- ) {
2695
- fail(
2696
- '[mem] Usage: claude-mem-lite registry <list|stats|search|import|remove|reindex|recommend-stats> [--type skill|agent] [--query Q] [--name N] [--resource-type T]',
2697
- );
2698
- return;
2699
- }
2700
-
2701
- // recommend-stats reads the shadow-recommendation JSONL (filesystem), not the
2702
- // registry DB — handle it before opening rdb so it works without a registry DB.
2703
- if (action === 'recommend-stats') {
2704
- const days =
2705
- (typeof flags.days === 'string' || typeof flags.days === 'number') && +flags.days > 0
2706
- ? Math.floor(+flags.days)
2707
- : 7;
2708
- out(formatFunnel(computeFunnel(days)));
2709
- if (flags.sweep) {
2710
- // Offline ROC over the shipped gate thresholds (B3). Parse `--floors`/`--margins` as
2711
- // comma lists of finite numbers; fall back to the spanning defaults on bad/empty input.
2712
- const parseNums = (v, fallback) => {
2713
- if (typeof v !== 'string') return fallback;
2714
- const nums = v
2715
- .split(',')
2716
- .map((x) => Number(x.trim()))
2717
- .filter(Number.isFinite);
2718
- return nums.length ? nums : fallback;
2719
- };
2720
- const floors = parseNums(flags.floors, DEFAULT_SWEEP_FLOORS);
2721
- const margins = parseNums(flags.margins, DEFAULT_SWEEP_MARGINS);
2722
- out('');
2723
- out(formatSweep(computeSweep(days, floors, margins)));
2724
- }
2725
- return;
2726
- }
2727
-
2728
- let rdb;
2729
- try {
2730
- rdb = ensureRegistryDb(REGISTRY_DB_PATH);
2731
- rdb.pragma('busy_timeout = 3000');
2732
- } catch (e) {
2733
- out(`[mem] Registry DB not available: ${e.message}`);
2734
- return;
2735
- }
2736
-
2737
- // `--type` and `--resource-type` are both constrained to skill|agent across
2738
- // registry sub-actions. Validating once here means search/list/import/remove
2739
- // all reject typos like `--type sklil` instead of silently returning
2740
- // "No resources found." (which looked like the registry was empty for that
2741
- // type, not like a typo).
2742
- if (flags.type !== undefined && flags.type !== 'skill' && flags.type !== 'agent') {
2743
- fail(`[mem] Invalid --type "${flags.type}". Use: skill, agent`);
2744
- return;
2745
- }
2746
- if (
2747
- flags['resource-type'] !== undefined &&
2748
- flags['resource-type'] !== 'skill' &&
2749
- flags['resource-type'] !== 'agent'
2750
- ) {
2751
- fail(`[mem] Invalid --resource-type "${flags['resource-type']}". Use: skill, agent`);
2752
- return;
2753
- }
2754
-
2755
- try {
2756
- if (action === 'search') {
2757
- // Bare `--query` parses to boolean true; `true || ...` would search for the literal
2758
- // string "true". Reject it cleanly (#8470) before it becomes a confusing no-match.
2759
- if (rejectBareStringFlags(flags, ['query', 'category', 'quality'])) return;
2760
- const query = flags.query || positional.slice(1).join(' ');
2761
- if (!query) {
2762
- fail(
2763
- '[mem] Usage: claude-mem-lite registry search <query> [--type skill|agent] [--category C] [--quality Q]',
2764
- );
2765
- return;
2766
- }
2767
- let results = searchResources(rdb, query, {
2768
- type: flags.type || undefined,
2769
- limit: flags.category || flags.quality ? 20 : 10,
2770
- });
2771
- // Apply category/quality post-filters (aligned with MCP mem_registry)
2772
- if (flags.category) results = results.filter((r) => r.category === flags.category);
2773
- if (flags.quality) results = results.filter((r) => r.quality_tier === flags.quality);
2774
- // Prioritize directly invocable resources (aligned with MCP mem_registry)
2775
- results.sort((a, b) => {
2776
- const aInvocable = a.invocation_name ? 1 : 0;
2777
- const bInvocable = b.invocation_name ? 1 : 0;
2778
- if (aInvocable !== bInvocable) return bInvocable - aInvocable;
2779
- return 0;
2780
- });
2781
- results = results.slice(0, 5);
2782
- if (results.length === 0) {
2783
- out(`[mem] No matching resources for: "${query}"`);
2784
- return;
2785
- }
2786
- out(`[mem] ${results.length} resource(s) for "${query}":`);
2787
- const home = homedir();
2788
- for (const r of results) {
2789
- const badge = r.quality_tier === 'installed' ? '[✓]' : r.quality_tier === 'verified' ? '[★]' : '[○]';
2790
- const categoryLabel = r.category ? ` [${r.category}]` : '';
2791
- // P2-6: the invocation rule is shared; only the four-space indent is this face's.
2792
- const { portablePath, howToUse } = resourceUseHint(r, {
2793
- home,
2794
- managedPrefix: join(DB_DIR, 'managed') + sep,
2795
- });
2796
- const pathLine = portablePath ? `\n Path: ${portablePath}` : '';
2797
- out(
2798
- ` ${badge} ${r.type === 'skill' ? 'S' : 'A'} ${r.name}${categoryLabel} — ${truncate(r.capability_summary || '', 80)}${pathLine}\n Use: ${howToUse}`,
2799
- );
2800
- }
2801
- return;
2802
- }
2803
-
2804
- if (action === 'list') {
2805
- const typeFilter = flags.type;
2806
- const listLimit = parseIntFlag(flags.limit, { name: '--limit', defaultValue: 20, max: 1000 });
2807
- // Shared ranked query + row line (registry.mjs, P2-12): COALESCE ordering and
2808
- // the 80-char/adopt:0 row shape had drifted between the faces.
2809
- const allResources = listResourcesRanked(rdb, { type: typeFilter });
2810
- if (allResources.length === 0) {
2811
- out('[mem] No resources found.');
2812
- return;
2813
- }
2814
- const resources = allResources.slice(0, listLimit);
2815
- out(`[mem] Resources (showing ${resources.length} of ${allResources.length}):`);
2816
- for (const r of resources) out(` ${formatRegistryListLine(r)}`);
2817
- if (allResources.length > listLimit) {
2818
- out(`[mem] Use --limit N to see more, or "registry search <query>" to find specific resources.`);
2819
- }
2820
- return;
2821
- }
2822
-
2823
- if (action === 'stats') {
2824
- // Shared collection (registry.mjs collectRegistryStats, P2-12) — single
2825
- // source with the MCP mem_registry stats action.
2826
- const s = collectRegistryStats(rdb);
2827
- out(`[mem] Registry Stats:`);
2828
- out(` Total active: ${s.total}`);
2829
- for (const t of s.byType) out(` ${t.type}: ${t.c}`);
2830
- out(` User-added: ${s.userAdded}`);
2831
- out(` Zero adoption (recommended but never adopted): ${s.zeroAdopt}`);
2832
- if (s.topAdopted.length > 0) {
2833
- out(' Top adopted:');
2834
- for (const r of s.topAdopted) out(` ${r.name} (${r.type}): ${r.adopt_count}/${r.recommend_count}`);
2835
- }
2836
- return;
2837
- }
2838
-
2839
- if (action === 'import') {
2840
- // Bare value-less flags → boolean true → SQLite-bind crash in upsertResource (#8470).
2841
- // Shared guard — single source with update/remove/the other commands.
2842
- if (
2843
- rejectBareStringFlags(flags, [
2844
- 'name',
2845
- 'resource-type',
2846
- 'invocation-name',
2847
- 'source',
2848
- 'repo-url',
2849
- 'local-path',
2850
- 'intent-tags',
2851
- 'domain-tags',
2852
- 'trigger-patterns',
2853
- 'capability-summary',
2854
- 'keywords',
2855
- 'tech-stack',
2856
- 'use-cases',
2857
- ])
2858
- )
2859
- return;
2860
- const name = flags.name;
2861
- const resourceType = flags['resource-type'];
2862
- if (!name || !resourceType) {
2863
- fail(
2864
- '[mem] Usage: claude-mem-lite registry import --name N --resource-type skill|agent [--invocation-name I] [--capability-summary S]',
2865
- );
2866
- return;
2867
- }
2868
- // Validate --source against its CHECK enum (parity with memRegistrySchema.source on MCP):
2869
- // an invalid value otherwise reaches the INSERT and throws a raw SqliteError stacktrace
2870
- // (the dispatcher's catch only special-cases SQLITE_BUSY/LOCKED).
2871
- if (flags.source && !new Set(['preinstalled', 'user', 'github']).has(flags.source)) {
2872
- fail(`[mem] Invalid --source "${flags.source}". Valid: preinstalled, user, github`);
2873
- return;
2874
- }
2875
- // Provenance preservation + the 'installed' tier grant live in lib/registry-core.mjs,
2876
- // shared with the mem_registry MCP twin (audit 2026-08-22 P1-3). CLI flags are
2877
- // kebab-case; the core's field list is the canonical snake_case source.
2878
- const fields = {};
2879
- for (const f of IMPORT_STRING_FIELDS) fields[f] = flags[f.replace(/_/g, '-')] || '';
2880
- const { id } = importResource(rdb, { name, type: resourceType, source: flags.source, fields });
2881
- out(`[mem] Imported: ${resourceType}:${name} (id=${id})`);
2882
- if (!flags['capability-summary'] && !flags['use-cases']) {
2883
- out('[mem] Tip: Add --capability-summary or --use-cases so the resource appears in searches.');
2884
- }
2885
- return;
2886
- }
2887
-
2888
- if (action === 'remove') {
2889
- // Bare value-less --name / --resource-type → boolean true → SQLite-bind crash on
2890
- // the DELETE below; shared guard, single source with import/update.
2891
- if (rejectBareStringFlags(flags, ['name', 'resource-type'])) return;
2892
- const name = flags.name;
2893
- const resourceType = flags['resource-type'];
2894
- if (!name || !resourceType) {
2895
- fail('[mem] Usage: claude-mem-lite registry remove --name N --resource-type skill|agent');
2896
- return;
2897
- }
2898
- const { removed } = removeResource(rdb, { name, type: resourceType });
2899
- out(removed ? `[mem] Removed: ${resourceType}:${name}` : `[mem] Not found: ${resourceType}:${name}`);
2900
- return;
2901
- }
2902
-
2903
- if (action === 'reindex') {
2904
- const { activeCount } = reindexResources(rdb);
2905
- out(`[mem] FTS5 reindexed. ${activeCount} active resources.`);
2906
- return;
2907
- }
2908
- } finally {
2909
- try {
2910
- rdb.close();
2911
- } catch {}
2912
- }
2913
- }
2914
-
2915
2664
  // ─── memdir-audit ────────────────────────────────────────────────────────────
2916
2665
  // Body-structure audit for ~/.claude/projects/<encoded>/memory/feedback_*.md
2917
2666
  // and project_*.md. CLI-only by design — running this every session would be
@@ -3281,7 +3030,7 @@ function cmdHelp() {
3281
3030
  Commands:
3282
3031
  search <query> FTS5 search across observations, sessions, and prompts
3283
3032
  --query Q Query as a flag (alias for the positional; use one, not both)
3284
- --source S Table: observations|sessions|prompts (default: all)
3033
+ --source S Table: observations|sessions|prompts|events (default: all)
3285
3034
  --type T Filter obs type (bugfix|decision|discovery|feature|refactor|change)
3286
3035
  --limit N Max results (default 20)
3287
3036
  --project P Filter by project
@@ -3289,6 +3038,11 @@ Commands:
3289
3038
  --to DATE End date (YYYY-MM-DD or ISO 8601)
3290
3039
  --since DUR Relative lower bound: 7d|24h|90m|2w|30s (ignored if --from set)
3291
3040
  --importance N Minimum importance (1=routine, 2=notable, 3=critical)
3041
+ --deep Opt-in LLM multi-query / HyDE deep search (observations only).
3042
+ One extra model call plus N hybrid searches — the explicit
3043
+ "search harder" lever for vocabulary-mismatch misses.
3044
+ --no-deep Force normal search, overriding any env/default that enables deep
3045
+ --rerank LLM-rerank the fused top 20. Requires --deep; ignored without it
3292
3046
  --branch B Filter by git branch
3293
3047
  --offset N Skip first N results (pagination)
3294
3048
  --tier T Filter by tier (working|active|archive, observations only)
@@ -3315,13 +3069,14 @@ Commands:
3315
3069
  D#123 (deferred item — FULL detail; defer list is title-only).
3316
3070
  Bare N defaults to obs. Mixed prefixes in one call route each token correctly.
3317
3071
  --ids 1,2 IDs as a flag (alias for the positional list)
3318
- --source S Force record type (obs|session|prompt); overrides prefixes
3072
+ --source S Force record type (obs|session|prompt|event); overrides prefixes
3319
3073
  (D# tokens exempt — they always read deferred_work).
3320
3074
  --fields f1,f2,... Select specific fields to return (observations only).
3321
3075
 
3322
3076
  timeline Show observations around an anchor (shows recent if no anchor)
3323
- --anchor ID Center on this ID. Accepts N, #N, P#N, or S#N — P#/S# anchors
3324
- resolve to the nearest-in-time observation in the same project.
3077
+ --anchor ID Center on this ID. Accepts N, #N, P#N, S#N or E#N — P#/S#/E#
3078
+ anchors resolve to the nearest-in-time observation in the
3079
+ same project.
3325
3080
  --query "text" Find anchor by FTS5 search. Ranks by BM25 × time-decay,
3326
3081
  so multi-term queries surface the BEST topical match
3327
3082
  (highest term coverage), not the most recent. For
@@ -3453,25 +3208,9 @@ Commands:
3453
3208
  --days N Cite-rate window in days (default 7)
3454
3209
  --json Output as JSON: {window_days,per_project:[],decay_queue:[],promoted:[]}
3455
3210
 
3456
- registry <action> Manage tool resource registry
3457
- list List resources [--type skill|agent] [--limit N] (default 20)
3458
- stats Registry statistics
3459
- search <query> Search resources [--type skill|agent] [--category C] [--quality Q]
3460
- import Import resource --name N --resource-type T [--repo-url U] [--local-path P] [--use-cases U]
3461
- remove Remove resource --name N --resource-type T
3462
- reindex Rebuild FTS5 index
3463
- recommend-stats Shadow recommendation funnel [--days N] [--sweep] [--json]
3464
-
3465
3211
  import-jsonl <file-or-dir> Import Claude Code JSONL transcripts (cold-start backfill)
3466
3212
  --project P Project name (default: inferred from cwd)
3467
3213
 
3468
- import <github-url> Import skills/agents into the resource registry from a GitHub repo
3469
- --enrich Auto-enrich each imported resource with a Haiku capability summary
3470
-
3471
- enrich <name> Re-enrich a single registry resource (Haiku capability summary)
3472
- --all Enrich every active resource missing or failed enrichment
3473
- --batch Skip the inter-call delay (use only with low rate-limit risk)
3474
-
3475
3214
  activity <action> Non-memdir event log (v2.31) — bugfix/lesson/bug/discovery/etc.
3476
3215
  save --type T "<title>" [--body "<text>"] [--files f1,f2] [--file path] [--importance 1-3] [--project P]
3477
3216
  search "<query>" Search events [--type T] [--limit N] [--project P]
@@ -3512,69 +3251,6 @@ DB: ${DB_PATH}`);
3512
3251
 
3513
3252
  // ─── Import (GitHub) ────────────────────────────────────────────────────────
3514
3253
 
3515
- async function cmdImport(argv) {
3516
- const { positional, flags } = parseArgs(argv);
3517
- const url = positional[0];
3518
-
3519
- if (!url) {
3520
- fail('[mem] Usage: claude-mem-lite import <github-url> [--enrich]');
3521
- return;
3522
- }
3523
-
3524
- let rdb;
3525
- try {
3526
- rdb = ensureRegistryDb(REGISTRY_DB_PATH);
3527
- rdb.pragma('busy_timeout = 3000');
3528
- } catch (e) {
3529
- fail(`[mem] Registry DB error: ${e.message}`);
3530
- return;
3531
- }
3532
-
3533
- try {
3534
- const { importFromGitHub, formatImportSkips } = await import('./registry-importer.mjs');
3535
- out(`[mem] Importing from ${url}...`);
3536
- // `skipped` sink + shared summary (R6 Q1) — same helper the MCP twin renders, so the
3537
- // bounds cannot end up enforced-but-silent on one of the two faces.
3538
- const skipped = [];
3539
- const results = await importFromGitHub(rdb, url, { skipped });
3540
- const refusal = formatImportSkips(skipped);
3541
-
3542
- if (results.length === 0) {
3543
- out('[mem] No skills/agents found in this repository.');
3544
- if (refusal) out(`[mem] ${refusal}`);
3545
- return;
3546
- }
3547
-
3548
- out(`[mem] Imported ${results.length} resource(s):`);
3549
- for (const r of results) {
3550
- out(` ${r.type === 'skill' ? 'S' : 'A'} ${r.name} (id=${r.id})`);
3551
- }
3552
- if (refusal) out(`[mem] ${refusal}`);
3553
-
3554
- if (flags.enrich) {
3555
- out('[mem] Running LLM enrichment...');
3556
- const { enrichResource } = await import('./registry-enricher.mjs');
3557
- const { ok: enriched, denied } = await enrichImportedResources(rdb, results, {
3558
- confineTo: DB_DIR,
3559
- enrichResource,
3560
- });
3561
- out(`[mem] Enriched ${enriched}/${results.length} resources.`);
3562
- if (denied)
3563
- out(
3564
- `[mem] Refused ${denied}: local_path outside the managed directory (${REGISTRY_CONFINE_ENV}=off to override).`,
3565
- );
3566
- }
3567
- } catch (e) {
3568
- fail(`[mem] Import failed: ${e.message}`);
3569
- } finally {
3570
- try {
3571
- rdb.close();
3572
- } catch {}
3573
- }
3574
- }
3575
-
3576
- // ─── Import (Claude Code JSONL transcript — cold-start backfill) ─────────────
3577
-
3578
3254
  async function cmdImportJsonl(db, argv) {
3579
3255
  const { positional, flags } = parseArgs(argv);
3580
3256
  const target = positional[0];
@@ -3583,7 +3259,16 @@ async function cmdImportJsonl(db, argv) {
3583
3259
  return;
3584
3260
  }
3585
3261
 
3586
- const project = flags.project || inferProject();
3262
+ // R10 P3-13: two defects in one line. A bare `--project` (no value) parses to boolean
3263
+ // `true`, which SQLite rejects at bind time with "SQLite3 can only bind numbers, strings…"
3264
+ // — a stack trace instead of a usage message. And unlike every other write command this
3265
+ // one never resolved the name, so `--project mem` imported under the literal string "mem"
3266
+ // while `save --project mem` wrote to `projects--mem`.
3267
+ if (flags.project !== undefined && typeof flags.project !== 'string') {
3268
+ fail('[mem] --project needs a name, e.g. --project my-repo');
3269
+ return;
3270
+ }
3271
+ const project = flags.project ? resolveProject(db, flags.project, { mode: 'write' }) : inferProject();
3587
3272
  const fs = await import('fs');
3588
3273
  const { join: pjoin, resolve } = await import('path');
3589
3274
  const abs = resolve(target);
@@ -3682,86 +3367,6 @@ async function cmdImportJsonl(db, argv) {
3682
3367
 
3683
3368
  // ─── Enrich ─────────────────────────────────────────────────────────────────
3684
3369
 
3685
- async function cmdEnrich(argv) {
3686
- const { positional, flags } = parseArgs(argv);
3687
- const name = positional[0];
3688
-
3689
- let rdb;
3690
- try {
3691
- rdb = ensureRegistryDb(REGISTRY_DB_PATH);
3692
- rdb.pragma('busy_timeout = 3000');
3693
- } catch (e) {
3694
- fail(`[mem] Registry DB error: ${e.message}`);
3695
- return;
3696
- }
3697
-
3698
- try {
3699
- const { enrichResource } = await import('./registry-enricher.mjs');
3700
-
3701
- if (flags.all) {
3702
- const rows = rdb
3703
- .prepare(
3704
- "SELECT name, type, local_path FROM resources WHERE status = 'active' AND (enrichment_status IS NULL OR enrichment_status = 'failed')",
3705
- )
3706
- .all();
3707
- if (rows.length === 0) {
3708
- out('[mem] All resources already enriched.');
3709
- return;
3710
- }
3711
- out(`[mem] Enriching ${rows.length} resources...`);
3712
- let ok = 0,
3713
- failCount = 0,
3714
- denied = 0;
3715
- for (const r of rows) {
3716
- const { status, error } = await enrichResourceRow(rdb, r, { confineTo: DB_DIR, enrichResource });
3717
- if (status === 'enriched') ok++;
3718
- else if (status === 'denied') denied++;
3719
- else failCount++;
3720
- // Pace exactly where the pre-refactor loop did: after an enrichResource call that
3721
- // RETURNED. A missing path, an unreadable file, a gate refusal and a throw out of
3722
- // enrichResource all skipped the sleep before, and still do — `error` present on a
3723
- // 'failed' row is what distinguishes "returned false" from "threw".
3724
- const apiReturned = status === 'enriched' || (status === 'failed' && !error);
3725
- if (apiReturned && !flags.batch) await new Promise((resolve) => setTimeout(resolve, 500));
3726
- }
3727
- out(`[mem] Done: ${ok} enriched, ${failCount} failed.`);
3728
- if (denied)
3729
- out(
3730
- `[mem] Refused ${denied}: local_path outside the managed directory (${REGISTRY_CONFINE_ENV}=off to override).`,
3731
- );
3732
- } else if (name) {
3733
- const { status, error } = await enrichNamedResource(rdb, name, { confineTo: DB_DIR, enrichResource });
3734
- if (status === 'not-found') {
3735
- fail(`[mem] Resource not found: ${name}`);
3736
- return;
3737
- }
3738
- if (status === 'no-path') {
3739
- fail(`[mem] No local_path for ${name}`);
3740
- return;
3741
- }
3742
- if (status === 'denied') {
3743
- fail(
3744
- `[mem] Access denied: local_path outside the managed directory (${REGISTRY_CONFINE_ENV}=off to override).`,
3745
- );
3746
- return;
3747
- }
3748
- if (status === 'unreadable') {
3749
- fail(`[mem] Enrich error: ${error?.message || 'cannot read local_path'}`);
3750
- return;
3751
- }
3752
- out(status === 'enriched' ? `[mem] Enriched: ${name}` : `[mem] Enrichment failed for ${name}`);
3753
- } else {
3754
- fail('[mem] Usage: claude-mem-lite enrich <name> OR claude-mem-lite enrich --all [--batch]');
3755
- }
3756
- } catch (e) {
3757
- fail(`[mem] Enrich error: ${e.message}`);
3758
- } finally {
3759
- try {
3760
- rdb.close();
3761
- } catch {}
3762
- }
3763
- }
3764
-
3765
3370
  async function cmdOptimize(db, args) {
3766
3371
  // cmdOptimize parses flags positionally (args.indexOf('--task') + args[idx+1])
3767
3372
  // instead of the shared parseArgs, so the GNU `--flag=value` form silently
@@ -3794,6 +3399,13 @@ async function cmdOptimize(db, args) {
3794
3399
  const VALID_TASKS = ['re-enrich', 'normalize', 'cluster-merge', 'smart-compress'];
3795
3400
  const taskIdx = args.indexOf('--task');
3796
3401
  let tasks;
3402
+ // R10 P3-15: a trailing bare `--task` used to fall through to "no filter" and run all
3403
+ // four tasks — the opposite of what someone typing --task wants, and each task is LLM
3404
+ // calls. Same treatment --max and --scope already get.
3405
+ if (taskIdx >= 0 && (args[taskIdx + 1] === undefined || args[taskIdx + 1].startsWith('--'))) {
3406
+ fail(`[mem] --task needs a value. One or more of: ${VALID_TASKS.join(', ')}`);
3407
+ return;
3408
+ }
3797
3409
  if (taskIdx >= 0 && args[taskIdx + 1]) {
3798
3410
  const parsed = args[taskIdx + 1]
3799
3411
  .split(',')
@@ -3839,7 +3451,11 @@ async function cmdOptimize(db, args) {
3839
3451
  let project;
3840
3452
  if (projectIdx >= 0 && args[projectIdx + 1]) {
3841
3453
  const raw = args[projectIdx + 1];
3842
- project = raw === '.' || raw === 'current' ? cliProject(db) : raw;
3454
+ // R10 P3-14: resolve like every other project-scoped command. optimize was the one
3455
+ // twin that took the raw string, so `--project api` matched 0 candidates while
3456
+ // `save --project api` in the same process resolved to `mono--api-gateway`. Read mode:
3457
+ // this selects rows to work on, it does not decide where a new row is filed.
3458
+ project = raw === '.' || raw === 'current' ? cliProject(db) : resolveProject(db, raw) || raw;
3843
3459
  }
3844
3460
 
3845
3461
  if (!run && !runAll) {
@@ -4112,18 +3728,9 @@ export async function run(argv) {
4112
3728
  case 'citation-stats':
4113
3729
  cmdCitationStats(db, cmdArgs);
4114
3730
  break;
4115
- case 'registry':
4116
- cmdRegistry(db, cmdArgs);
4117
- break;
4118
- case 'import':
4119
- await cmdImport(cmdArgs);
4120
- break;
4121
3731
  case 'import-jsonl':
4122
3732
  await cmdImportJsonl(db, cmdArgs);
4123
3733
  break;
4124
- case 'enrich':
4125
- await cmdEnrich(cmdArgs);
4126
- break;
4127
3734
  case 'doctor':
4128
3735
  await cmdDoctor(db, cmdArgs);
4129
3736
  break;
@@ -4153,7 +3760,12 @@ export async function run(argv) {
4153
3760
  process.exitCode = 1;
4154
3761
  return;
4155
3762
  }
4156
- throw e;
3763
+ // R10 P3-17: everything else used to be re-thrown, so the terminal — and, when the
3764
+ // agent runs the CLI, the model's context — got a raw Node stack trace. Print the
3765
+ // message, keep the stack behind CLAUDE_MEM_DEBUG for whoever is actually debugging.
3766
+ process.stderr.write(`[mem] ${cmd || 'command'} failed: ${(e && e.message) || e}\n`);
3767
+ if (process.env.CLAUDE_MEM_DEBUG) process.stderr.write(`${(e && e.stack) || ''}\n`);
3768
+ process.exitCode = 1;
4157
3769
  } finally {
4158
3770
  try {
4159
3771
  db.close();
package/nlp.mjs CHANGED
@@ -361,7 +361,7 @@ export function sanitizeFtsQuery(query, opts = {}) {
361
361
  // "redis" in "redis缓存问题". extractCjkKeywords + cjkBigrams only see CJK runs, so
362
362
  // without this the Latin anchor (often the single most precise term — a proper noun
363
363
  // like redis/grafana/oauth with no CJK synonym) was dropped, zeroing recall on
364
- // whitespace-free mixed-script prompts. Mirrors registry-retriever.mjs's embedded-
364
+ // whitespace-free mixed-script prompts. Mirrors the embedded-
365
365
  // English extraction. Lowercased for parity with the write-path unicode61 folding.
366
366
  for (const en of remainder.match(/[a-zA-Z]{2,}/g) || []) {
367
367
  const low = en.toLowerCase();
@@ -1,12 +1,16 @@
1
1
  {
2
2
  "name": "claude-mem-lite",
3
- "version": "4.0.4",
3
+ "version": "5.1.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "claude-mem-lite",
9
- "version": "4.0.4",
9
+ "version": "5.1.0",
10
+ "os": [
11
+ "darwin",
12
+ "linux"
13
+ ],
10
14
  "dependencies": {
11
15
  "@modelcontextprotocol/sdk": "^1.30.0",
12
16
  "better-sqlite3": "^13.0.3",