memoryrouter-claude 1.0.1 → 2.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.
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,52 @@
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|failure|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, 'failure', 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
+ SessionEnd: [{ hooks: [commandHook(bin, 'flush', 30)] }],
47
37
  };
48
38
  }
49
39
 
50
40
  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)
41
+ return Boolean(
42
+ hookEntry
43
+ && hookEntry.type === 'command'
44
+ && typeof hookEntry.command === 'string'
45
+ && OURS_RE.test(hookEntry.command)
46
+ && HOOK_RE.test(hookEntry.command),
57
47
  );
58
48
  }
59
49
 
60
- // Remove our hooks from a settings object (mutates a deep copy, returns it).
61
50
  function removeOurHooks(settings) {
62
51
  const out = JSON.parse(JSON.stringify(settings || {}));
63
52
  if (!out.hooks || typeof out.hooks !== 'object') return out;
@@ -65,27 +54,21 @@ function removeOurHooks(settings) {
65
54
  const matchers = out.hooks[event];
66
55
  if (!Array.isArray(matchers)) continue;
67
56
  const kept = [];
68
- for (const m of matchers) {
69
- if (!m || !Array.isArray(m.hooks)) {
70
- kept.push(m);
57
+ for (const matcher of matchers) {
58
+ if (!matcher || !Array.isArray(matcher.hooks)) {
59
+ kept.push(matcher);
71
60
  continue;
72
61
  }
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
62
+ const remaining = matcher.hooks.filter((hook) => !isOurs(hook));
63
+ if (remaining.length) kept.push({ ...matcher, hooks: remaining });
78
64
  }
79
- if (kept.length > 0) out.hooks[event] = kept;
65
+ if (kept.length) out.hooks[event] = kept;
80
66
  else delete out.hooks[event];
81
67
  }
82
68
  if (Object.keys(out.hooks).length === 0) delete out.hooks;
83
69
  return out;
84
70
  }
85
71
 
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
72
  function mergeHooks(settings, bin) {
90
73
  const out = removeOurHooks(settings);
91
74
  const ours = buildHookConfig(bin);
@@ -97,17 +80,15 @@ function mergeHooks(settings, bin) {
97
80
  return out;
98
81
  }
99
82
 
100
- // --- file-level helpers ---
101
-
102
83
  function settingsPathFor(scope, cwd) {
103
84
  if (scope === 'user') return path.join(os.homedir(), '.claude', 'settings.json');
85
+ if (scope === 'local') return path.join(cwd || process.cwd(), '.claude', 'settings.local.json');
104
86
  return path.join(cwd || process.cwd(), '.claude', 'settings.json');
105
87
  }
106
88
 
107
89
  function readSettings(file) {
108
90
  try {
109
- const text = fs.readFileSync(file, 'utf8');
110
- return JSON.parse(text);
91
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
111
92
  } catch (err) {
112
93
  if (err.code === 'ENOENT') return {};
113
94
  throw new Error(`Could not parse ${file}: ${err.message}. Fix or move the file and retry.`);
@@ -116,9 +97,12 @@ function readSettings(file) {
116
97
 
117
98
  function writeSettings(file, settings) {
118
99
  fs.mkdirSync(path.dirname(file), { recursive: true });
119
- const tmp = file + '.tmp';
120
- fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + '\n');
100
+ const existingMode = (() => { try { return fs.statSync(file).mode & 0o777; } catch { return 0o600; } })();
101
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
102
+ fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + '\n', { mode: existingMode });
103
+ try { fs.chmodSync(tmp, existingMode); } catch { /* windows best-effort */ }
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
  };