@skedulo/memory-hub-mcp 0.2.12 → 0.2.14

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/README.md CHANGED
@@ -69,13 +69,17 @@ npm install -g @skedulo/memory-hub-mcp
69
69
  memory-hub-mcp setup
70
70
  ```
71
71
 
72
+ The Claude Code hooks need `bash`, `curl` and `jq` (`jq` ships with macOS 15 and later; otherwise
73
+ `brew install jq`); `setup` warns about any that are missing. `setup` also asks about
74
+ auto-capture, which is off by default; switch it later with `memory-hub-mcp capture on` (or `off`).
75
+
72
76
  `setup` asks which host you use — Claude Code, Claude Desktop, or both (`--code` / `--desktop` /
73
77
  `--both` skip the prompt) — then logs you in with the same browser OAuth `sked` itself uses and
74
78
  mints a personal token from that session. For **Claude Code** it does everything
75
79
  `scripts/setup-dev.sh` does for contributors: registers the MCP server in `~/.claude.json`, puts
76
80
  the token in `~/.claude/settings.json`, installs the `SessionStart` hook into
77
81
  `~/.claude/memory-hub-hook/` and registers it (appending, never stacking duplicates), and syncs
78
- `SKILL.md` into `~/.claude/skills/se-ai-memory-hub/`. For **Claude Desktop** it writes
82
+ every skill folder into `~/.claude/skills/`. For **Claude Desktop** it writes
79
83
  `claude_desktop_config.json` — no hook, because Desktop has none. Every file is merged, never
80
84
  clobbered, and a `.bak` is left behind. Then it makes one real call to confirm the token works
81
85
  before it says done.
@@ -93,8 +97,8 @@ Re-run `memory-hub-mcp setup` anytime — it keeps a token that's already config
93
97
  ### Updates
94
98
 
95
99
  `setup` registers the server as `npx -y @skedulo/memory-hub-mcp@latest`, so every Claude start runs
96
- the newest published version. On start, that server brings the hooks and `SKILL.md` that `setup`
97
- copied into `~/.claude` up to its own version (never down), so nobody re-runs anything after a
100
+ the newest published version. On start, that server brings the hooks and skills that `setup`
101
+ copied into `~/.claude` up to its own version (never down), adding any skill a release introduced, so nobody re-runs anything after a
98
102
  release. Two exceptions: a release that adds a new kind of hook still needs `memory-hub-mcp setup`
99
103
  once, and `setup --no-auto-update` pins the installed binary instead (update it with
100
104
  `npm i -g @skedulo/memory-hub-mcp`, then re-run `setup`).
@@ -159,6 +163,38 @@ design, discovery). `memory_checkRepoStatus` will not work from Desktop. `memory
159
163
  does, but only if you name the repo — pass `repoName` explicitly, since there is nothing to
160
164
  detect; `memory_listTeams` shows the team names to link it to.
161
165
 
166
+ ## Importing product knowledge
167
+
168
+ `memory-hub-mcp import` copies a knowledge pack into the hub as product knowledge pages. A pack is
169
+ one folder per core or project team, `domains/<name>/` in the shared memory repo, holding
170
+ `rules.json`, `constraints.json`, `api.json` and `workflow.json`, each optionally split into
171
+ `<kind>-<area>.json` shards. The product-knowledge skill runs the import and walks you through the
172
+ review; it has two steps, and only the second saves anything:
173
+
174
+ npx -y @skedulo/memory-hub-mcp@latest import convert <shared-memory-repo>/domains/<name> --product "<Product>" --prefix <PREFIX> --by "<your name>"
175
+ npx -y @skedulo/memory-hub-mcp@latest import apply <plan.json> --repo <owner/name>
176
+
177
+ `convert` writes a plan (JSON) and a review file (Markdown) that lists every value that looks like
178
+ customer data, both readable only by you; it will not overwrite a plan that already records saved
179
+ items unless you pass `--force`. It also warns about IDs it cannot prefix, IDs used twice, and
180
+ uncommitted changes in the pack. When the pack is in a git checkout, the Sources page records the
181
+ repo, the pack's path and the HEAD commit, and every saved item carries that repo and commit as its
182
+ `source`, so `memory_checkSources` run in a checkout of the shared memory repo shows when the pack
183
+ has moved on.
184
+
185
+ `apply` refuses until each flagged value is removed or marked `resolved`, and refuses a repo that
186
+ already has pages titled `<Product> ›` that this plan did not save, so a lost plan file cannot
187
+ cause a second import. It saves every page as Team on the repo with an embedding, and records each
188
+ saved uid in the plan, so running it again resumes. Packs in the older layout (JSON under
189
+ `memory/`, with `knowledge/` docs and clarification Q&A files) still convert; their clarifications
190
+ become facts that keep their ticket IDs in the text but link no hub task, so old tickets do not
191
+ appear as Open tasks. `apply` reads `MEMORY_HUB_MCP_TOKEN` and `MEMORY_HUB_FUNCTION_URL` from the
192
+ environment, as the hooks do.
193
+
194
+ After the import, the hub copy is the one developers edit. When the pack repo moves on,
195
+ product-knowledge update converts the pack again and proposes the differences through the usual
196
+ confirmed edits.
197
+
162
198
  ## Tags
