memoryrouter-claude 1.0.0 → 2.0.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.
package/lib/config.js CHANGED
@@ -1,62 +1,80 @@
1
1
  'use strict';
2
- // Config + state storage for the MemoryRouter Claude Code integration.
3
- // Key lives in ~/.memoryrouter/config.json (0600), NOT in Claude settings JSON.
2
+ // Private config + crash-safe per-session state for the Claude Code integration.
4
3
 
5
4
  const fs = require('fs');
6
5
  const path = require('path');
7
6
  const os = require('os');
8
7
 
8
+ const CONFIG_VERSION = 2;
9
9
  const CONFIG_DIR = process.env.MEMORYROUTER_CONFIG_DIR || path.join(os.homedir(), '.memoryrouter');
10
10
  const CONFIG_PATH = path.join(CONFIG_DIR, 'config.json');
11
11
  const STATE_DIR = path.join(CONFIG_DIR, 'state');
12
-
13
12
  const API_BASE = process.env.MEMORYROUTER_API_BASE || 'https://api.memoryrouter.ai';
13
+ const DEFAULT_STATE_TTL_DAYS = 30;
14
14
 
15
15
  function ensureDir(dir) {
16
16
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
17
+ try { fs.chmodSync(dir, 0o700); } catch { /* windows best-effort */ }
17
18
  }
18
19
 
