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/project.js ADDED
@@ -0,0 +1,153 @@
1
+ 'use strict';
2
+ // Deterministic project/workspace identity for Claude Code hooks.
3
+ // Only the opaque hash is sent to MemoryRouter; local paths and remotes stay local.
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const crypto = require('crypto');
8
+ const { execFileSync } = require('child_process');
9
+
10
+ const PROJECT_CONFIG = '.memoryrouter.json';
11
+
12
+ function runGit(args, cwd) {
13
+ try {
14
+ return execFileSync('git', args, {
15
+ cwd,
16
+ encoding: 'utf8',
17
+ timeout: 1500,
18
+ stdio: ['ignore', 'pipe', 'ignore'],
19
+ }).trim();
20
+ } catch {
21
+ return '';
22
+ }
23
+ }
24
+
25
+ function realpathSafe(value) {
26
+ const resolved = path.resolve(value || process.cwd());
27
+ try {
28
+ return fs.realpathSync.native(resolved);
29
+ } catch {
30
+ return resolved;
31
+ }
32
+ }
33
+
34
+ function normalizeRemote(remote) {
35
+ let value = String(remote || '').trim();
36
+ if (!value) return '';
37
+
38
+ // SCP-like git syntax: git@github.com:Org/Repo.git
39
+ const scp = value.match(/^(?:[^@/]+@)?([^:/]+):(.+)$/);
40
+ if (scp && !/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
41
+ value = `ssh://${scp[1]}/${scp[2]}`;
42
+ }
43
+
44
+ try {
45
+ const url = new URL(value);
46
+ const host = url.hostname.toLowerCase();
47
+ const port = url.port && !((url.protocol === 'https:' && url.port === '443') || (url.protocol === 'ssh:' && url.port === '22'))
48
+ ? `:${url.port}`
49
+ : '';
50
+ let pathname = decodeURIComponent(url.pathname).replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '');
51
+ return host && pathname ? `${host}${port}/${pathname}`.toLowerCase() : '';
52
+ } catch {
53
+ return value
54
+ .replace(/^[^@/]+@/, '')
55
+ .replace(/^[a-z][a-z0-9+.-]*:\/\//i, '')
56
+ .replace(/[?#].*$/, '')
57
+ .replace(/^\/+|\/+$/g, '')
58
+ .replace(/\.git$/i, '')
59
+ .toLowerCase();
60
+ }
61
+ }
62
+
63
+ function readProjectConfig(root) {
64
+ const file = path.join(root, PROJECT_CONFIG);
65
+ try {
66
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
67
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
68
+ } catch {
69
+ return {};
70
+ }
71
+ }
72
+
73
+ function hashIdentity(canonical) {
74
+ return crypto.createHash('sha256').update(canonical).digest('hex');
75
+ }
76
+
77
+ function deriveProjectIdentity(input = {}, config = {}) {
78
+ const cwd = realpathSafe(input.cwd || process.cwd());
79
+ const envRoot = process.env.CLAUDE_PROJECT_DIR;
80
+ const requestedRoot = envRoot || input.project_dir || cwd;
81
+ const gitRootRaw = runGit(['rev-parse', '--show-toplevel'], requestedRoot);
82
+ const root = realpathSafe(gitRootRaw || requestedRoot);
83
+ const projectConfig = readProjectConfig(root);
84
+ const ignored = fs.existsSync(path.join(root, '.memoryrouterignore')) || projectConfig.enabled === false;
85
+
86
+ const explicit = process.env.MEMORYROUTER_PROJECT_ID
87
+ || projectConfig.projectId
88
+ || projectConfig.project
89
+ || config.projectId
90
+ || config.project;
91
+
92
+ const remote = normalizeRemote(
93
+ runGit(['config', '--get', 'remote.origin.url'], root)
94
+ || runGit(['config', '--get-regexp', '^remote\\..*\\.url$'], root).split(/\s+/).pop(),
95
+ );
96
+
97
+ const commonDirRaw = gitRootRaw
98
+ ? runGit(['rev-parse', '--path-format=absolute', '--git-common-dir'], root)
99
+ : '';
100
+ const commonDir = commonDirRaw ? realpathSafe(commonDirRaw) : '';
101
+
102
+ let source;
103
+ let canonical;
104
+ if (explicit && String(explicit).trim()) {
105
+ source = 'explicit';
106
+ canonical = `explicit:${String(explicit).trim().toLowerCase()}`;
107
+ } else if (remote) {
108
+ source = 'git-remote';
109
+ canonical = `git:${remote}`;
110
+ } else if (commonDir) {
111
+ source = 'git-common-dir';
112
+ canonical = `git-local:${commonDir}`;
113
+ } else {
114
+ source = 'directory';
115
+ canonical = `dir:${root}`;
116
+ }
117
+
118
+ const digest = hashIdentity(canonical);
119
+ const id = `ccp_${digest.slice(0, 24)}`;
120
+ const localKey = `local_${hashIdentity(`local:${root}`).slice(0, 16)}`;
121
+ const configuredScope = projectConfig.memoryScope || projectConfig.scope || config.memoryScope || config.scope;
122
+ const memoryScope = configuredScope === 'global' ? 'global' : 'project';
123
+ const includeGlobal = projectConfig.includeGlobal === true || config.includeGlobal === true;
124
+
125
+ return {
126
+ id,
127
+ source,
128
+ root,
129
+ cwd,
130
+ remote,
131
+ localKey,
132
+ label: path.basename(root) || 'workspace',
133
+ memoryScope,
134
+ includeGlobal,
135
+ ignored,
136
+ projectConfig,
137
+ };
138
+ }
139
+
140
+ function sessionIdFor(identity) {
141
+ return identity && identity.memoryScope === 'global' ? undefined : identity && identity.id;
142
+ }
143
+
144
+ module.exports = {
145
+ PROJECT_CONFIG,
146
+ runGit,
147
+ realpathSafe,
148
+ normalizeRemote,
149
+ readProjectConfig,
150
+ hashIdentity,
151
+ deriveProjectIdentity,
152
+ sessionIdFor,
153
+ };
package/lib/settings.js CHANGED
@@ -1,63 +1,53 @@
1
1
  'use strict';
2
- // Non-destructive merge/removal of MemoryRouter hooks into Claude Code settings JSON.
3
- // We tag every hook command we own with the marker string so uninstall removes
4
- // ONLY our hooks and never touches anything else in the file.
2
+ // Non-destructive, idempotent merge/removal of MemoryRouter-owned hooks.
5
3
 
6
4
  const fs = require('fs');
7
5
  const path = require('path');
8
6
  const os = require('os');
9
7
 
10
- // Ours = command mentions memoryrouter (package/path, case-insensitive) AND
11
- // invokes one of our hook kinds. This survives both `npx -y memoryrouter-claude hook X`
12
- // and absolute-path installs like `"node" ".../memoryrouter/bin/cli.js" hook X`.
13
8
  const OURS_RE = /memoryrouter/i;
14
- const HOOK_RE = /\bhook (inject|capture|flush|session-start)\b/;
9
+ const HOOK_RE = /\bhook (inject|capture|capture-subagent|flush|compact|reinject|session-start)\b/;
10
+
11
+ function commandHook(bin, kind, timeout, extra = {}) {
12
+ return { type: 'command', command: `${bin} hook ${kind}`, timeout, ...extra };
13
+ }
15
14
 
16
- // Hook definitions per the research spec (section b).
17
- // `bin` is the command prefix to invoke us — absolute path when possible, npx fallback.
18
15
  function buildHookConfig(bin) {
19
16
  return {
20
17
  SessionStart: [
21
18
  {
22
- matcher: 'startup|resume',
23
- hooks: [{ type: 'command', command: `${bin} hook session-start`, timeout: 15 }],
24
- },
25
- ],
26
- UserPromptSubmit: [
27
- {
28
- hooks: [{ type: 'command', command: `${bin} hook inject`, timeout: 10 }],
19
+ matcher: 'startup|resume|clear|compact|fork',
20
+ hooks: [commandHook(bin, 'session-start', 15, { async: true })],
29
21
  },
30
- ],
31
- Stop: [
32
22
  {
33
- hooks: [{ type: 'command', command: `${bin} hook capture`, timeout: 30 }],
23
+ matcher: 'resume|compact|fork',
24
+ hooks: [commandHook(bin, 'reinject', 10)],
34
25
  },
35
26
  ],
27
+ UserPromptSubmit: [{ hooks: [commandHook(bin, 'inject', 10)] }],
28
+ Stop: [{ hooks: [commandHook(bin, 'capture', 30)] }],
29
+ StopFailure: [{ hooks: [commandHook(bin, 'flush', 30)] }],
36
30
  PreCompact: [
37
- {
38
- matcher: 'auto|manual',
39
- hooks: [{ type: 'command', command: `${bin} hook flush`, timeout: 30 }],
40
- },
31
+ { matcher: 'auto|manual', hooks: [commandHook(bin, 'flush', 30)] },
41
32
  ],
42
- SessionEnd: [
43
- {
44
- hooks: [{ type: 'command', command: `${bin} hook flush --final`, timeout: 30 }],
45
- },
33
+ PostCompact: [
34
+ { matcher: 'auto|manual', hooks: [commandHook(bin, 'compact', 30)] },
46
35
  ],
36
+ SubagentStop: [{ hooks: [commandHook(bin, 'capture-subagent', 30)] }],
37
+ SessionEnd: [{ hooks: [commandHook(bin, 'flush', 30)] }],
47
38
  };
48
39
  }
49
40
 
50
41
  function isOurs(hookEntry) {
51
- return (
52
- hookEntry &&
53
- hookEntry.type === 'command' &&
54
- typeof hookEntry.command === 'string' &&
55
- OURS_RE.test(hookEntry.command) &&
56
- HOOK_RE.test(hookEntry.command)
42
+ return Boolean(
43
+ hookEntry
44
+ && hookEntry.type === 'command'
45
+ && typeof hookEntry.command === 'string'
46
+ && OURS_RE.test(hookEntry.command)
47
+ && HOOK_RE.test(hookEntry.command),
57
48
  );
58
49
  }
59
50
 
60
- // Remove our hooks from a settings object (mutates a deep copy, returns it).
61
51
  function removeOurHooks(settings) {
62
52
  const out = JSON.parse(JSON.stringify(settings || {}));
63
53
  if (!out.hooks || typeof out.hooks !== 'object') return out;
@@ -65,27 +55,21 @@ function removeOurHooks(settings) {
65
55
  const matchers = out.hooks[event];
66
56
  if (!Array.isArray(matchers)) continue;
67
57
  const kept = [];
68
- for (const m of matchers) {
69
- if (!m || !Array.isArray(m.hooks)) {
70
- kept.push(m);
58
+ for (const matcher of matchers) {
59
+ if (!matcher || !Array.isArray(matcher.hooks)) {
60
+ kept.push(matcher);
71
61
  continue;
72
62
  }
73
- const remaining = m.hooks.filter((h) => !isOurs(h));
74
- if (remaining.length > 0) {
75
- kept.push({ ...m, hooks: remaining });
76
- }
77
- // if all hooks in this matcher group were ours, drop the group
63
+ const remaining = matcher.hooks.filter((hook) => !isOurs(hook));
64
+ if (remaining.length) kept.push({ ...matcher, hooks: remaining });
78
65
  }
79
- if (kept.length > 0) out.hooks[event] = kept;
66
+ if (kept.length) out.hooks[event] = kept;
80
67
  else delete out.hooks[event];
81
68
  }
82
69
  if (Object.keys(out.hooks).length === 0) delete out.hooks;
83
70
  return out;
84
71
  }
85
72
 
86
- // Merge our hooks into a settings object non-destructively.
87
- // Strategy: first strip any previous MemoryRouter hooks (idempotent re-init),
88
- // then append our matcher groups to each event's array.
89
73
  function mergeHooks(settings, bin) {
90
74
  const out = removeOurHooks(settings);
91
75
  const ours = buildHookConfig(bin);
@@ -97,17 +81,15 @@ function mergeHooks(settings, bin) {
97
81
  return out;
98
82
  }
99
83
 
100
- // --- file-level helpers ---
101
-
102
84
  function settingsPathFor(scope, cwd) {
103
85
  if (scope === 'user') return path.join(os.homedir(), '.claude', 'settings.json');
86
+ if (scope === 'local') return path.join(cwd || process.cwd(), '.claude', 'settings.local.json');
104
87
  return path.join(cwd || process.cwd(), '.claude', 'settings.json');
105
88
  }
106
89
 
107
90
  function readSettings(file) {
108
91
  try {
109
- const text = fs.readFileSync(file, 'utf8');
110
- return JSON.parse(text);
92
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
111
93
  } catch (err) {
112
94
  if (err.code === 'ENOENT') return {};
113
95
  throw new Error(`Could not parse ${file}: ${err.message}. Fix or move the file and retry.`);
@@ -116,9 +98,11 @@ function readSettings(file) {
116
98
 
117
99
  function writeSettings(file, settings) {
118
100
  fs.mkdirSync(path.dirname(file), { recursive: true });
119
- const tmp = file + '.tmp';
120
- fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + '\n');
101
+ const existingMode = (() => { try { return fs.statSync(file).mode & 0o777; } catch { return 0o600; } })();
102
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
103
+ fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + '\n', { mode: existingMode });
121
104
  fs.renameSync(tmp, file);
105
+ try { fs.chmodSync(file, existingMode); } catch { /* windows best-effort */ }
122
106
  }
123
107
 
124
108
  function installHooks(file, bin) {
@@ -129,18 +113,31 @@ function installHooks(file, bin) {
129
113
  }
130
114
 
131
115
  function uninstallHooks(file) {
132
- let settings;
133
- try {
134
- settings = readSettings(file);
135
- } catch {
136
- return null; // unparseable — don't touch
137
- }
116
+ const settings = readSettings(file);
138
117
  if (!settings || Object.keys(settings).length === 0) return null;
139
118
  const cleaned = removeOurHooks(settings);
119
+ if (JSON.stringify(cleaned) === JSON.stringify(settings)) return null;
140
120
  writeSettings(file, cleaned);
141
121
  return cleaned;
142
122
  }
143
123
 
124
+ function hookDiagnostics(file) {
125
+ let settings;
126
+ try { settings = readSettings(file); } catch (err) {
127
+ return { file, exists: fs.existsSync(file), valid: false, error: err.message, owned: 0 };
128
+ }
129
+ let owned = 0;
130
+ const events = [];
131
+ for (const [event, groups] of Object.entries(settings.hooks || {})) {
132
+ for (const group of Array.isArray(groups) ? groups : []) {
133
+ for (const hook of Array.isArray(group && group.hooks) ? group.hooks : []) {
134
+ if (isOurs(hook)) { owned++; events.push(event); }
135
+ }
136
+ }
137
+ }
138
+ return { file, exists: fs.existsSync(file), valid: true, owned, events: [...new Set(events)] };
139
+ }
140
+
144
141
  module.exports = {
145
142
  OURS_RE,
146
143
  HOOK_RE,
@@ -153,4 +150,5 @@ module.exports = {
153
150
  writeSettings,
154
151
  installHooks,
155
152
  uninstallHooks,
153
+ hookDiagnostics,
156
154
  };
package/lib/transcript.js CHANGED
@@ -1,63 +1,253 @@
1
1
  'use strict';
2
- // Claude Code transcript (JSONL) parsing.
3
- // Each line is a JSON object; conversation messages have shape roughly:
4
- // { "type": "user"|"assistant", "uuid": "...", "message": { "role": "...", "content": "..."|[{type:"text",text:"..."}, ...] }, ... }
5
- // We extract plain-text user/assistant messages above a high-water mark (line index).
2
+ // Lossless-at-the-cursor Claude Code JSONL parsing. The parser works in bytes,
3
+ // never advances over malformed/incomplete data, and converts noisy transcript
4
+ // records into compact, deterministic memory events.
6
5
 
7
6
  const fs = require('fs');
7
+ const crypto = require('crypto');
8
8
 
9
- // Pull plain text out of a message content field (string or content-block array).
10
- function contentToText(content) {
9
+ const MAX_TEXT_CHARS = 12000;
10
+ const MAX_TOOL_INPUT_CHARS = 8000;
11
+ const MAX_TOOL_RESULT_CHARS = 6000;
12
+
13
+ function hash(value) {
14
+ return crypto.createHash('sha256').update(String(value)).digest('hex');
15
+ }
16
+
17
+ function cleanText(value) {
18
+ return String(value || '')
19
+ .replace(/<system-reminder>[\s\S]*?<\/system-reminder>/gi, '')
20
+ .replace(/<local-command-caveat>[\s\S]*?<\/local-command-caveat>/gi, '')
21
+ .replace(/\u0000/g, '')
22
+ .trim();
23
+ }
24
+
25
+ function compactText(value, maxChars) {
26
+ const text = cleanText(value);
27
+ if (text.length <= maxChars) return text;
28
+ const head = Math.max(1, Math.floor(maxChars * 0.7));
29
+ const tail = Math.max(1, maxChars - head - 80);
30
+ return `${text.slice(0, head)}\n… [${text.length - head - tail} chars omitted] …\n${text.slice(-tail)}`;
31
+ }
32
+
33
+ function stableJson(value) {
34
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
35
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;
36
+ return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${stableJson(value[k])}`).join(',')}}`;
37
+ }
38
+
39
+ function event(kind, role, content, extra = {}) {
40
+ const normalized = cleanText(content);
41
+ if (!normalized) return null;
42
+ const tool = extra.tool || '';
43
+ return {
44
+ kind,
45
+ role,
46
+ content: normalized,
47
+ ...extra,
48
+ contentKey: hash(`${kind}\n${role}\n${tool}\n${normalized}`).slice(0, 32),
49
+ };
50
+ }
51
+
52
+ function summarizeToolUse(block) {
53
+ const name = String(block.name || 'unknown');
54
+ const input = block.input && typeof block.input === 'object' ? block.input : {};
55
+ const file = input.file_path || input.path || input.notebook_path;
56
+ const lines = [`Tool call: ${name}`];
57
+ if (file) lines.push(`File: ${file}`);
58
+ if (typeof input.command === 'string') lines.push(`Command: ${compactText(input.command, MAX_TOOL_INPUT_CHARS)}`);
59
+ else if (name === 'Edit' || name === 'MultiEdit') {
60
+ if (input.old_string) lines.push(`Replaced: ${compactText(input.old_string, 2500)}`);
61
+ if (input.new_string) lines.push(`With: ${compactText(input.new_string, 2500)}`);
62
+ if (Array.isArray(input.edits)) lines.push(`Edits: ${compactText(stableJson(input.edits), 5000)}`);
63
+ } else if (name === 'Write' && typeof input.content === 'string') {
64
+ lines.push(`Content: ${compactText(input.content, 3500)}`);
65
+ } else {
66
+ const useful = { ...input };
67
+ delete useful.content;
68
+ const serialized = stableJson(useful);
69
+ if (serialized && serialized !== '{}') lines.push(`Input: ${compactText(serialized, MAX_TOOL_INPUT_CHARS)}`);
70
+ }
71
+ return event('tool_use', 'assistant', lines.join('\n'), {
72
+ tool: name,
73
+ toolUseId: block.id || undefined,
74
+ });
75
+ }
76
+
77
+ function toolResultText(content) {
11
78
  if (typeof content === 'string') return content;
12
- if (Array.isArray(content)) {
13
- return content
14
- .filter((b) => b && b.type === 'text' && typeof b.text === 'string')
15
- .map((b) => b.text)
16
- .join('\n');
79
+ if (!Array.isArray(content)) return stableJson(content);
80
+ return content.map((part) => {
81
+ if (!part) return '';
82
+ if (typeof part === 'string') return part;
83
+ if (part.type === 'text') return part.text || '';
84
+ if (part.type === 'image') return '[image result]';
85
+ return stableJson(part);
86
+ }).filter(Boolean).join('\n');
87
+ }
88
+
89
+ function summarizeToolResult(block, obj) {
90
+ const detail = toolResultText(block.content);
91
+ const extraResult = obj && obj.toolUseResult && typeof obj.toolUseResult === 'object'
92
+ ? obj.toolUseResult
93
+ : null;
94
+ let resultText = detail;
95
+ if (!resultText && extraResult) resultText = stableJson(extraResult);
96
+ const status = block.is_error ? 'failed' : 'completed';
97
+ return event('tool_result', 'user', `Tool ${status}${block.tool_use_id ? ` (${block.tool_use_id})` : ''}:\n${compactText(resultText || '[no textual output]', MAX_TOOL_RESULT_CHARS)}`, {
98
+ toolUseId: block.tool_use_id || undefined,
99
+ isError: block.is_error === true,
100
+ });
101
+ }
102
+
103
+ function normalizeMessage(obj) {
104
+ const msg = obj && obj.message;
105
+ if (!msg || (msg.role !== 'user' && msg.role !== 'assistant')) return [];
106
+ const role = msg.role;
107
+ const content = msg.content;
108
+ const out = [];
109
+ if (typeof content === 'string') {
110
+ const text = compactText(content, MAX_TEXT_CHARS);
111
+ const ev = event('text', role, text);
112
+ if (ev) out.push(ev);
113
+ return out;
114
+ }
115
+ if (!Array.isArray(content)) return out;
116
+ for (const block of content) {
117
+ if (!block || typeof block !== 'object') continue;
118
+ if (block.type === 'text') {
119
+ const ev = event('text', role, compactText(block.text, MAX_TEXT_CHARS));
120
+ if (ev) out.push(ev);
121
+ } else if (block.type === 'tool_use') {
122
+ const ev = summarizeToolUse(block);
123
+ if (ev) out.push(ev);
124
+ } else if (block.type === 'tool_result') {
125
+ const ev = summarizeToolResult(block, obj);
126
+ if (ev) out.push(ev);
127
+ }
128
+ // Deliberately exclude thinking/signature blocks and binary payloads.
17
129
  }
18
- return '';
130
+ return out;
19
131
  }
20
132
 
21
- // Parse transcript lines into [{role, content}], starting AFTER line index `afterLine`
22
- // (-1 = from the beginning). Returns { messages, lastLine } where lastLine is the
23
- // index of the last line in the file (new high-water mark).
133
+ function normalizeRecord(obj) {
134
+ if (!obj || typeof obj !== 'object') return [];
135
+ if (obj.isSidechain) return [];
136
+ return normalizeMessage(obj).map((ev, index) => ({
137
+ ...ev,
138
+ // Claude transcript UUID + block index distinguishes legitimate repeated
139
+ // content in later turns. Content keys remain available solely to match a
140
+ // Stop fallback with the same message once JSONL catches up.
141
+ eventKey: obj.uuid
142
+ ? hash(`record\n${obj.uuid}\n${index}\n${ev.contentKey}`).slice(0, 32)
143
+ : ev.contentKey,
144
+ }));
145
+ }
146
+
147
+ function parseBuffer(buffer, baseOffset = 0) {
148
+ const records = [];
149
+ let position = 0;
150
+ let blockedOffset = null;
151
+
152
+ while (position < buffer.length) {
153
+ const newline = buffer.indexOf(0x0a, position);
154
+ const end = newline === -1 ? buffer.length : newline + 1;
155
+ const raw = buffer.subarray(position, newline === -1 ? end : newline);
156
+ const text = raw.toString('utf8').replace(/\r$/, '').trim();
157
+ const startOffset = baseOffset + position;
158
+ const endOffset = baseOffset + end;
159
+ position = end;
160
+
161
+ if (!text) {
162
+ records.push({ startOffset, endOffset, events: [], ignored: true });
163
+ continue;
164
+ }
165
+ let obj;
166
+ try {
167
+ obj = JSON.parse(text);
168
+ } catch {
169
+ blockedOffset = startOffset;
170
+ break;
171
+ }
172
+ records.push({ startOffset, endOffset, events: normalizeRecord(obj), ignored: false });
173
+ }
174
+
175
+ return {
176
+ records,
177
+ blockedOffset,
178
+ nextOffset: records.length ? records[records.length - 1].endOffset : baseOffset,
179
+ };
180
+ }
181
+
182
+ function readTranscriptDelta(transcriptPath, afterOffset = 0) {
183
+ let data;
184
+ try { data = fs.readFileSync(transcriptPath); } catch {
185
+ return { records: [], nextOffset: afterOffset, blockedOffset: null, fileSize: null, reset: false };
186
+ }
187
+ let cursor = Number.isInteger(afterOffset) && afterOffset >= 0 ? afterOffset : 0;
188
+ let reset = false;
189
+ if (cursor > data.length) {
190
+ cursor = 0;
191
+ reset = true;
192
+ }
193
+ const parsed = parseBuffer(data.subarray(cursor), cursor);
194
+ return { ...parsed, fileSize: data.length, reset };
195
+ }
196
+
197
+ function lineIndexToOffset(transcriptPath, lineIndex) {
198
+ if (!Number.isInteger(lineIndex) || lineIndex < 0) return 0;
199
+ let data;
200
+ try { data = fs.readFileSync(transcriptPath); } catch { return 0; }
201
+ let lines = 0;
202
+ for (let i = 0; i < data.length; i++) {
203
+ if (data[i] === 0x0a) {
204
+ if (lines === lineIndex) return i + 1;
205
+ lines++;
206
+ }
207
+ }
208
+ return lines === lineIndex ? data.length : 0;
209
+ }
210
+
211
+ function contentToText(content) {
212
+ if (typeof content === 'string') return cleanText(content);
213
+ if (!Array.isArray(content)) return '';
214
+ return content.filter((b) => b && b.type === 'text').map((b) => cleanText(b.text)).filter(Boolean).join('\n');
215
+ }
216
+
217
+ // Legacy compatibility for callers/tests. Unlike the old parser, lastLine only
218
+ // advances across valid records; tool activity is represented in compact text.
24
219
  function parseTranscript(jsonlText, afterLine = -1) {
25
- const lines = jsonlText.split('\n');
220
+ const lines = String(jsonlText).split('\n');
26
221
  const messages = [];
27
222
  let lastLine = afterLine;
28
223
  for (let i = 0; i < lines.length; i++) {
29
- const line = lines[i].trim();
30
- if (!line) continue;
31
- lastLine = i;
32
- if (i <= afterLine) continue;
224
+ if (i <= afterLine || !lines[i].trim()) continue;
33
225
  let obj;
34
- try {
35
- obj = JSON.parse(line);
36
- } catch {
37
- continue;
38
- }
39
- // Skip meta/sidechain entries
40
- if (obj.isSidechain) continue;
41
- const msg = obj.message;
42
- if (!msg || !msg.role) continue;
43
- if (msg.role !== 'user' && msg.role !== 'assistant') continue;
44
- const text = contentToText(msg.content);
45
- if (!text || !text.trim()) continue;
46
- // Skip tool-result-only user entries and system-reminder noise
47
- if (text.startsWith('<system-reminder>')) continue;
48
- messages.push({ role: msg.role, content: text });
226
+ try { obj = JSON.parse(lines[i]); } catch { break; }
227
+ lastLine = i;
228
+ for (const ev of normalizeRecord(obj)) messages.push({ role: ev.role, content: ev.content });
49
229
  }
50
230
  return { messages, lastLine };
51
231
  }
52
232
 
53
233
  function readTranscript(transcriptPath, afterLine = -1) {
54
- let text;
55
- try {
56
- text = fs.readFileSync(transcriptPath, 'utf8');
57
- } catch {
58
- return { messages: [], lastLine: afterLine };
59
- }
60
- return parseTranscript(text, afterLine);
234
+ try { return parseTranscript(fs.readFileSync(transcriptPath, 'utf8'), afterLine); }
235
+ catch { return { messages: [], lastLine: afterLine }; }
61
236
  }
62
237
 
63
- module.exports = { parseTranscript, readTranscript, contentToText };
238
+ module.exports = {
239
+ MAX_TEXT_CHARS,
240
+ MAX_TOOL_INPUT_CHARS,
241
+ MAX_TOOL_RESULT_CHARS,
242
+ hash,
243
+ cleanText,
244
+ compactText,
245
+ stableJson,
246
+ contentToText,
247
+ normalizeRecord,
248
+ parseBuffer,
249
+ readTranscriptDelta,
250
+ lineIndexToOffset,
251
+ parseTranscript,
252
+ readTranscript,
253
+ };
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "memoryrouter-claude",
3
- "version": "1.0.0",
4
- "description": "Persistent memory for Claude Code. One command installs hooks that inject relevant memories every turn, capture every conversation, and flush context before compaction — powered by MemoryRouter.",
3
+ "version": "2.0.0",
4
+ "description": "Deterministic, project-scoped persistent memory for Claude Code: automatic hook retrieval/capture plus an optional OAuth MCP control surface.",
5
5
  "license": "MIT",
6
6
  "author": "John Rood <john@memoryrouter.ai>",
7
- "homepage": "https://memoryrouter.ai",
7
+ "homepage": "https://memoryrouter.ai/claude-code",
8
8
  "repository": {
9
9
  "type": "git",
10
10
  "url": "git+https://github.com/John-Rood/MemoryRouter.git",
@@ -17,6 +17,7 @@
17
17
  "claude",
18
18
  "claude-code",
19
19
  "memory",
20
+ "mcp",
20
21
  "ai",
21
22
  "hooks",
22
23
  "persistent-memory",
@@ -32,12 +33,16 @@
32
33
  "bin/",
33
34
  "lib/",
34
35
  "README.md",
36
+ "CHANGELOG.md",
35
37
  "LICENSE"
36
38
  ],
37
39
  "engines": {
38
40
  "node": ">=18.0.0"
39
41
  },
40
42
  "scripts": {
41
- "test": "node --test 'test/*.test.js'"
43
+ "check": "node --check bin/cli.js && for f in lib/*.js; do node --check \"$f\"; done",
44
+ "test": "node --test 'test/*.test.js'",
45
+ "test:all": "npm run check && npm test",
46
+ "pack:check": "npm pack --dry-run"
42
47
  }
43
48
  }