163
199
 
164
200
  `memory_save`/`memory_recall`'s `tags` parameter is a fixed picklist
@@ -166,7 +202,7 @@ matching the `AgentFacts`/`AgentSkills`/`AgentWikiPages` custom objects' `Tags`
166
202
  `ConnectedFunction`, `HorizonComponent`, `TriggeredAction`, `ObjectModel`, `MobileExtension`,
167
203
  `Deployment`, `Auth`, `Testing`, `BreezeUI`, `PSS`, `PSF`, `Optimization`, `Webhooks`, `Salesforce`,
168
204
  `Other`, `ArchitectureMap`, `SOW`, `TDD`, `AI`, `API`, `Mobile`, `Infrastructure`, `Security`,
169
- `Messaging` (24 in all; `TAG_VALUES` in `src/index.ts` is the source of truth). The tool's Zod schema enforces this — any other value fails validation
205
+ `Messaging`, `ProductRules` (25 in all; `TAG_VALUES` in `src/index.ts` is the source of truth). The tool's Zod schema enforces this — any other value fails validation
170
206
  before the request reaches the connected function (which otherwise 400s with no indication of
171
207
  what went wrong). If the underlying Picklist's `allowedValues` ever changes, update `TAG_VALUES`
172
208
  in `src/index.ts` to match.
@@ -19,6 +19,12 @@ if [ -z "$TOKEN" ]; then
19
19
  exit 0
20
20
  fi
21
21
 
22
+ # Without jq the JSON below cannot be built, and an invalid line is dropped without a word.
23
+ if ! command -v jq >/dev/null 2>&1; then
24
+ printf '%s\n' '{"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": "memory-hub needs jq, which is not installed, so memory is off this session. Tell the user to install it (macOS: brew install jq; Debian/Ubuntu: sudo apt install jq) and restart Claude Code."}}'
25
+ exit 0
26
+ fi
27
+
22
28
  TMP_DIR=$(mktemp -d)
23
29
  trap 'rm -rf "$TMP_DIR"' EXIT
24
30
 
@@ -431,7 +437,13 @@ auto_capture_registered() {
431
437
  return 1
432
438
  }
433
439
 
434
- if auto_capture_registered; then
440
+ # Same rule as session-stop.sh; change both together.
441
+ capture_opted_in() {
442
+ case "$(printf '%s' "${MEMORY_HUB_AUTO_CAPTURE:-}" | tr '[:upper:]' '[:lower:]')" in 1|true|yes|on) return 0 ;; esac
443
+ [ "${CLAUDE_PLUGIN_OPTION_CAPTURE:-}" = true ]
444
+ }
445
+
446
+ if auto_capture_registered || { [ -n "${CLAUDE_PLUGIN_ROOT:-}" ] && capture_opted_in; }; then
435
447
  SAVE_LINE='Auto-capture is on: after long stretches and at session end, a background run saves or updates a Fact for this session'"'"'s work, shown as "memory-hub auto-saved" notices. Still save what matters yourself.'
436
448
  else
437
449
  SAVE_LINE='What follows is an automatic recall only - nothing in this session is saved unless you call memory_save.'
@@ -7,6 +7,16 @@ if [ -n "${MEMORY_HUB_STOP_HOOK_ACTIVE:-}" ]; then
7
7
  exit 0
8
8
  fi
9
9
 
10
+ opted_in() {
11
+ case "$(printf '%s' "${MEMORY_HUB_AUTO_CAPTURE:-}" | tr '[:upper:]' '[:lower:]')" in 1|true|yes|on) return 0 ;; esac
12
+ [ "${CLAUDE_PLUGIN_OPTION_CAPTURE:-}" = true ]
13
+ }
14
+
15
+ # The plugin registers this hook for everyone, so there it waits for an opt-in; a hand registration is the opt-in.
16
+ if [ -n "${CLAUDE_PLUGIN_ROOT:-}" ] && ! opted_in; then
17
+ exit 0
18
+ fi
19
+
10
20
  TOKEN="${MEMORY_HUB_MCP_TOKEN:-${CLAUDE_PLUGIN_OPTION_TOKEN:-}}"
11
21
  [ -n "$TOKEN" ] || exit 0
12
22
  command -v jq >/dev/null 2>&1 || exit 0
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.refreshInstalledAssets = exports.syncInstalledAssets = exports.recordInstall = exports.recordCliPath = exports.compareVersions = exports.packageVersion = exports.installDirs = exports.CLI_PATH_FILE = exports.VERSION_FILE = exports.HOOK_SCRIPTS = void 0;
3
+ exports.refreshInstalledAssets = exports.syncInstalledAssets = exports.recordInstall = exports.recordCliPath = exports.compareVersions = exports.packageVersion = exports.copySkills = exports.ownsSkillDir = exports.removeSkill = exports.markedSkills = exports.listedSkillFiles = exports.packagedSkills = exports.filesUnder = exports.installDirs = exports.LEGACY_SKILL = exports.SKILL_MARKER = exports.CLI_PATH_FILE = exports.VERSION_FILE = exports.HOOK_SCRIPTS = void 0;
4
4
  const fs_1 = require("fs");