19
- function readJsonSafe(file) {
20
+ function readJsonSafe(file, { strict = false } = {}) {
20
21
  try {
21
22
  return JSON.parse(fs.readFileSync(file, 'utf8'));
22
- } catch {
23
+ } catch (err) {
24
+ if (strict && err.code !== 'ENOENT') throw new Error(`Could not parse ${file}: ${err.message}`);
23
25
  return null;
24
26
  }
25
27
  }
26
28
 
27
29
  function writeJsonPrivate(file, obj) {
28
30
  ensureDir(path.dirname(file));
29
- const tmp = file + '.tmp';
31
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
30
32
  fs.writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', { mode: 0o600 });
31
33
  fs.renameSync(tmp, file);
32
- try {
33
- fs.chmodSync(file, 0o600);
34
- } catch {
35
- /* windows best-effort */
34
+ try { fs.chmodSync(file, 0o600); } catch { /* windows best-effort */ }
35
+ }
36
+
37
+ function migrateConfig(input) {
38
+ const cfg = input && typeof input === 'object' && !Array.isArray(input) ? { ...input } : {};
39
+ const fromVersion = Number.isInteger(cfg.configVersion) ? cfg.configVersion : 1;
40
+ if (fromVersion < 2) {
41
+ // v1 already used safe flat keys. Preserve every unknown/user key and add
42
+ // explicit scoping/lifecycle defaults rather than replacing the object.
43
+ if (!cfg.memoryScope) cfg.memoryScope = 'project';
44
+ if (cfg.includeGlobal === undefined) cfg.includeGlobal = false;
45
+ if (cfg.captureSubagents === undefined) cfg.captureSubagents = false;
46
+ if (cfg.captureEnabled === undefined) cfg.captureEnabled = true;
47
+ if (cfg.stateTtlDays === undefined) cfg.stateTtlDays = DEFAULT_STATE_TTL_DAYS;
36
48
  }
49
+ cfg.configVersion = CONFIG_VERSION;
50
+ return { config: cfg, fromVersion, changed: fromVersion !== CONFIG_VERSION };
37
51
  }
38
52
 
39
- function loadConfig() {
40
- return readJsonSafe(CONFIG_PATH) || {};
53
+ function loadConfig(options = {}) {
54
+ const raw = readJsonSafe(CONFIG_PATH, options) || {};
55
+ return options.migrate === false ? raw : migrateConfig(raw).config;
41
56
  }
42
57
 
43
58
  function saveConfig(cfg) {
44
- writeJsonPrivate(CONFIG_PATH, cfg);
59
+ writeJsonPrivate(CONFIG_PATH, migrateConfig(cfg).config);
45
60
  }
46
61
 
47
- // Resolution order: env var > config file.
48
62
  function getApiKey() {
49
63
  if (process.env.MEMORYROUTER_API_KEY) return process.env.MEMORYROUTER_API_KEY.trim();
50
64
  const cfg = loadConfig();
51
- return cfg.apiKey || null;
65
+ return typeof cfg.apiKey === 'string' && cfg.apiKey.trim() ? cfg.apiKey.trim() : null;
52
66
  }
53
67
 
54
- // --- per-session state (high-water mark for transcript ingestion, cached prompt) ---
68
+ function safeStateName(sessionId) {
69
+ return String(sessionId || 'unknown').replace(/[^a-zA-Z0-9_.-]/g, '_').slice(0, 180);
70
+ }
55
71
 
56
72
  function statePath(sessionId) {
57
- // session ids are uuid-ish; sanitize defensively
58
- const safe = String(sessionId || 'unknown').replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 128);
59
- return path.join(STATE_DIR, safe + '.json');
73
+ return path.join(STATE_DIR, safeStateName(sessionId) + '.json');
74
+ }
75
+
76
+ function lockPath(sessionId) {
77
+ return statePath(sessionId) + '.lock';
60
78
  }
61
79
 
62
80
  function loadState(sessionId) {
@@ -64,20 +82,87 @@ function loadState(sessionId) {
64
82
  }
65
83
 
66
84
  function saveState(sessionId, state) {
67
- writeJsonPrivate(statePath(sessionId), state);
85
+ const next = { ...state, updatedAt: Date.now() };
86
+ writeJsonPrivate(statePath(sessionId), next);
87
+ return next;
88
+ }
89
+
90
+ function sleep(ms) {
91
+ return new Promise((resolve) => setTimeout(resolve, ms));
92
+ }
93
+
94
+ async function withStateLock(sessionId, fn, options = {}) {
95
+ ensureDir(STATE_DIR);
96
+ const file = lockPath(sessionId);
97
+ const timeoutMs = options.timeoutMs || 1500;
98
+ const staleMs = options.staleMs || 30000;
99
+ const started = Date.now();
100
+ let fd;
101
+ while (Date.now() - started < timeoutMs) {
102
+ try {
103
+ fd = fs.openSync(file, 'wx', 0o600);
104
+ fs.writeFileSync(fd, `${process.pid}\n${Date.now()}\n`);
105
+ break;
106
+ } catch (err) {
107
+ if (err.code !== 'EEXIST') throw err;
108
+ try {
109
+ if (Date.now() - fs.statSync(file).mtimeMs > staleMs) fs.unlinkSync(file);
110
+ } catch { /* another process won */ }
111
+ if (fd === undefined) await sleep(25);
112
+ }
113
+ }
114
+ if (fd === undefined) throw new Error(`state lock timeout for ${safeStateName(sessionId)}`);
115
+ try {
116
+ return await fn(loadState(sessionId));
117
+ } finally {
118
+ try { fs.closeSync(fd); } catch { /* ignore */ }
119
+ try { fs.unlinkSync(file); } catch { /* ignore */ }
120
+ }
121
+ }
122
+
123
+ function pruneState(ttlDays = DEFAULT_STATE_TTL_DAYS, now = Date.now()) {
124
+ const days = Number.isFinite(Number(ttlDays)) && Number(ttlDays) > 0 ? Number(ttlDays) : DEFAULT_STATE_TTL_DAYS;
125
+ const cutoff = now - days * 24 * 60 * 60 * 1000;
126
+ let removed = 0;
127
+ let kept = 0;
128
+ try {
129
+ for (const entry of fs.readdirSync(STATE_DIR, { withFileTypes: true })) {
130
+ if (!entry.isFile() || (!entry.name.endsWith('.json') && !entry.name.endsWith('.lock'))) continue;
131
+ const file = path.join(STATE_DIR, entry.name);
132
+ try {
133
+ if (fs.statSync(file).mtimeMs < cutoff) {
134
+ fs.unlinkSync(file);
135
+ removed++;
136
+ } else kept++;
137
+ } catch { /* race-safe */ }
138
+ }
139
+ } catch { /* state dir absent */ }
140
+ return { removed, kept, ttlDays: days };
141
+ }
142
+
143
+ function configPermissions() {
144
+ try { return fs.statSync(CONFIG_PATH).mode & 0o777; } catch { return null; }
68
145
  }
69
146
 
70
147
  module.exports = {
148
+ CONFIG_VERSION,
71
149
  CONFIG_DIR,
72
150
  CONFIG_PATH,
73
151
  STATE_DIR,
74
152
  API_BASE,
153
+ DEFAULT_STATE_TTL_DAYS,
154
+ ensureDir,
75
155
  loadConfig,
76
156
  saveConfig,
157
+ migrateConfig,
77
158
  getApiKey,
78
159
  loadState,
79
160
  saveState,
161
+ withStateLock,
162
+ pruneState,
80
163
  statePath,
164
+ lockPath,
81
165
  writeJsonPrivate,
82
166
  readJsonSafe,
167
+ configPermissions,
83
168
  };