5
5
  const os_1 = require("os");
6
6
  const path_1 = require("path");
@@ -8,13 +8,162 @@ exports.HOOK_SCRIPTS = ['session-start.sh', 'session-stop.sh', 'user-prompt-subm
8
8
  exports.VERSION_FILE = '.installed-version';
9
9
  // The prompt hook runs `embed` from this path, i.e. the build the host last launched.
10
10
  exports.CLI_PATH_FILE = 'cli-path';
11
+ exports.SKILL_MARKER = '.memory-hub';
12
+ // Copied by setup before the marker existed, so it is ours without one.
13
+ exports.LEGACY_SKILL = 'se-ai-memory-hub';
11
14
  function installDirs(home = (0, os_1.homedir)()) {
12
15
  return {
13
16
  hookDir: (0, path_1.join)(home, '.claude', 'memory-hub-hook'),
14
- skillFile: (0, path_1.join)(home, '.claude', 'skills', 'se-ai-memory-hub', 'SKILL.md'),
17
+ skillsDir: (0, path_1.join)(home, '.claude', 'skills'),
15
18
  };
16
19
  }
17
20
  exports.installDirs = installDirs;
21
+ function filesUnder(dir) {
22
+ return (0, fs_1.readdirSync)(dir, { withFileTypes: true }).flatMap((entry) => entry.isDirectory() ? filesUnder((0, path_1.join)(dir, entry.name)) : [(0, path_1.join)(dir, entry.name)]);
23
+ }
24
+ exports.filesUnder = filesUnder;
25
+ function packagedSkills(assetsDir) {
26
+ const root = (0, path_1.join)(assetsDir, 'skills');
27
+ if (!(0, fs_1.existsSync)(root))
28
+ return [];
29
+ return (0, fs_1.readdirSync)(root, { withFileTypes: true })
30
+ .filter((entry) => entry.isDirectory())
31
+ .map((entry) => entry.name)
32
+ .sort();
33
+ }
34
+ exports.packagedSkills = packagedSkills;
35
+ function entryAt(path) {
36
+ try {
37
+ return (0, fs_1.lstatSync)(path);
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ }
43
+ // A symlinked folder or marker is never ours, so nothing is copied into or deleted through it.
44
+ function isMarked(dir) {
45
+ return !!entryAt(dir)?.isDirectory() && !!entryAt((0, path_1.join)(dir, exports.SKILL_MARKER))?.isFile();
46
+ }
47
+ function isLegacyCopy(dir) {
48
+ return (0, path_1.basename)(dir) === exports.LEGACY_SKILL && !!entryAt(dir)?.isDirectory() && !entryAt((0, path_1.join)(dir, exports.SKILL_MARKER));
49
+ }
50
+ // The marker lists the files setup copied, so a later release can delete the ones it no longer ships.
51
+ function listedSkillFiles(dir) {
52
+ if (!isMarked(dir))
53
+ return [];
54
+ return (0, fs_1.readFileSync)((0, path_1.join)(dir, exports.SKILL_MARKER), 'utf8')
55
+ .split('\n')
56
+ .map((line) => line.trim())
57
+ .filter((line) => line && line !== exports.SKILL_MARKER && !(0, path_1.isAbsolute)(line) && !line.split(/[\\/]/).includes('..'));
58
+ }
59
+ exports.listedSkillFiles = listedSkillFiles;
60
+ function writeSkillMarker(dir, files) {
61
+ (0, fs_1.writeFileSync)((0, path_1.join)(dir, exports.SKILL_MARKER), [...new Set(files)].sort().map((file) => `${file}\n`).join(''));
62
+ }
63
+ function skillFiles(srcRoot) {
64
+ return filesUnder(srcRoot).map((src) => (0, path_1.relative)(srcRoot, src).split(path_1.sep).join('/')).sort();
65
+ }
66
+ function markedSkills(skillsDir) {
67
+ if (!(0, fs_1.existsSync)(skillsDir))
68
+ return [];
69
+ return (0, fs_1.readdirSync)(skillsDir, { withFileTypes: true })
70
+ .filter((entry) => entry.isDirectory() && isMarked((0, path_1.join)(skillsDir, entry.name)))
71
+ .map((entry) => entry.name)
72
+ .sort();
73
+ }
74
+ exports.markedSkills = markedSkills;
75
+ // A symlinked subfolder would resolve elsewhere, so the file's folder must resolve to where its path reads.
76
+ function isOwnFile(dir, realDir, path) {
77
+ const folder = (0, path_1.relative)(dir, (0, path_1.dirname)(path));
78
+ if (folder === '..' || folder.startsWith(`..${path_1.sep}`) || (0, path_1.isAbsolute)(folder) || !entryAt(path)?.isFile())
79
+ return false;
80
+ try {
81
+ return (0, fs_1.realpathSync)((0, path_1.dirname)(path)) === (0, path_1.join)(realDir, folder);
82
+ }
83
+ catch {
84
+ return false;
85
+ }
86
+ }
87
+ // Only the folders a removed file leaves empty, so an empty folder the developer made stays.
88
+ function removeEmptyParents(dir, path) {
89
+ for (let parent = (0, path_1.dirname)(path); parent !== dir && (0, fs_1.readdirSync)(parent).length === 0; parent = (0, path_1.dirname)(parent)) {
90
+ (0, fs_1.rmdirSync)(parent);
91
+ }
92
+ }
93
+ function removeFiles(dir, files) {
94
+ const realDir = (0, fs_1.realpathSync)(dir);
95
+ const removed = [];
96
+ for (const file of files) {
97
+ const path = (0, path_1.join)(dir, file);
98
+ if (!isOwnFile(dir, realDir, path))
99
+ continue;
100
+ (0, fs_1.unlinkSync)(path);
101
+ removed.push(path);
102
+ removeEmptyParents(dir, path);
103
+ }
104
+ return removed;
105
+ }
106
+ // Deletes only what the marker lists (plus `extra`), so a file the developer added keeps the folder.
107
+ function removeSkill(skillsDir, name, extra = []) {
108
+ const dir = (0, path_1.join)(skillsDir, name);
109
+ const legacy = isLegacyCopy(dir);
110
+ if (!legacy && !isMarked(dir))
111
+ return [];
112
+ const files = legacy ? ['SKILL.md'] : [...listedSkillFiles(dir), ...extra, exports.SKILL_MARKER];
113
+ const removed = removeFiles(dir, [...new Set(files)]);
114
+ if ((0, fs_1.readdirSync)(dir).length === 0)
115
+ (0, fs_1.rmdirSync)(dir);
116
+ return removed;
117
+ }
118
+ exports.removeSkill = removeSkill;
119
+ function ownsSkillDir(skillsDir, name) {
120
+ const dir = (0, path_1.join)(skillsDir, name);
121
+ return !entryAt(dir) || isMarked(dir) || isLegacyCopy(dir);
122
+ }
123
+ exports.ownsSkillDir = ownsSkillDir;
124
+ function copySkills(assetsDir, skillsDir, log = () => { }) {
125
+ const changed = [];
126
+ const packaged = packagedSkills(assetsDir);
127
+ for (const name of packaged) {
128
+ const srcRoot = (0, path_1.join)(assetsDir, 'skills', name);
129
+ const destRoot = (0, path_1.join)(skillsDir, name);
130
+ if (!ownsSkillDir(skillsDir, name)) {
131
+ log(`memory-hub-mcp: left ${destRoot} alone: memory-hub did not install it`);
132
+ continue;
133
+ }
134
+ const files = skillFiles(srcRoot);
135
+ const listed = listedSkillFiles(destRoot);
136
+ // Marked first, listing old and new files, so an interrupted copy is finished and pruned by the next run.
137
+ (0, fs_1.mkdirSync)(destRoot, { recursive: true });
138
+ writeSkillMarker(destRoot, [...listed, ...files]);
139
+ // Before copying: on a case-insensitive disk, Foo.md renamed to foo.md is one file and would be deleted.
140
+ changed.push(...removeFiles(destRoot, listed.filter((file) => !files.includes(file))));
141
+ for (const file of files) {
142
+ const src = (0, path_1.join)(srcRoot, file);
143
+ const dest = (0, path_1.join)(destRoot, file);
144
+ if ((0, fs_1.existsSync)(dest) && (0, fs_1.readFileSync)(src).equals((0, fs_1.readFileSync)(dest)))
145
+ continue;
146
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(dest), { recursive: true });
147
+ (0, fs_1.copyFileSync)(src, dest);
148
+ changed.push(dest);
149
+ }
150
+ writeSkillMarker(destRoot, files);
151
+ }
152
+ for (const name of new Set([exports.LEGACY_SKILL, ...markedSkills(skillsDir)])) {
153
+ if (packaged.includes(name))
154
+ continue;
155
+ const removed = removeSkill(skillsDir, name);
156
+ if (removed.length > 0)
157
+ log(`memory-hub-mcp: removed ${(0, path_1.join)(skillsDir, name)}: the package no longer ships it`);
158
+ changed.push(...removed);
159
+ }
160
+ return changed;
161
+ }
162
+ exports.copySkills = copySkills;
163
+ // setup --plugin removes the copied skills but can keep a hook script, so hooks alone do not mean skills are wanted.
164
+ function hasCopiedSkills(skillsDir) {
165
+ return ((0, fs_1.existsSync)((0, path_1.join)(skillsDir, exports.LEGACY_SKILL, 'SKILL.md')) || markedSkills(skillsDir).length > 0);
166
+ }
18
167
  function packageVersion(distDir = __dirname) {
19
168
  return JSON.parse((0, fs_1.readFileSync)((0, path_1.join)(distDir, '..', 'package.json'), 'utf8')).version;
20
169
  }
@@ -55,9 +204,8 @@ function syncInstalledAssets(options) {
55
204
  const previous = (0, fs_1.existsSync)(marker) ? (0, fs_1.readFileSync)(marker, 'utf8').trim() : '';
56
205
  if (previous && compareVersions(options.version, previous) < 0)
57
206
  return { updated: [], skipped: 'newer-installed' };
58
- const files = [...hooks, { src: (0, path_1.join)(options.assetsDir, 'SKILL.md'), dest: options.skillFile, executable: false }];
59
207
  const updated = [];
60
- for (const file of files) {
208
+ for (const file of hooks) {
61
209
  if (!(0, fs_1.existsSync)(file.src) || !(0, fs_1.existsSync)(file.dest))
62
210
  continue;
63
211
  if ((0, fs_1.readFileSync)(file.src).equals((0, fs_1.readFileSync)(file.dest)))
@@ -67,6 +215,10 @@ function syncInstalledAssets(options) {
67
215
  (0, fs_1.chmodSync)(file.dest, 0o755);
68
216
  updated.push(file.dest);
69
217
  }
218
+ // Unlike a hook script, a skill the package added since setup is installed: it needs no registration to work.
219
+ if (hasCopiedSkills(options.skillsDir)) {
220
+ updated.push(...copySkills(options.assetsDir, options.skillsDir, options.log));
221
+ }
70
222
  recordInstall(options.hookDir, options.version, options.cliPath);
71
223
  return { updated };
72
224
  }
@@ -77,9 +229,9 @@ function refreshInstalledAssets({ distDir = __dirname, home = (0, os_1.homedir)(
77
229
  return undefined;
78
230
  try {
79
231
  const version = packageVersion(distDir);
80
- const { hookDir, skillFile } = installDirs(home);
232
+ const { hookDir, skillsDir } = installDirs(home);
81
233
  const cliPath = (0, path_1.join)(distDir, 'cli.js');
82
- const result = syncInstalledAssets({ assetsDir: (0, path_1.join)(distDir, '..', 'assets'), hookDir, skillFile, version, cliPath });
234
+ const result = syncInstalledAssets({ assetsDir: (0, path_1.join)(distDir, '..', 'assets'), hookDir, skillsDir, version, cliPath, log });
83
235
  // A plugin install has no copied hooks, but its prompt hook still needs this to embed.
84
236
  if (result.skipped === 'not-installed')
85
237
  recordCliPath(hookDir, cliPath);
package/dist/bulk.js CHANGED
@@ -14,7 +14,7 @@ async function performSaveItem(deps, input) {
14
14
  if (refused) {
15
15
  return { refused: refused.message };
16
16
  }
17
- const result = await (0, save_1.performSave)(deps, input);
17
+ const result = await (0, save_1.performSave)(deps, { ...input, visibility: (0, capture_1.captureVisibility)(input.visibility) });
18
18
  (0, capture_1.logCapture)({ action: 'saved', type: input.type, uid: result.uid, externalRef: input.externalRef });
19
19
  return { result };
20
20
  }
package/dist/capture.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.logCapture = exports.captureUpsert = exports.isCaptureMode = void 0;
3
+ exports.logCapture = exports.captureVisibility = exports.captureUpsert = exports.isCaptureMode = void 0;
4
4
  const fs_1 = require("fs");
5
5
  const SIMILAR_OWN_FACT_FLOOR = 0.86;
6
6
  function isCaptureMode(env = process.env) {
@@ -50,6 +50,11 @@ async function captureUpsert(deps, input, env = process.env) {
50
50
  };
51
51
  }
52
52
  exports.captureUpsert = captureUpsert;
53
+ // An auto-capture is never reviewed before it is saved, so it stays with its author until they share it.
54
+ function captureVisibility(requested, env = process.env) {
55
+ return isCaptureMode(env) ? 'Private' : requested;
56
+ }
57
+ exports.captureVisibility = captureVisibility;
53
58
  function logCapture(entry, env = process.env, append = fs_1.appendFileSync, now = () => new Date()) {
54
59
  const path = env.MEMORY_HUB_CAPTURE_LOG;
55
60
  if (!isCaptureMode(env) || !path) {
package/dist/cli.js CHANGED
@@ -12,6 +12,14 @@ if (command === 'setup') {
12
12
  process.exit(1);
13
13
  });
14
14
  }
15
+ else if (command === 'capture') {
16
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
17
+ const { runCapture } = require('./setup');
18
+ runCapture(process.argv.slice(3)).catch((error) => {
19
+ console.error(error instanceof Error ? error.message : String(error));
20
+ process.exit(1);
21
+ });
22
+ }
15
23
  else if (command === 'embed') {
16
24
  // eslint-disable-next-line @typescript-eslint/no-var-requires
17
25
  const { runEmbed, readProcessStdin } = require('./embed-cli');
@@ -25,6 +33,28 @@ else if (command === 'embed') {
25
33
  }
26
34
  });
27
35
  }
36
+ else if (command === 'import') {
37
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
38
+ const { runImport } = require('./import-cli');
39
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
40
+ const { embed } = require('./embeddings');
41
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
42
+ const { functionUrl } = require('./setup');
43
+ runImport(process.argv.slice(3), {
44
+ env: process.env,
45
+ log: (line) => console.log(line),
46
+ today: () => new Date().toISOString().slice(0, 10),
47
+ embed,
48
+ functionUrl,
49
+ }).then(
50
+ // Exit code, not process.exit: onnxruntime aborts if the process exits with its model session open.
51
+ (code) => {
52
+ process.exitCode = code;
53
+ }, (error) => {
54
+ console.error(error instanceof Error ? error.message : String(error));
55
+ process.exitCode = 1;
56
+ });
57
+ }
28
58
  else if (command === '--help' || command === '-h') {
29
59
  console.log(`memory-hub-mcp — MCP server for the SE AI Memory Hub
30
60
 
@@ -34,7 +64,20 @@ else if (command === '--help' || command === '-h') {
34
64
  on (needs the claude CLI and GitHub access; --no-plugin installs
35
65
  the hooks and skill directly instead). The server runs as
36
66
  npx ...@latest, so each start picks up the newest release;
37
- --no-auto-update pins this install instead.
67
+ --no-auto-update pins this install instead. It asks about
68
+ auto-capture; --capture or --no-capture answers for it.
69
+ memory-hub-mcp capture on|off
70
+ turn auto-capture on or off: after long stretches and at session
71
+ end, a background Claude run, using your Claude usage, saves what
72
+ the session learned (new memories Private, updates keep their
73
+ visibility). setup also asks.
74
+ memory-hub-mcp import convert <packDir> --product <name> --prefix <PREFIX> [--by <name>] [--out <plan.json>] [--force]
75
+ turn a knowledge pack folder (domains/<name> in the shared memory
76
+ repo) into a plan of product knowledge pages, plus a review file
77
+ listing values that look like customer data. Saves nothing.
78
+ memory-hub-mcp import apply <plan.json> --repo <owner/name>
79
+ save a reviewed plan to the hub as Team items on that repo, with
80
+ embeddings. Re-running resumes where it stopped.
38
81
  memory-hub-mcp embed print the embedding of the text on stdin (or the arguments) as JSON;
39
82
  used by the UserPromptSubmit hook. Exits non-zero if it cannot.
40
83
  memory-hub-mcp run the MCP server on stdio (how a host launches it)
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.detectRepoName = exports.canonicalizeRemoteUrl = void 0;
3
+ exports.packCheckout = exports.detectRepoName = exports.canonicalizeRemoteUrl = void 0;
4
4
  // memory-hub-mcp/src/git-remote.ts
5
5
  const child_process_1 = require("child_process");
6
+ const fs_1 = require("fs");
7
+ const path_1 = require("path");
6
8
  /**
7
9
  * Normalize a git remote URL to the canonical `owner/name` form, per the
8
10
  * repo/team grouping spec §3. The host is deliberately dropped — this project
@@ -60,3 +62,19 @@ function detectRepoName(cwd = process.cwd()) {
60
62
  return remoteUrl ? canonicalizeRemoteUrl(remoteUrl) : null;
61
63
  }
62
64
  exports.detectRepoName = detectRepoName;
65
+ function packCheckout(dir) {
66
+ const root = runGit(['rev-parse', '--show-toplevel'], dir);
67
+ const commit = runGit(['rev-parse', 'HEAD'], dir);
68
+ const repo = detectRepoName(dir);
69
+ if (!root || !commit || !repo) {
70
+ return null;
71
+ }
72
+ return {
73
+ repo,
74
+ commit,
75
+ // git prints the real path, so a symlinked temp or home folder must be resolved before comparing.
76
+ pathInRepo: (0, path_1.relative)((0, fs_1.realpathSync)(root), (0, fs_1.realpathSync)(dir)).split(path_1.sep).join('/'),
77
+ dirty: runGit(['status', '--porcelain', '--', '.'], dir) !== null,
78
+ };
79
+ }
80
+ exports.packCheckout = packCheckout;
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.applyPlan = exports.unresolvedFlags = void 0;
4
+ const pack_import_1 = require("./pack-import");
5
+ const save_1 = require("./save");
6
+ function unresolvedFlags(plan) {
7
+ const kept = new Set(plan.flags.filter((flag) => flag.resolved).map((flag) => `${flag.kind}|${flag.match}`));
8
+ const items = [
9
+ ...plan.pages.map((page) => ({ ...page, text: `${page.title}\n${page.content}` })),
10
+ ...plan.facts.map((fact) => ({ ...fact, text: fact.content })),
11
+ ];
12
+ return items
13
+ .filter((item) => !item.skip && !item.savedUid)
14
+ .flatMap((item) => (0, pack_import_1.flagText)(item.text)
15
+ .filter((flag) => !kept.has(`${flag.kind}|${flag.match}`))
16
+ .map((flag) => ({ target: item.id, ...flag })));
17
+ }
18
+ exports.unresolvedFlags = unresolvedFlags;
19
+ async function listWikiPages(client, repo, titlePrefix) {
20
+ const items = [];
21
+ for (;;) {
22
+ const page = await client.listResources({ type: 'Wiki', repo, titlePrefix, offset: items.length, limit: 200 });
23
+ items.push(...page.items);
24
+ if (page.items.length === 0 || items.length >= page.total)
25
+ return items;
26
+ }
27
+ }
28
+ // One item per request, in sequence: the function allows 5 concurrent invocations of 12 s each.
29
+ async function applyPlan(deps, plan, repoName) {
30
+ const open = unresolvedFlags(plan);
31
+ if (open.length) {
32
+ const places = [...new Set(open.map((flag) => `${flag.target} ${flag.kind}`))];
33
+ throw new Error(`Nothing saved: ${open.length} flagged value(s) are unresolved: ${places.slice(0, 10).join('; ')}${places.length > 10 ? '; …' : ''}. ` +
34
+ `${deps.reviewPath} lists each value; resolve them in the plan file first.`);
35
+ }
36
+ const repo = await deps.client.resolveRepo({ name: repoName });
37
+ if (!repo.uid || !('devTeamId' in repo) || !repo.devTeamId) {
38
+ throw new Error(`Nothing saved: ${repoName} is not linked to a team. Link it to the product's team (memory_linkRepoTeam) first.`);
39
+ }
40
+ const repoUid = repo.uid;
41
+ const titlePrefix = `${plan.product} ›`;
42
+ const savedByPlan = new Set(plan.pages.map((page) => page.savedUid));
43
+ const foreign = (await listWikiPages(deps.client, repoUid, titlePrefix)).filter((page) => !savedByPlan.has(page.uid));
44
+ if (foreign.length) {
45
+ const sample = foreign.slice(0, 3).map((page) => `${page.title} (${page.uid})`);
46
+ throw new Error(`Nothing saved: ${repoName} already has ${foreign.length} Wiki page(s) titled "${titlePrefix}" that this plan did not save, e.g. ${sample.join('; ')}. ` +
47
+ 'Resume an earlier import with its own plan file. If that plan is lost, delete those pages or use another --product before importing again.');
48
+ }
49
+ // resolve-task does not say whether it created the task, so an import links none rather than open one per historic ticket.
50
+ const resolveTaskUid = () => Promise.reject(new Error('An import never links a task; the ticket IDs stay in the fact text.'));
51
+ // performSave saves without an embedding when embedding fails; an imported page must stay searchable, so stop instead.
52
+ const save = async (id, embedText, input) => {
53
+ const embedding = await deps.embed(embedText).catch((err) => {
54
+ throw new Error(`Stopped before ${id}: the embedding model did not load (${err instanceof Error ? err.message : String(err)}), and imported pages must be searchable. Items already saved are recorded in the plan; re-run to resume.`);
55
+ });
56
+ const result = await (0, save_1.performSave)({ client: deps.client, embed: async () => embedding, currentRepoUid: async () => repoUid, resolveTaskUid }, input);
57
+ const similar = result.similar?.length ? result.similar : result.possibleDuplicate ? [result.possibleDuplicate] : [];
58
+ if (similar.length)
59
+ deps.log(` ${result.uid} resembles ${similar.map((match) => match.uid).join(', ')}; check for a duplicate`);
60
+ return result;
61
+ };
62
+ let saved = 0;
63
+ let skipped = 0;
64
+ for (const page of plan.pages) {
65
+ if (page.skip || page.savedUid) {
66
+ skipped++;
67
+ continue;
68
+ }
69
+ const result = await save(page.id, `${page.title}\n\n${page.content}`, { type: 'Wiki', title: page.title, content: page.content, tags: page.tags, repo: repoUid, visibility: 'Team', source: plan.source });
70
+ page.savedUid = result.uid;
71
+ deps.savePlan(plan);
72
+ deps.log(`saved ${page.title} -> ${result.uid}`);
73
+ saved++;
74
+ }
75
+ for (const fact of plan.facts) {
76
+ if (fact.skip || fact.savedUid) {
77
+ skipped++;
78
+ continue;
79
+ }
80
+ const result = await save(fact.id, fact.content, { type: 'Fact', content: fact.content, repo: repoUid, visibility: 'Team', source: plan.source });
81
+ fact.savedUid = result.uid;
82
+ deps.savePlan(plan);
83
+ deps.log(`saved fact ${fact.id} -> ${result.uid}`);
84
+ saved++;
85
+ }
86
+ return { saved, skipped };
87
+ }
88
+ exports.applyPlan = applyPlan;
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runImport = exports.IMPORT_USAGE = void 0;
4
+ const fs_1 = require("fs");
5
+ const os_1 = require("os");
6
+ const path_1 = require("path");
7
+ const client_1 = require("./client");
8
+ const pack_import_1 = require("./pack-import");
9
+ const import_apply_1 = require("./import-apply");
10
+ const git_remote_1 = require("./git-remote");
11
+ exports.IMPORT_USAGE = `memory-hub-mcp import convert <packDir> --product <name> --prefix <PREFIX> [--by <name>] [--out <plan.json>] [--force]
12
+ memory-hub-mcp import apply <plan.json> --repo <owner/name>`;
13
+ function option(argv, name) {
14
+ const index = argv.indexOf(`--${name}`);
15
+ const value = index >= 0 ? argv[index + 1] : undefined;
16
+ return value && !value.startsWith('--') ? value : undefined;
17
+ }
18
+ // Holds flagged customer values; chmod also tightens a file an earlier run left readable.
19
+ function writePrivate(path, text) {
20
+ (0, fs_1.writeFileSync)(path, text, { mode: 0o600 });
21
+ (0, fs_1.chmodSync)(path, 0o600);
22
+ }
23
+ // apply rewrites the plan after every save; a rename means an interrupted write never loses the resume state.
24
+ function writePlan(path, plan) {
25
+ writePrivate(`${path}.tmp`, `${JSON.stringify(plan, null, 2)}\n`);
26
+ (0, fs_1.renameSync)(`${path}.tmp`, path);
27
+ }
28
+ function reviewPathFor(planPath) {
29
+ return `${planPath.replace(/\.json$/, '')}.md`;
30
+ }
31
+ function readPlan(path) {
32
+ let plan;
33
+ try {
34
+ plan = JSON.parse((0, fs_1.readFileSync)(path, 'utf8'));
35
+ }
36
+ catch (error) {
37
+ throw new Error(`Could not read the plan ${path}: ${error instanceof Error ? error.message : String(error)}`);
38
+ }
39
+ if (plan.version !== 1 || !Array.isArray(plan.pages) || !Array.isArray(plan.facts) || !Array.isArray(plan.flags)) {
40
+ throw new Error(`${path} is not an import plan this version understands (expected version 1 with pages, facts and flags).`);
41
+ }
42
+ return plan;
43
+ }
44
+ function hasSavedItems(path) {
45
+ const plan = readPlan(path);
46
+ return [...plan.pages, ...plan.facts].some((item) => item.savedUid);
47
+ }
48
+ async function runImport(argv, deps) {
49
+ const [subcommand, rawTarget] = argv;
50
+ const target = rawTarget && !rawTarget.startsWith('--') ? rawTarget : undefined;
51
+ if (subcommand === 'convert' && target) {
52
+ const product = option(argv, 'product');
53
+ const prefix = option(argv, 'prefix');
54
+ if (!product || !prefix) {
55
+ deps.log(`--product and --prefix are required.\n${exports.IMPORT_USAGE}`);
56
+ return 2;
57
+ }
58
+ const packDir = (0, path_1.resolve)(target);
59
+ const plan = (0, pack_import_1.convertPack)({ packDir, product, prefix, by: option(argv, 'by') ?? 'memory-hub-mcp import', today: deps.today(), checkout: (0, git_remote_1.packCheckout)(packDir) });
60
+ const out = option(argv, 'out');
61
+ const planPath = (0, path_1.resolve)(out ?? (0, path_1.join)((0, os_1.tmpdir)(), 'memory-hub-import', `${prefix}.json`));
62
+ const reviewPath = reviewPathFor(planPath);
63
+ if ((0, fs_1.existsSync)(planPath) && !argv.includes('--force') && hasSavedItems(planPath)) {
64
+ deps.log(`${planPath} already records saved items; re-run apply to resume, or pass --force to start a new plan.`);
65
+ return 1;
66
+ }
67
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(planPath), { recursive: true, mode: 0o700 });
68
+ // Only the default folder is ours to tighten; a folder named with --out keeps the developer's own mode.
69
+ if (!out)
70
+ (0, fs_1.chmodSync)((0, path_1.dirname)(planPath), 0o700);
71
+ writePlan(planPath, plan);
72
+ writePrivate(reviewPath, (0, pack_import_1.renderReview)(plan, planPath));
73
+ for (const warning of plan.warnings ?? [])
74
+ deps.log(`Warning: ${warning}`);
75
+ deps.log(`${plan.pages.length} pages, ${plan.facts.length} facts, ${plan.flags.length} flags to review.\nPlan: ${planPath}\nReview: ${reviewPath}`);
76
+ return 0;
77
+ }
78
+ if (subcommand === 'apply' && target) {
79
+ const repoName = option(argv, 'repo');
80
+ if (!repoName) {
81
+ deps.log(`--repo is required.\n${exports.IMPORT_USAGE}`);
82
+ return 2;
83
+ }
84
+ const apiToken = deps.env.MEMORY_HUB_MCP_TOKEN;
85
+ if (!apiToken) {
86
+ deps.log('MEMORY_HUB_MCP_TOKEN is not set. Run `npx -y @skedulo/memory-hub-mcp setup` first.');
87
+ return 1;
88
+ }
89
+ const planPath = (0, path_1.resolve)(target);
90
+ const plan = readPlan(planPath);
91
+ const client = new client_1.MemoryHubClient({ baseUrl: deps.env.MEMORY_HUB_FUNCTION_URL || deps.functionUrl(), apiToken });
92
+ const { saved, skipped } = await (0, import_apply_1.applyPlan)({ client, embed: deps.embed, savePlan: (next) => writePlan(planPath, next), log: deps.log, reviewPath: reviewPathFor(planPath) }, plan, repoName);
93
+ deps.log(`Saved ${saved} item(s); ${skipped} skipped or already saved.`);
94
+ return 0;
95
+ }
96
+ deps.log(exports.IMPORT_USAGE);
97
+ return 2;
98
+ }
99
+ exports.runImport = runImport;