@skedulo/memory-hub-mcp 0.2.11 → 0.2.13

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,6 +69,10 @@ 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
@@ -162,9 +166,11 @@ detect; `memory_listTeams` shows the team names to link it to.
162
166
  ## Tags
163
167
 
164
168
  `memory_save`/`memory_recall`'s `tags` parameter is a fixed picklist
165
- matching the `AgentFacts`/`AgentSkills` custom objects' `Tags` field exactly: `ConnectedFunction`,
166
- `HorizonComponent`, `TriggeredAction`, `ObjectModel`, `MobileExtension`, `Deployment`, `Auth`,
167
- `Testing`, `Other`. The tool's Zod schema enforces this — any other value fails validation
169
+ matching the `AgentFacts`/`AgentSkills`/`AgentWikiPages` custom objects' `Tags` field exactly:
170
+ `ConnectedFunction`, `HorizonComponent`, `TriggeredAction`, `ObjectModel`, `MobileExtension`,
171
+ `Deployment`, `Auth`, `Testing`, `BreezeUI`, `PSS`, `PSF`, `Optimization`, `Webhooks`, `Salesforce`,
172
+ `Other`, `ArchitectureMap`, `SOW`, `TDD`, `AI`, `API`, `Mobile`, `Infrastructure`, `Security`,
173
+ `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
168
174
  before the request reaches the connected function (which otherwise 400s with no indication of
169
175
  what went wrong). If the underlying Picklist's `allowedValues` ever changes, update `TAG_VALUES`
170
176
  in `src/index.ts` to match.
package/assets/SKILL.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: se-ai-memory-hub
3
- description: Use when working in a repo where the memory-hub MCP tools (memory_recall, memory_list, memory_save, memory_saveBatch, memory_upsertPersona, memory_setVisibility, memory_bulkPromoteRepoScoped, memory_grantAccess, memory_checkRepoStatus, memory_linkRepoTeam, memory_moveResourceRepo, memory_listRepos, memory_getSkillGuide) are available, to recall prior context mid-session, save durable facts/skills/scenarios, update your persona, and share items with your team on explicit request
3
+ description: Use when working in a repo where the memory-hub MCP tools (memory_recall, memory_list, memory_save, memory_saveBatch, memory_upsertPersona, memory_setVisibility, memory_bulkPromoteRepoScoped, memory_grantAccess, memory_checkRepoStatus, memory_linkRepoTeam, memory_moveResourceRepo, memory_listRepos, memory_registerRepo, memory_checkSources, memory_listTeams, memory_joinTeam, memory_addTeamMember, memory_listTeamMembers, memory_whoCanRead, memory_update, memory_getSkillGuide) are available, to recall prior context mid-session, save durable facts/skills/scenarios, update your persona, and share items with your team on explicit request
4
4
  ---
5
5
 
6
6
  # SE AI Memory Hub
@@ -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
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) {
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.performCheckSources = exports.execGit = void 0;
4
+ const child_process_1 = require("child_process");
5
+ const TYPES = ['Fact', 'Skill', 'Scenario', 'Wiki'];
6
+ const PAGE_SIZE = 200;
7
+ const HEX_SHA = /^[0-9a-f]{7,64}$/i;
8
+ const execGit = (args) => new Promise((resolve, reject) => {
9
+ (0, child_process_1.execFile)('git', args, { cwd: process.cwd(), encoding: 'utf8' }, (err, stdout) => (err ? reject(err) : resolve(stdout)));
10
+ });
11
+ exports.execGit = execGit;
12
+ async function listBySourceRepo(client, sourceRepo) {
13
+ const items = [];
14
+ for (const type of TYPES) {
15
+ let offset = 0;
16
+ for (;;) {
17
+ const page = await client.listResources({ type, sourceRepo, offset, limit: PAGE_SIZE });
18
+ items.push(...page.items);
19
+ offset += page.items.length;
20
+ if (page.items.length === 0 || offset >= page.total) {
21
+ break;
22
+ }
23
+ }
24
+ }
25
+ return items;
26
+ }
27
+ async function compareToHead(exec, sha) {
28
+ if (!HEX_SHA.test(sha)) {
29
+ return {};
30
+ }
31
+ const behind = await exec(['rev-list', '--count', `${sha}..HEAD`]).then((out) => Number.parseInt(out.trim(), 10), () => undefined);
32
+ if (behind === undefined || Number.isNaN(behind)) {
33
+ return {};
34
+ }
35
+ if (behind > 0) {
36
+ return { behind };
37
+ }
38
+ const isAncestor = await exec(['merge-base', '--is-ancestor', sha, 'HEAD']).then(() => true, () => false);
39
+ return isAncestor ? { behind } : { behind, notAncestor: true };
40
+ }
41
+ async function performCheckSources(deps, input) {
42
+ const repo = (input.repo ?? deps.detectRepoName() ?? '').trim();
43
+ if (!repo) {
44
+ throw new Error('No repo detected in this session. Pass repo as owner/name.');
45
+ }
46
+ const cwdRepo = deps.detectRepoName()?.trim();
47
+ if (input.repo && cwdRepo && cwdRepo.toLowerCase() !== repo.toLowerCase()) {
48
+ throw new Error(`repo "${repo}" does not match this directory's repo "${cwdRepo}". Run this from a checkout of ${repo}, since commits are compared with the local git history.`);
49
+ }
50
+ const exec = deps.exec ?? exports.execGit;
51
+ const head = await exec(['rev-parse', 'HEAD']).then((out) => out.trim(), () => {
52
+ throw new Error('The current directory is not a git checkout, so commits cannot be compared. Run this from a checkout of the repo.');
53
+ });
54
+ const listed = await listBySourceRepo(deps.client, repo);
55
+ const behindBySha = new Map();
56
+ const items = [];
57
+ for (const item of listed) {
58
+ if (!item.source) {
59
+ continue;
60
+ }
61
+ const sha = item.source.commit;
62
+ if (!behindBySha.has(sha)) {
63
+ behindBySha.set(sha, await compareToHead(exec, sha));
64
+ }
65
+ const { behind, notAncestor } = behindBySha.get(sha) ?? {};
66
+ items.push({
67
+ uid: item.uid,
68
+ type: item.type,
69
+ title: item.title,
70
+ source: item.source,
71
+ ...(behind === undefined ? { unknownCommit: true } : { commitsBehind: behind }),
72
+ ...(notAncestor ? { notAncestor } : {}),
73
+ });
74
+ }
75
+ // An unknown sha has no count to rank by, so those sort last.
76
+ items.sort((a, b) => (b.commitsBehind ?? -1) - (a.commitsBehind ?? -1));
77
+ return { repo, head, checked: items.length, items };
78
+ }
79
+ exports.performCheckSources = performCheckSources;
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');
@@ -34,7 +42,13 @@ else if (command === '--help' || command === '-h') {
34
42
  on (needs the claude CLI and GitHub access; --no-plugin installs
35
43
  the hooks and skill directly instead). The server runs as
36
44
  npx ...@latest, so each start picks up the newest release;
37
- --no-auto-update pins this install instead.
45
+ --no-auto-update pins this install instead. It asks about
46
+ auto-capture; --capture or --no-capture answers for it.
47
+ memory-hub-mcp capture on|off
48
+ turn auto-capture on or off: after long stretches and at session
49
+ end, a background Claude run, using your Claude usage, saves what
50
+ the session learned (new memories Private, updates keep their
51
+ visibility). setup also asks.
38
52
  memory-hub-mcp embed print the embedding of the text on stdin (or the arguments) as JSON;
39
53
  used by the UserPromptSubmit hook. Exits non-zero if it cannot.
40
54
  memory-hub-mcp run the MCP server on stdio (how a host launches it)
package/dist/client.js CHANGED
@@ -95,9 +95,24 @@ class MemoryHubClient {
95
95
  listTeams() {
96
96
  return this.post('/memory/list-teams', {});
97
97
  }
98
+ joinTeam(input) {
99
+ return this.post('/memory/join-team', input);
100
+ }
101
+ addTeamMember(input) {
102
+ return this.post('/memory/add-team-member', input);
103
+ }
104
+ listTeamMembers(input) {
105
+ return this.post('/memory/list-team-members', input);
106
+ }
107
+ whoCanRead(input) {
108
+ return this.post('/memory/who-can-read', input);
109
+ }
98
110
  listRepos(input) {
99
111
  return this.post('/memory/list-repos', input);
100
112
  }
113
+ registerRepo(input) {
114
+ return this.post('/memory/register-repo', input);
115
+ }
101
116
  moveResourceRepo(input) {
102
117
  return this.post('/memory/move-resource-repo', input);
103
118
  }
package/dist/index.js CHANGED
@@ -7,12 +7,15 @@ const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
7
7
  const zod_1 = require("zod");
8
8
  const client_1 = require("./client");
9
9
  const list_repos_1 = require("./list-repos");
10
+ const check_sources_1 = require("./check-sources");
11
+ const source_1 = require("./source");
10
12
  const repo_context_1 = require("./repo-context");
11
13
  const task_context_1 = require("./task-context");
12
14
  const git_remote_1 = require("./git-remote");
13
15
  const embeddings_1 = require("./embeddings");
14
16
  const bulk_1 = require("./bulk");
15
17
  const set_visibility_1 = require("./set-visibility");
18
+ const teams_1 = require("./teams");
16
19
  const capture_1 = require("./capture");
17
20
  const recall_1 = require("./recall");
18
21
  const guide_check_1 = require("./guide-check");
@@ -44,6 +47,12 @@ const TAG_VALUES = [
44
47
  'ArchitectureMap',
45
48
  'SOW',
46
49
  'TDD',
50
+ 'AI',
51
+ 'API',
52
+ 'Mobile',
53
+ 'Infrastructure',
54
+ 'Security',
55
+ 'Messaging',
47
56
  ];
48
57
  // The team's one deployed memory-hub function. MEMORY_HUB_FUNCTION_URL only needs to
49
58
  // be set to override this (e.g. pointing at a local `sked function dev` instance).
@@ -64,7 +73,7 @@ const INSTRUCTIONS = [
64
73
  'Call memory_sessionContext once at the start of a conversation to load this',
65
74
  "developer's persona, facts, skills and wiki pages before answering from scratch.",
66
75
  'Before wrapping up a task, save anything durable with memory_save — nothing is',
67
- 'saved automatically unless the optional capture hook is registered, and on hosts',
76
+ 'saved automatically unless the user switched on auto-capture, and on hosts',
68
77
  'without hooks (e.g. Claude Desktop) nothing can capture it.',
69
78
  ].join(' ');
70
79
  const server = new mcp_js_1.McpServer({ name: 'memory-hub-mcp', version: '0.1.0' }, { instructions: INSTRUCTIONS });
@@ -121,7 +130,7 @@ server.tool('memory_recall', "Recall this developer's (or their team's) Facts, S
121
130
  const result = await (0, recall_1.performRecall)({ client, embed: embeddings_1.embed }, input);
122
131
  return { content: [...embeddingNoticeBlocks(), { type: 'text', text: JSON.stringify(result) }] };
123
132
  });
124
- server.tool('memory_get', "Fetch one Fact/Skill/Scenario/Wiki page in full by its uid. memory_recall truncates every item it lists (500 chars by default), so use this to read anything longer than a paragraph — take the uid from a memory_recall result.", {
133
+ server.tool('memory_get', "Fetch one Fact/Skill/Scenario/Wiki page in full by its uid (a Wiki page also returns its links and backlinks). memory_recall truncates every item it lists (500 chars by default), so use this to read anything longer than a paragraph — take the uid from a memory_recall result.", {
125
134
  type: zod_1.z.enum(['Fact', 'Skill', 'Scenario', 'Wiki']),
126
135
  uid: zod_1.z.string().min(1).describe('The uid from a memory_recall result.'),
127
136
  }, async (input) => {
@@ -143,8 +152,9 @@ const saveShape = {
143
152
  links: zod_1.z.array(zod_1.z.string()).optional().describe('Wiki only — UIDs of other wiki pages this one depends on.'),
144
153
  tags: zod_1.z.array(zod_1.z.enum(TAG_VALUES)).optional().describe('Fact, Skill, Wiki only.'),
145
154
  externalRef: zod_1.z.string().optional().describe("Fact, Scenario, Wiki only — the Linear/Jira ticket this relates to, e.g. 'SOL-1234' — pass it when the user mentions a ticket."),
146
- repo: zod_1.z.string().min(1).optional().describe('A DevRepos uid from memory_listRepos, or an owner/name that is already linked to a team, overriding the current-directory auto-detected repo.'),
147
- visibility: zod_1.z.enum(['Private', 'Team', 'Org']).optional().describe('Only when the human approved sharing this item or batch in this conversation. Org is readable by everyone in the tenant. Omit it to get the default.'),
155
+ repo: zod_1.z.string().min(1).optional().describe('A DevRepos uid from memory_listRepos, or an owner/name that is already registered, overriding the current-directory auto-detected repo.'),
156
+ visibility: zod_1.z.enum(['Private', 'Team', 'Org']).optional().describe('Only when the human approved sharing this item or batch in this conversation. Org is readable by everyone in the tenant. Omit it to get the default. Team is refused on a repo no team owns yet.'),
157
+ source: source_1.sourceSchema.optional().describe(source_1.SOURCE_DESCRIPTION),
148
158
  };
149
159
  const saveDeps = {
150
160
  client,
@@ -193,6 +203,8 @@ server.tool('memory_list', "List memory items of one type that you can see, newe
193
203
  tags: zod_1.z.array(zod_1.z.enum(TAG_VALUES)).optional().describe('Items carrying any of these tags. Not supported for Scenario.'),
194
204
  mine: zod_1.z.boolean().optional().describe('true: only items you saved.'),
195
205
  createdAfter: zod_1.z.string().min(1).optional().describe('ISO date or datetime. Skills filter on last modified instead of created.'),
206
+ sourceRepo: zod_1.z.string().min(1).optional().describe('owner/name, exact: only items whose source.repo is this.'),
207
+ verifiedBefore: zod_1.z.string().min(1).refine(source_1.isIsoDate, 'verifiedBefore must be an ISO date or datetime').optional().describe('Only items last verified before this ISO date or datetime.'),
196
208
  offset: zod_1.z.number().int().min(0).optional(),
197
209
  limit: zod_1.z.number().int().min(1).max(200).optional().describe('Default 50, max 200.'),
198
210
  }, async (input) => {
@@ -237,15 +249,41 @@ server.tool('memory_moveResourceRepo', "Reassign an already-saved Fact/Scenario/
237
249
  const result = await (0, bulk_1.performMoveResourceRepo)({ client }, input);
238
250
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
239
251
  });
240
- server.tool('memory_checkRepoStatus', "Check whether the current repo is linked to a memory team yet, reporting the linked team and whether you are a member. See memory_getSkillGuide for what to do if it isn't.", {}, async () => {
252
+ server.tool('memory_checkRepoStatus', "Check whether the current repo is linked to a memory team yet, reporting the linked team and whether you are a member (linked: false with registered: true means the repo exists but has no team). See memory_getSkillGuide for what to do if it isn't.", {}, async () => {
241
253
  const status = await repoContext.checkRepoStatus();
242
254
  return { content: [...(await joinNoticeBlocks()), { type: 'text', text: JSON.stringify(status) }] };
243
255
  });
244
- server.tool('memory_listTeams', "List the memory teams this developer belongs to, for choosing a teamName to pass to memory_linkRepoTeam.", {}, async () => {
256
+ server.tool('memory_listTeams', "List the memory teams this developer belongs to, with each team's memberCount, for choosing a teamName to pass to memory_linkRepoTeam.", {}, async () => {
245
257
  const { teams } = await client.listTeams();
246
258
  return { content: [{ type: 'text', text: JSON.stringify({ teams }) }] };
247
259
  });
248
- server.tool('memory_update', "Revise a memory you saved, in place, instead of saving a second copy. Pass the uid (from memory_recall, memory_get or a memory_save notice) and only the fields to change: content and tags for a Fact; title, content and tags for a Skill or Wiki page; summary for a Scenario; repo (a uid from memory_listRepos, or null for not project-specific) for any. Only the author can update. When this repeats or corrects something you already saved, use this, not memory_save.", {
260
+ server.tool('memory_joinTeam', "Join an EXISTING memory team by name (case-insensitive; it never creates one). Joining changes who can read the team's Team-visibility items, so only call this when a human in the conversation explicitly asks to join that team — never autonomously. Use memory_listTeams for teams you already belong to.", {
261
+ teamName: zod_1.z.string().min(1),
262
+ }, async (input) => {
263
+ const result = await (0, teams_1.performJoinTeam)({ client }, input);
264
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
265
+ });
266
+ server.tool('memory_addTeamMember', "Add a teammate to a memory team you already belong to. agent is their DevAgents uid or their exact display name (case-insensitive); an ambiguous or unknown name errors with candidates. Idempotent. Adding a member changes who can read the team's Team-visibility items, so only call this when a human in the conversation explicitly asks to add that person — never autonomously, the same rule as sharing. Co-membership is symmetric: the new member can read the Team-visibility items of every member, and every member can read theirs, including the repo-less Team items the new member saved, without that person's separate consent. Tell the person being added before you do it.", {
267
+ teamName: zod_1.z.string().min(1),
268
+ agent: zod_1.z.string().min(1).describe('A DevAgents uid or an exact display name.'),
269
+ }, async (input) => {
270
+ const result = await (0, teams_1.performAddTeamMember)({ client }, input);
271
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
272
+ });
273
+ server.tool('memory_listTeamMembers', "List the members (uid and display name) of a memory team by name. Only members of that team may list it.", {
274
+ teamName: zod_1.z.string().min(1),
275
+ }, async (input) => {
276
+ const result = await (0, teams_1.performListTeamMembers)({ client }, input);
277
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
278
+ });
279
+ server.tool('memory_whoCanRead', "Preview who can read one Fact/Scenario/Skill/Wiki page you can read, from its actual visibility: { visibility, audience }. audience.kind is author (Private), everyone (Org), team (the repo's owning team with memberCount), coMembers (Team with no repo: the author's teams, with memberCount and readerCount) or grants (Restricted: the granted agents by display name). Use it to check sharing instead of guessing from your own session.", {
280
+ type: zod_1.z.enum(['Fact', 'Scenario', 'Skill', 'Wiki']),
281
+ uid: zod_1.z.string().min(1),
282
+ }, async (input) => {
283
+ const result = await (0, teams_1.performWhoCanRead)({ client }, input);
284
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
285
+ });
286
+ server.tool('memory_update', "Revise a memory you saved, in place, instead of saving a second copy. Pass the uid (from memory_recall, memory_get or a memory_save notice) and only the fields to change: content and tags for a Fact; title, content and tags for a Skill or Wiki page; summary for a Scenario; links for a Wiki page; factIds for a Scenario; repo (a uid from memory_listRepos, or null for not project-specific) and source (or null to clear it) for any. Only the author can update. When this repeats or corrects something you already saved, use this, not memory_save.", {
249
287
  type: zod_1.z.enum(['Fact', 'Skill', 'Scenario', 'Wiki']),
250
288
  uid: zod_1.z.string().min(1),
251
289
  content: zod_1.z.string().min(1).optional().describe('Fact, Skill, Wiki: the full new text, not a patch.'),
@@ -253,6 +291,9 @@ server.tool('memory_update', "Revise a memory you saved, in place, instead of sa
253
291
  summary: zod_1.z.string().min(1).optional().describe('Scenario only: the full new summary.'),
254
292
  tags: zod_1.z.array(zod_1.z.enum(TAG_VALUES)).optional().describe('Fact, Skill, Wiki only. Replaces the existing tags.'),
255
293
  repo: zod_1.z.string().min(1).nullable().optional().describe('A DevRepos uid, or null to clear it.'),
294
+ links: zod_1.z.array(zod_1.z.string().min(1)).optional().describe('Wiki only: the full new list of target wiki page uids; [] clears. Replaces, not appends.'),
295
+ factIds: zod_1.z.array(zod_1.z.string().min(1)).optional().describe('Scenario only: the full new list of YOUR fact uids that belong to it; [] unlinks all. Facts that are not yours come back as skippedFactIds.'),
296
+ source: source_1.sourceSchema.nullable().optional().describe(`${source_1.SOURCE_DESCRIPTION} Pass it after re-checking the item against the repo; null clears the source.`),
256
297
  }, async (input) => {
257
298
  const result = await (0, revise_1.performUpdate)({ client, embed: embeddings_1.embed }, input);
258
299
  (0, capture_1.logCapture)({ action: 'updated', type: input.type, uid: result.uid });
@@ -272,10 +313,11 @@ server.tool('memory_setTaskStatus', "Mark a ticket's task Done when its work is
272
313
  const result = await (0, revise_1.performSetTaskStatus)({ client }, input);
273
314
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
274
315
  });
275
- server.tool('memory_listRepos', "List repos across this developer's teams, with an optional substring query filter, for targeting memory_save or memory_moveResourceRepo at a repo other than the current directory.", {
316
+ server.tool('memory_listRepos', "List repos across this developer's teams, with an optional substring query filter, for targeting memory_save or memory_moveResourceRepo at a repo other than the current directory. includeUnlinked also lists repos no team owns yet (teamName null).", {
276
317
  query: zod_1.z.string().optional().describe('Case-insensitive substring filter on repo name.'),
318
+ includeUnlinked: zod_1.z.boolean().optional().describe('true: also return repos with no team, with teamName null.'),
277
319
  }, async (input) => {
278
- const repos = await (0, list_repos_1.listReposForTools)(client, input.query);
320
+ const repos = await (0, list_repos_1.listReposForTools)(client, input.query, input.includeUnlinked === true);
279
321
  return { content: [{ type: 'text', text: JSON.stringify({ repos }) }] };
280
322
  });
281
323
  server.tool('memory_linkRepoTeam', "Link a repo to a team by name (existing or new) after the user has confirmed which team it belongs to. Defaults to the repo of the current directory; pass repoName to link a different one, or from a host with no repo at all (Claude Desktop). Pass repoNames (1-50) to link several repos to the same team in one call; each reports its own result. Use memory_listTeams to see the team names to choose from.", {
@@ -290,6 +332,18 @@ server.tool('memory_linkRepoTeam', "Link a repo to a team by name (existing or n
290
332
  const result = await (0, bulk_1.performLinkRepoTeam)({ client, detectRepoName: git_remote_1.detectRepoName }, input);
291
333
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
292
334
  });
335
+ server.tool('memory_registerRepo', "Register a repo nobody has linked to a team yet, so memory can be saved against it. Defaults to the repo of the current directory; pass repoName (owner/name) otherwise. Returns the existing repo if it is already registered: { uid, name, teamName, created }. Items on a repo with no team cannot be Team-visible (Private or Org only) until memory_linkRepoTeam links it.", {
336
+ repoName: zod_1.z.string().min(1).optional().describe("owner/name. Defaults to the current directory's repo; required when there is none."),
337
+ }, async (input) => {
338
+ const result = await (0, list_repos_1.performRegisterRepo)({ client, detectRepoName: git_remote_1.detectRepoName }, input);
339
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
340
+ });
341
+ server.tool('memory_checkSources', "Find memories that may be stale against a repo checkout. Lists the items you can read whose source.repo is the given repo (default: the current directory's repo) and, using git in the current directory, reports how many commits HEAD is ahead of each item's source.commit (commitsBehind), or unknownCommit: true when that commit is not in the local history. Most behind first; unknown commits last. Changes nothing: re-read the repo, then memory_update the item with its new source.", {
342
+ repo: zod_1.z.string().min(1).optional().describe("owner/name. Defaults to the current directory's repo."),
343
+ }, async (input) => {
344
+ const result = await (0, check_sources_1.performCheckSources)({ client, detectRepoName: git_remote_1.detectRepoName }, input);
345
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
346
+ });
293
347
  server.tool('memory_sessionContext', "Load this developer's saved memory-hub context: their persona profile, facts, skills, and — when the session has a repo — its wiki pages. Call once at the start of a conversation. If the result has persona.configured false, offer once to set up their persona with memory_upsertPersona, then drop it for the rest of the conversation. On Claude Code the SessionStart hook already covers facts and skills; call this there for the persona, or if that context is missing.", {}, async () => {
294
348
  const context = await (0, session_context_1.buildSessionContext)({ client, currentRepoUid: repoContext.currentRepoUid });
295
349
  return { content: [...embeddingNoticeBlocks(), { type: 'text', text: JSON.stringify(context) }] };
@@ -1,17 +1,24 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.listReposForTools = void 0;
3
+ exports.performRegisterRepo = exports.listReposForTools = void 0;
4
+ const capture_1 = require("./capture");
4
5
  // Fans out listTeams() -> listRepos() per team and flattens into one list
5
6
  // labeled with each repo's team name — the small, infrequent list a caller
6
7
  // picks a target repo uid from (for memory_saveX's repo param or
7
- // memory_moveResourceRepo). A single team's listRepos failing degrades that
8
- // team's repos out of the result rather than failing the whole call, since
9
- // a partial list is still useful for picking a repo and a total failure
10
- // isn't warranted by one team's transient error.
11
- async function listReposForTools(client, query) {
8
+ // memory_moveResourceRepo). A single call failing degrades its repos out of
9
+ // the result rather than failing the whole call, since a partial list is
10
+ // still useful for picking a repo. includeUnlinked adds one extra call for
11
+ // repos no team owns, which also works for a user on no teams.
12
+ async function listReposForTools(client, query, includeUnlinked = false) {
12
13
  const { teams } = await client.listTeams();
13
- const perTeam = await Promise.allSettled(teams.map((team) => client.listRepos({ teamId: team.uid }).then((result) => result.repos.map((repo) => ({ uid: repo.uid, name: repo.name, teamName: team.name })))));
14
- const allRepos = perTeam
14
+ const perTeam = teams.map((team) => client.listRepos({ teamId: team.uid }).then((result) => result.repos.map((repo) => ({ uid: repo.uid, name: repo.name, teamName: team.name }))));
15
+ const unlinked = includeUnlinked
16
+ ? [
17
+ client.listRepos({ unlinkedOnly: true }).then((result) => result.repos.map((repo) => ({ uid: repo.uid, name: repo.name, teamName: null }))),
18
+ ]
19
+ : [];
20
+ const settled = await Promise.allSettled([...perTeam, ...unlinked]);
21
+ const allRepos = settled
15
22
  .filter((result) => result.status === 'fulfilled')
16
23
  .flatMap((result) => result.value);
17
24
  if (!query) {
@@ -21,3 +28,14 @@ async function listReposForTools(client, query) {
21
28
  return allRepos.filter((repo) => repo.name.toLowerCase().includes(normalizedQuery));
22
29
  }
23
30
  exports.listReposForTools = listReposForTools;
31
+ function performRegisterRepo(deps, input) {
32
+ if ((0, capture_1.isCaptureMode)()) {
33
+ throw new Error('memory_registerRepo is not allowed in capture mode.');
34
+ }
35
+ const repoName = (input.repoName ?? deps.detectRepoName() ?? '').trim();
36
+ if (!repoName) {
37
+ throw new Error('No repo detected in this session. Pass repoName as owner/name.');
38
+ }
39
+ return deps.client.registerRepo({ repoName });
40
+ }
41
+ exports.performRegisterRepo = performRegisterRepo;
@@ -61,8 +61,17 @@ function createRepoContext(client, detectName = git_remote_1.detectRepoName, det
61
61
  };
62
62
  }
63
63
  // resolveRepo auto-joins the repo's team, so a linked repo always means membership.
64
- const team = result.devTeamId ? { teamId: result.devTeamId, teamName: result.teamName, member: true } : {};
65
- return { uid: result.uid, name: result.name, justJoinedTeamName: result.justJoinedTeamName, ...team };
64
+ if (!result.devTeamId) {
65
+ return { uid: result.uid, name: result.name, registered: true, linked: false, teamNameHint };
66
+ }
67
+ return {
68
+ uid: result.uid,
69
+ name: result.name,
70
+ justJoinedTeamName: result.justJoinedTeamName,
71
+ teamId: result.devTeamId,
72
+ teamName: result.teamName,
73
+ member: true,
74
+ };
66
75
  }
67
76
  catch {
68
77
  return NO_REPO;
package/dist/revise.js CHANGED
@@ -1,15 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.performSetTaskStatus = exports.performDelete = exports.performUpdate = void 0;
4
+ const source_1 = require("./source");
4
5
  const save_1 = require("./save");
6
+ const capture_1 = require("./capture");
5
7
  // Which fields each type accepts. Anything else is refused, not dropped, so a typo cannot look like a successful edit.
6
8
  const ALLOWED = {
7
- Fact: ['content', 'tags', 'repo'],
8
- Skill: ['title', 'content', 'tags', 'repo'],
9
- Scenario: ['summary', 'repo'],
10
- Wiki: ['title', 'content', 'tags', 'repo'],
9
+ Fact: ['content', 'tags', 'repo', 'source'],
10
+ Skill: ['title', 'content', 'tags', 'repo', 'source'],
11
+ Scenario: ['summary', 'repo', 'factIds', 'source'],
12
+ Wiki: ['title', 'content', 'tags', 'repo', 'links', 'source'],
11
13
  };
12
- const FIELDS = ['content', 'title', 'summary', 'tags', 'repo'];
14
+ const FIELDS = ['content', 'title', 'summary', 'tags', 'repo', 'links', 'factIds', 'source'];
13
15
  // The text an item is embedded from, matching save.ts, so a revised item stays comparable to the rest.
14
16
  function embeddedText(type, current) {
15
17
  if (type === 'Fact')
@@ -34,12 +36,28 @@ async function performUpdate(deps, input) {
34
36
  const { client, embed } = deps;
35
37
  const given = FIELDS.filter((field) => input[field] !== undefined);
36
38
  if (given.length === 0) {
37
- throw new Error('Nothing to update: pass at least one of content, title, summary, tags or repo.');
39
+ throw new Error('Nothing to update: pass at least one of content, title, summary, tags, repo, links, factIds or source.');
38
40
  }
39
41
  const refused = given.filter((field) => !ALLOWED[input.type].includes(field));
40
42
  if (refused.length > 0) {
43
+ if (refused.includes('links')) {
44
+ throw new Error(`links applies to a Wiki page only; a ${input.type} has none.`);
45
+ }
46
+ if (refused.includes('factIds')) {
47
+ throw new Error(`factIds applies to a Scenario only; a ${input.type} has none.`);
48
+ }
41
49
  throw new Error(`A ${input.type} has no ${refused.join(', ')}. It accepts: ${ALLOWED[input.type].join(', ')}.`);
42
50
  }
51
+ if ((0, capture_1.isCaptureMode)() && (input.links !== undefined || input.factIds !== undefined)) {
52
+ throw new Error('links and factIds replace whole lists and are not allowed in capture mode.');
53
+ }
54
+ for (const field of ['links', 'factIds']) {
55
+ const value = input[field];
56
+ if (value !== undefined && (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || item.trim() === ''))) {
57
+ throw new Error(`${field} must be an array of non-empty uid strings (an empty array clears it).`);
58
+ }
59
+ }
60
+ (0, source_1.assertSource)(input.source, true);
43
61
  const repo = typeof input.repo === 'string' ? await (0, save_1.validateRepoArg)(client, input.repo) : input.repo;
44
62
  const textChanged = input.content !== undefined || input.title !== undefined || input.summary !== undefined;
45
63
  let embedding;
package/dist/save.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.performSave = exports.validateRepoArg = void 0;
4
+ const source_1 = require("./source");
4
5
  const UID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5
6
  const OWNER_NAME_PATTERN = /^[^/\s]+\/[^/\s]+$/;
6
7
  async function validateRepoArg(client, repo) {
@@ -12,7 +13,7 @@ async function validateRepoArg(client, repo) {
12
13
  if (resolved.uid) {
13
14
  return resolved.uid;
14
15
  }
15
- throw new Error(`repo must be a uid from memory_listRepos; "${repo}" is not a linked repo`);
16
+ throw new Error(`repo must be a uid from memory_listRepos; "${repo}" is not a registered repo`);
16
17
  }
17
18
  throw new Error(`repo must be a uid from memory_listRepos, got "${repo}"`);
18
19
  }
@@ -24,6 +25,7 @@ exports.validateRepoArg = validateRepoArg;
24
25
  // itself untestable, the same reason list-repos.ts was extracted earlier.
25
26
  async function performSave(deps, input) {
26
27
  const { client, embed, currentRepoUid, resolveTaskUid } = deps;
28
+ (0, source_1.assertSource)(input.source);
27
29
  const explicitRepo = () => (input.repo === undefined ? undefined : validateRepoArg(client, input.repo));
28
30
  // Required-field checks run BEFORE any repo resolution/network call — the old
29
31
  // per-type tools got this for free from Zod (`content: z.string()`, not
@@ -38,7 +40,7 @@ async function performSave(deps, input) {
38
40
  const repo = (await explicitRepo()) ?? (await currentRepoUid());
39
41
  const devTaskId = input.externalRef ? await resolveTaskUid(input.externalRef, repo ?? null) : undefined;
40
42
  const embedding = await embed(input.content).catch(() => undefined);
41
- return client.saveFact({ content: input.content, tags: input.tags, devTaskId, repo, embedding, visibility: input.visibility });
43
+ return client.saveFact({ content: input.content, tags: input.tags, devTaskId, repo, embedding, visibility: input.visibility, source: input.source });
42
44
  }
43
45
  case 'Skill': {
44
46
  if (!input.title || !input.content) {
@@ -46,7 +48,7 @@ async function performSave(deps, input) {
46
48
  }
47
49
  const repo = (await explicitRepo()) ?? (await currentRepoUid());
48
50
  const embedding = await embed(`${input.title}\n\n${input.content}`).catch(() => undefined);
49
- return client.saveSkill({ title: input.title, content: input.content, tags: input.tags, repo, embedding, visibility: input.visibility });
51
+ return client.saveSkill({ title: input.title, content: input.content, tags: input.tags, repo, embedding, visibility: input.visibility, source: input.source });
50
52
  }
51
53
  case 'Scenario': {
52
54
  if (!input.summary) {
@@ -55,7 +57,7 @@ async function performSave(deps, input) {
55
57
  const repo = (await explicitRepo()) ?? (await currentRepoUid());
56
58
  const devTaskId = input.externalRef ? await resolveTaskUid(input.externalRef, repo ?? null) : undefined;
57
59
  const embedding = await embed(input.summary).catch(() => undefined);
58
- return client.saveScenario({ summary: input.summary, factIds: input.factIds, devTaskId, repo, embedding, visibility: input.visibility });
60
+ return client.saveScenario({ summary: input.summary, factIds: input.factIds, devTaskId, repo, embedding, visibility: input.visibility, source: input.source });
59
61
  }
60
62
  case 'Wiki': {
61
63
  if (!input.title || !input.content) {
@@ -73,6 +75,7 @@ async function performSave(deps, input) {
73
75
  repo,
74
76
  embedding,
75
77
  visibility: input.visibility,
78
+ source: input.source,
76
79
  });
77
80
  }
78
81
  }
package/dist/setup.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.runSetup = exports.registerPromptHook = exports.registerSessionStartHook = exports.removeMcpServer = exports.removeCopiedAssets = exports.unregisterHooks = exports.installPlugin = exports.enableMarketplaceAutoUpdate = exports.writeUserEnv = exports.writeDesktopConfig = exports.writeMcpServer = exports.functionUrl = exports.desktopConfigPath = exports.mcpLaunch = exports.pluginInstalled = exports.PLUGIN_ID = exports.MARKETPLACE_REF = exports.MARKETPLACE_REPO = exports.MARKETPLACE_NAME = exports.launchPath = exports.PACKAGE_SPEC = void 0;
3
+ exports.runSetup = exports.runCapture = exports.registerPromptHook = exports.registerSessionStartHook = exports.removeMcpServer = exports.removeCopiedAssets = exports.setCapture = exports.captureOn = exports.CAPTURE_FLAG = exports.unregisterHooks = exports.installPlugin = exports.enableMarketplaceAutoUpdate = exports.removeUserEnv = exports.writeUserEnv = exports.writeDesktopConfig = exports.writeMcpServer = exports.functionUrl = exports.desktopConfigPath = exports.mcpLaunch = exports.pluginInstalled = exports.PLUGIN_ID = exports.MARKETPLACE_REF = exports.MARKETPLACE_REPO = exports.MARKETPLACE_NAME = exports.launchPath = exports.PACKAGE_SPEC = void 0;
4
4
  const child_process_1 = require("child_process");
5
5
  const fs_1 = require("fs");
6
6
  const os_1 = require("os");
@@ -156,11 +156,19 @@ function writeUserEnv(path, env) {
156
156
  writeJson(path, settings);
157
157
  }
158
158
  exports.writeUserEnv = writeUserEnv;
159
+ function removeUserEnv(path, key) {
160
+ const settings = readJson(path);
161
+ if (!settings.env || !(key in settings.env))
162
+ return;
163
+ delete settings.env[key];
164
+ writeJson(path, settings);
165
+ }
166
+ exports.removeUserEnv = removeUserEnv;
159
167
  // Only our own entries are touched — a developer may have their own SessionStart hooks.
160
168
  // "Ours" is the script's identity, not its exact path: setup-dev.sh registers the repo
161
169
  // checkout and this installer ~/.claude/memory-hub-hook, so matching the exact string
162
170
  // lets both stack copies of the same script. Replaces, keeping any timeout it carried.
163
- function registerHook(path, event, hookPath, script, timeout) {
171
+ function registerHook(path, event, hookPath, script, timeout, extra = {}) {
164
172
  const settings = readJson(path);
165
173
  const hooks = (settings.hooks ||= {});
166
174
  const entries = (hooks[event] ||= []);
@@ -168,7 +176,7 @@ function registerHook(path, event, hookPath, script, timeout) {
168
176
  (command.trim() === hookPath || command.trim().endsWith(`memory-hub-hook/${script}`));
169
177
  const ours = entries.flatMap((entry) => (entry.hooks || []).filter((h) => isOurs(h.command)));
170
178
  const already = ours.length === 1 && ours[0].command === hookPath;
171
- const kept = { type: 'command', ...(timeout ? { timeout } : {}), ...ours[0], command: hookPath };
179
+ const kept = { type: 'command', ...(timeout ? { timeout } : {}), ...extra, ...ours[0], command: hookPath };
172
180
  for (const entry of entries) {
173
181
  entry.hooks = (entry.hooks || []).filter((h) => !isOurs(h.command));
174
182
  }
@@ -220,25 +228,75 @@ function claudeRunner() {
220
228
  };
221
229
  }
222
230
  // The plugin brings its own hooks, so setup's copies would run every hook twice.
231
+ // Empty event lists are dropped too: left behind, they read as "the hooks are missing".
232
+ function removeHookCommands(settings, event, matches) {
233
+ const entries = settings.hooks?.[event];
234
+ if (!Array.isArray(entries))
235
+ return { removed: 0, changed: false };
236
+ let removed = 0;
237
+ for (const entry of entries) {
238
+ const before = (entry.hooks || []).length;
239
+ entry.hooks = (entry.hooks || []).filter((h) => !(typeof h.command === 'string' && matches(h.command.trim())));
240
+ removed += before - entry.hooks.length;
241
+ }
242
+ const kept = entries.filter((entry) => entry.hooks.length > 0);
243
+ if (kept.length > 0) {
244
+ settings.hooks[event] = kept;
245
+ }
246
+ else {
247
+ delete settings.hooks[event];
248
+ }
249
+ return { removed, changed: removed > 0 || kept.length !== entries.length || kept.length === 0 };
250
+ }
223
251
  function unregisterHooks(path) {
224
252
  const settings = readJson(path);
225
253
  let removed = 0;
254
+ let changed = false;
226
255
  for (const [event, script] of [['SessionStart', 'session-start.sh'], ['UserPromptSubmit', 'user-prompt-submit.sh']]) {
227
- const entries = settings.hooks?.[event];
228
- if (!Array.isArray(entries))
229
- continue;
230
- for (const entry of entries) {
231
- const before = (entry.hooks || []).length;
232
- entry.hooks = (entry.hooks || []).filter((h) => !(typeof h.command === 'string' && h.command.trim().endsWith(`memory-hub-hook/${script}`)));
233
- removed += before - entry.hooks.length;
234
- }
235
- settings.hooks[event] = entries.filter((entry) => entry.hooks.length > 0);
256
+ const result = removeHookCommands(settings, event, (command) => command.endsWith(`memory-hub-hook/${script}`));
257
+ removed += result.removed;
258
+ changed ||= result.changed;
236
259
  }
237
- if (removed > 0)
260
+ if (changed)
238
261
  writeJson(path, settings);
239
262
  return removed;
240
263
  }
241
264
  exports.unregisterHooks = unregisterHooks;
265
+ exports.CAPTURE_FLAG = 'MEMORY_HUB_AUTO_CAPTURE';
266
+ const CAPTURE_EVENTS = ['Stop', 'SessionEnd'];
267
+ // Same reading as the hooks' opted_in; change both together.
268
+ function flagOn(value) {
269
+ return typeof value === 'string' && ['1', 'true', 'yes', 'on'].includes(value.toLowerCase());
270
+ }
271
+ function captureOn(settingsPath) {
272
+ const settings = readJson(settingsPath);
273
+ if (flagOn(settings.env?.[exports.CAPTURE_FLAG]))
274
+ return true;
275
+ return CAPTURE_EVENTS.some((event) => (settings.hooks?.[event] ?? []).some((entry) => (entry.hooks || []).some((h) => typeof h.command === 'string' && h.command.includes('session-stop.sh'))));
276
+ }
277
+ exports.captureOn = captureOn;
278
+ // With the plugin its own hooks wait for the flag; without it the copied hook is registered here.
279
+ function setCapture(settingsPath, on, mode) {
280
+ if (on) {
281
+ writeUserEnv(settingsPath, { [exports.CAPTURE_FLAG]: '1' });
282
+ if (!mode.plugin && mode.hookPath) {
283
+ registerHook(settingsPath, 'Stop', mode.hookPath, 'session-stop.sh', undefined, { async: true });
284
+ registerHook(settingsPath, 'SessionEnd', mode.hookPath, 'session-stop.sh', 60);
285
+ }
286
+ return;
287
+ }
288
+ removeUserEnv(settingsPath, exports.CAPTURE_FLAG);
289
+ if (!mode.plugin && mode.hookPath) {
290
+ const settings = readJson(settingsPath);
291
+ let changed = false;
292
+ for (const event of CAPTURE_EVENTS) {
293
+ changed = removeHookCommands(settings, event, (command) => command === mode.hookPath).changed || changed;
294
+ }
295
+ if (changed)
296
+ writeJson(settingsPath, settings);
297
+ }
298
+ }
299
+ exports.setCapture = setCapture;
242
300
  // Under the plugin a copied SKILL.md lists the skill twice. state/ and cli-path stay: the plugin's prompt hook uses them.
243
301
  function removeCopiedAssets(settingsPath, home = (0, os_1.homedir)()) {
244
302
  const { hookDir, skillFile } = (0, asset_sync_1.installDirs)(home);
@@ -344,6 +402,60 @@ function existingToken(hosts) {
344
402
  const env = readJson(desktopConfigPath()).mcpServers?.['memory-hub']?.env || {};
345
403
  return { token: env.MEMORY_HUB_MCP_TOKEN, url: env.MEMORY_HUB_FUNCTION_URL };
346
404
  }
405
+ const CAPTURE_SWITCH_HINT = 'Switch it any time with `npx -y @skedulo/memory-hub-mcp@latest capture on` (or `off`).';
406
+ function warnHookTools() {
407
+ if ((0, os_1.platform)() === 'win32') {
408
+ console.log(' warning: the hooks are bash scripts, so on Windows they only run inside Git Bash or WSL');
409
+ }
410
+ for (const tool of ['bash', 'curl', 'jq']) {
411
+ if ((0, child_process_1.spawnSync)('which', [tool]).status !== 0) {
412
+ console.log(` warning: ${tool} is not installed. The hooks need it, so memory is not injected until you install it (macOS: brew install ${tool}).`);
413
+ }
414
+ }
415
+ }
416
+ async function askCapture(current) {
417
+ console.log(' After long stretches and at session end, a background Claude run saves what the');
418
+ console.log(' session learned. New memories are Private (shared only if you share them); an');
419
+ console.log(' update keeps the memory\'s visibility. It uses your Claude usage, and you see what');
420
+ console.log(' it saved at the start of your next session.');
421
+ const answer = (await ask(` Turn on auto-capture? (${current ? 'Y/n' : 'y/N'}): `)).toLowerCase();
422
+ if (!answer)
423
+ return current;
424
+ return answer.startsWith('y');
425
+ }
426
+ async function runCapture(argv = []) {
427
+ const settingsPath = (0, path_1.join)((0, os_1.homedir)(), '.claude', 'settings.json');
428
+ const plugin = pluginInstalled();
429
+ const hookPath = (0, path_1.join)((0, asset_sync_1.installDirs)().hookDir, 'session-stop.sh');
430
+ const choice = argv[0];
431
+ const pluginNote = "If you turned on the plugin's Auto-capture option in /plugin configure, that keeps it on too.";
432
+ if (choice !== 'on' && choice !== 'off') {
433
+ console.log(`auto-capture is ${captureOn(settingsPath) ? 'on' : 'off'} in ~/.claude/settings.json.`);
434
+ if (plugin)
435
+ console.log(pluginNote);
436
+ console.log('Usage: memory-hub-mcp capture on|off');
437
+ return;
438
+ }
439
+ if (choice === 'on' && !plugin && !(0, fs_1.existsSync)(hookPath)) {
440
+ console.log('memory-hub is not set up for Claude Code yet. Run `npx -y @skedulo/memory-hub-mcp setup` first.');
441
+ process.exitCode = 1;
442
+ return;
443
+ }
444
+ setCapture(settingsPath, choice === 'on', { plugin, hookPath: plugin ? undefined : hookPath });
445
+ if (choice === 'on') {
446
+ console.log('auto-capture is on: after long stretches and at session end, a background Claude run, using your Claude usage, saves what the session learned. New memories are Private; updates keep their visibility.');
447
+ }
448
+ else if (captureOn(settingsPath)) {
449
+ console.log('auto-capture is still on: a session-stop.sh entry under Stop or SessionEnd in ~/.claude/settings.json keeps it running. Remove that entry by hand to stop it.');
450
+ }
451
+ else {
452
+ console.log('auto-capture is off.');
453
+ if (plugin)
454
+ console.log(pluginNote);
455
+ }
456
+ console.log('Restart Claude Code to pick this up.');
457
+ }
458
+ exports.runCapture = runCapture;
347
459
  async function runSetup(argv = []) {
348
460
  console.log('==> Setting up the memory hub');
349
461
  let hosts;
@@ -464,11 +576,21 @@ async function runSetup(argv = []) {
464
576
  const prompt = registerPromptHook((0, path_1.join)((0, os_1.homedir)(), '.claude', 'settings.json'), promptHookPath);
465
577
  console.log(` UserPromptSubmit hook -> ${promptHookPath}${prompt.already ? ' (already registered)' : ''}`);
466
578
  console.log(' skill -> ~/.claude/skills/se-ai-memory-hub/SKILL.md');
467
- for (const tool of ['curl', 'jq']) {
468
- if ((0, child_process_1.spawnSync)('which', [tool]).status !== 0) {
469
- console.log(` warning: ${tool} is not installed — the startup hook needs it`);
470
- }
471
- }
579
+ }
580
+ if (hosts.includes('code')) {
581
+ warnHookTools();
582
+ console.log();
583
+ console.log('==> Auto-capture');
584
+ const hookPath = plugin ? undefined : (0, path_1.join)((0, asset_sync_1.installDirs)().hookDir, 'session-stop.sh');
585
+ let on = captureOn(settingsPath);
586
+ if (argv.includes('--capture'))
587
+ on = true;
588
+ else if (argv.includes('--no-capture'))
589
+ on = false;
590
+ else if (process.stdin.isTTY)
591
+ on = await askCapture(on);
592
+ setCapture(settingsPath, on, { plugin, hookPath });
593
+ console.log(on ? ` on. ${CAPTURE_SWITCH_HINT}` : ` off. ${CAPTURE_SWITCH_HINT}`);
472
594
  }
473
595
  if (hosts.includes('desktop')) {
474
596
  console.log();
package/dist/source.js ADDED
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.assertSource = exports.SOURCE_DESCRIPTION = exports.sourceSchema = exports.isIsoDate = void 0;
4
+ const zod_1 = require("zod");
5
+ const REPO_PATTERN = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
6
+ const COMMIT_PATTERN = /^[0-9a-fA-F]{7,64}$/;
7
+ const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?$/;
8
+ function isIsoDate(value) {
9
+ return ISO_DATE_PATTERN.test(value) && !Number.isNaN(new Date(value).getTime());
10
+ }
11
+ exports.isIsoDate = isIsoDate;
12
+ exports.sourceSchema = zod_1.z.object({
13
+ repo: zod_1.z.string().max(255).regex(REPO_PATTERN, 'repo must be in owner/name form'),
14
+ commit: zod_1.z.string().regex(COMMIT_PATTERN, 'commit must be 7-64 hex characters'),
15
+ verifiedAt: zod_1.z.string().refine(isIsoDate, 'verifiedAt must be an ISO date').optional(),
16
+ });
17
+ exports.SOURCE_DESCRIPTION = 'The repo this knowledge was derived from and the HEAD commit sha you read: { repo: "owner/name", commit, verifiedAt? }. verifiedAt defaults to now.';
18
+ function assertSource(source, allowNull = false) {
19
+ if (source === undefined || (source === null && allowNull)) {
20
+ return;
21
+ }
22
+ const parsed = exports.sourceSchema.safeParse(source);
23
+ if (!parsed.success) {
24
+ throw new Error(`source is invalid: ${parsed.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`).join('; ')}`);
25
+ }
26
+ }
27
+ exports.assertSource = assertSource;
package/dist/teams.js ADDED
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.performWhoCanRead = exports.performListTeamMembers = exports.performAddTeamMember = exports.performJoinTeam = void 0;
4
+ function requireText(value, name) {
5
+ if (typeof value !== 'string' || value.trim() === '') {
6
+ throw new Error(`${name} is required.`);
7
+ }
8
+ return value.trim();
9
+ }
10
+ async function performJoinTeam(deps, input) {
11
+ return deps.client.joinTeam({ teamName: requireText(input.teamName, 'teamName') });
12
+ }
13
+ exports.performJoinTeam = performJoinTeam;
14
+ async function performAddTeamMember(deps, input) {
15
+ return deps.client.addTeamMember({ teamName: requireText(input.teamName, 'teamName'), agent: requireText(input.agent, 'agent') });
16
+ }
17
+ exports.performAddTeamMember = performAddTeamMember;
18
+ async function performListTeamMembers(deps, input) {
19
+ return deps.client.listTeamMembers({ teamName: requireText(input.teamName, 'teamName') });
20
+ }
21
+ exports.performListTeamMembers = performListTeamMembers;
22
+ async function performWhoCanRead(deps, input) {
23
+ return deps.client.whoCanRead({ resourceType: input.type, uid: requireText(input.uid, 'uid') });
24
+ }
25
+ exports.performWhoCanRead = performWhoCanRead;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skedulo/memory-hub-mcp",
3
- "version": "0.2.11",
3
+ "version": "0.2.13",
4
4
  "description": "MCP server for the SE AI Memory Hub: recall and save developer memory from Claude Code and Claude Desktop.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
package/skill-guide.md CHANGED
@@ -70,7 +70,11 @@ picklist, not a free-form string — pick from `ConnectedFunction`,
70
70
  codebase-map skills described below, not for facts), `SOW` (a Statement of
71
71
  Work), `TDD` (a Technical Design Doc) — `SOW`/`TDD` are most useful on wiki
72
72
  pages, where a whole document usually lands (see below), but are valid on
73
- Fact, Skill, or Wiki saves alike. The tool schema enforces this, so an invalid tag fails
73
+ Fact, Skill, or Wiki saves alike. Newer tags: `AI` (LLMs, agents, MCP, prompts),
74
+ `API` (REST/GraphQL endpoints and schemas), `Mobile` (the Skedulo mobile app/v3 —
75
+ not `MobileExtension`, which is MEX forms), `Infrastructure` (CI/CD, pipelines,
76
+ hosting, environments), `Security` (permissions, secrets, vulnerabilities),
77
+ `Messaging` (SMS, email, notifications, queues). The tool schema enforces this, so an invalid tag fails
74
78
  with a clear validation error rather than reaching the backend — if this
75
79
  list and the schema's actual error ever disagree, trust the error: this
76
80
  list is prose, kept in sync by hand.
@@ -115,9 +119,12 @@ a link *is* the dependency edge, just without a label on it (plain
115
119
  "linked," not "depends on" vs. "supersedes"). The link is directional (the page you're saving is the source, each UID in
116
120
  `links` is a target) and computes backlinks automatically for the reverse
117
121
  direction. `memory_get type=Wiki` returns `links` (the targets this page
118
- points at) and `backlinks` (pages that link to it). Both come only from link
119
- rows you created yourself, so a teammate's links to your page don't appear.
120
- The panel's Wiki tab shows the same graph.
122
+ points at) and `backlinks` (pages that link to it) for any page you can
123
+ read, whoever authored it: links are limited to target pages you can read, and
124
+ backlinks to source pages you can read. To change a page's links later, pass
125
+ the full new `links` list to `memory_update` (it replaces; `[]` clears). Read
126
+ the current list with `memory_get` first. The panel's Wiki tab shows the same
127
+ graph.
121
128
 
122
129
  **If the user hands you a document (PDF, Word, PowerPoint, etc.) to turn
123
130
  into a wiki page**, and a `convert_to_markdown` tool is available (from the
@@ -157,12 +164,12 @@ it. A save that happens is worth more than a better-timed one that doesn't.
157
164
 
158
165
  ## Automatic capture (when enabled)
159
166
 
160
- Nothing saves on its own unless the user has switched on the optional capture
161
- hook. It is `memory-hub-hook/session-stop.sh`, registered by hand in
162
- `~/.claude/settings.json` as a `Stop` and/or `SessionEnd` hook; the plugin and
163
- `setup` do not install it. The session-start Reminder says "Auto-capture is on"
164
- when it is registered. Without it, a memory exists only if you called
165
- `memory_save`.
167
+ Nothing saves on its own unless the user has switched on auto-capture. It is
168
+ off by default: `setup` asks, and `npx -y @skedulo/memory-hub-mcp@latest capture on`
169
+ (or `off`) switches it, as does the plugin's Auto-capture option. The
170
+ session-start Reminder says "Auto-capture is on" when it is. Without it, a
171
+ memory exists only if you called `memory_save`. If the user asks how to turn it
172
+ on, give them that one command; never ask them to edit hook JSON.
166
173
 
167
174
  When it runs, it resumes the session headlessly and asks the model to keep
168
175
  anything durable:
@@ -172,7 +179,10 @@ anything durable:
172
179
  - **`SessionEnd`**: once, in the background, when the session ends.
173
180
 
174
181
  It updates the existing Fact for a ticket instead of adding copies, so a
175
- ticket's Fact is revised as the work moves on. Saving yourself is still the
182
+ ticket's Fact is revised as the work moves on. New memories it saves are
183
+ Private, even in a repo linked to a team, because nobody reviewed them first;
184
+ the user shares one with `memory_setVisibility` once they have read it. An
185
+ update to an existing memory keeps that memory's visibility. Saving yourself is still the
176
186
  right move for anything you know matters now. The capture model is
177
187
  `MEMORY_HUB_CAPTURE_MODEL`, default `sonnet`.
178
188
 
@@ -187,8 +197,10 @@ the list of saves in `~/.claude/memory-hub-hook/state/captures-<session>.jsonl`,
187
197
  and a one-line entry per run in `$TMPDIR/memory-hub-stop-hook.log`
188
198
  (`/tmp/memory-hub-stop-hook.log` when `TMPDIR` is unset).
189
199
 
190
- To turn it off, remove the `session-stop.sh` entry from the `Stop` and
191
- `SessionEnd` hooks in `~/.claude/settings.json`.
200
+ To turn it off: `npx -y @skedulo/memory-hub-mcp@latest capture off`, and switch off the
201
+ plugin's Auto-capture option if it was turned on there. A `session-stop.sh`
202
+ registered by hand in `~/.claude/settings.json` keeps capturing until its entry
203
+ is removed.
192
204
 
193
205
  ## Revise, don't re-save
194
206
 
@@ -197,8 +209,12 @@ repeats a memory of yours, change that memory instead of saving another one:
197
209
 
198
210
  - **`memory_update`** with `type`, `uid` and only the fields that change
199
211
  (`content`/`tags` for a Fact; `title`/`content`/`tags` for a Skill or Wiki
200
- page; `summary` for a Scenario; `repo`, or `null`, for any). Pass the full
201
- new text, not a patch. It re-embeds the text, so search keeps working. Only
212
+ page; `summary` for a Scenario; `links` for a Wiki page; `factIds` for a
213
+ Scenario; `repo`, or `null`, and `source`, or `null`, for any). Pass the full new text, not a patch.
214
+ `links` (target wiki uids) and `factIds` (uids of your facts that belong to
215
+ the scenario) replace the whole list; `[]` clears it. A fact that is not
216
+ yours comes back in `skippedFactIds` instead of failing; facts left out of the
217
+ new list are unlinked from the scenario. It re-embeds the text, so search keeps working. Only
202
218
  the author can update.
203
219
  - **`memory_delete`** removes one of your memories for good. Use it for a copy
204
220
  you have just merged into another, or a memory that is wrong or obsolete.
@@ -311,8 +327,27 @@ Two consequences worth knowing:
311
327
  now. Use `memory_setVisibility` to demote it back, the same way you'd use
312
328
  it to promote something the other direction (see below).
313
329
 
330
+ ## Checking who can read an item
331
+
332
+ - **`memory_whoCanRead`** — `type` and `uid` of an item you can read; returns
333
+ `{ visibility, audience }` where `audience.kind` is `author`, `everyone`,
334
+ `team` (the repo's team, with `memberCount`), `coMembers` (Team item with no
335
+ repo: the author's teams plus `readerCount`) or `grants` (Restricted: display
336
+ names of the granted agents). Use it to check who sees an item instead of
337
+ guessing from the author's session. It only reads, so it needs no
338
+ permission.
339
+
314
340
  ## Sharing — only on explicit human request
315
341
 
342
+ - **`memory_joinTeam`** — `teamName` of an existing team (never creates one).
343
+ **`memory_addTeamMember`** — `teamName` you already belong to and `agent`
344
+ (a uid or exact display name; idempotent). Both change who can read Team
345
+ items, so call them only when a human explicitly asks, like sharing.
346
+ Membership is symmetric: adding someone shares their own repo-less Team
347
+ items with every member of the team, and theirs with them, so tell the
348
+ person being added first.
349
+ **`memory_listTeamMembers`** — `teamName`; members only. `memory_listTeams`
350
+ now includes each team's `memberCount`.
316
351
  - **`memory_setVisibility`** — changes a Fact/Scenario/Skill/Wiki page's
317
352
  visibility in either direction: promote to `Team`, `Org` or `Restricted`,
318
353
  or demote back to `Private` (e.g. to undo an automatic Team default, or to
@@ -352,14 +387,17 @@ on one bad item.
352
387
  (`uid`, title, `visibility`, repo, `mine`), with `total` and a page of items
353
388
  (`offset`, `limit` up to 200, default 50). Filters: `repo` (a uid; `null`
354
389
  means no repo), `visibility`, `titlePrefix`, `tags` (not for Scenario),
355
- `mine`, `createdAfter` (ISO date). It is not a search; use `memory_recall`
390
+ `mine`, `createdAfter` (ISO date), `sourceRepo` (`owner/name`, exact) and
391
+ `verifiedBefore` (ISO date; items last verified earlier). Each item carries its
392
+ `source` when it has one. It is not a search; use `memory_recall`
356
393
  for that. It changes nothing.
357
394
  - **`memory_saveBatch`** — `items` (1-25), each exactly a `memory_save` input.
358
395
  Results come back by `index`; duplicates appear as a short `similarTo` list.
359
396
  - **`memory_moveResourceRepo`** — `resourceId` or `resourceIds` (1-100, one
360
397
  `resourceType`), exactly one.
361
398
  - **`memory_linkRepoTeam`** — `repoName`, or `repoNames` (1-50) for one
362
- `teamName`; with neither it uses the current repo.
399
+ `teamName`; with neither it uses the current repo. It also gives a repo
400
+ registered with `memory_registerRepo` its first team.
363
401
 
364
402
  **Bulk-sharing recipe.** Call `memory_list` (e.g. `mine: true`, a `repo`,
365
403
  `visibility: 'Team'`) and collect the uids from every page first, until
@@ -385,6 +423,30 @@ so a batch share must be done in the live conversation. The allow rules are
385
423
  per-user opt-in that removes the last interactive check before an item goes
386
424
  Team or Org, so add it only while doing an approved bulk share.
387
425
 
426
+ ## Source tracking: keeping repo knowledge fresh
427
+
428
+ Knowledge you derive from a repo goes stale as the repo moves. When you save a
429
+ Fact, Skill, Scenario or Wiki page from reading a repo, pass `source` on
430
+ `memory_save` (or each `memory_saveBatch` item): `{ repo: 'owner/name', commit,
431
+ verifiedAt? }`, where `commit` is the HEAD sha (7-64 hex characters) of the
432
+ checkout you read (`git rev-parse HEAD`). `verifiedAt` defaults to now. Leave
433
+ `source` off for knowledge that is not tied to a repo's contents, such as a
434
+ preference or a decision. Capture mode may pass `source`.
435
+
436
+ To find what has gone stale, call `memory_checkSources` (optionally with `repo`;
437
+ it defaults to the current directory's repo, and must be run from a checkout of
438
+ it). It lists the items you can read whose `source.repo` is that repo and, from
439
+ local git, how many commits HEAD is ahead of each item's `source.commit`
440
+ (`commitsBehind`), most behind first. `unknownCommit: true` means that commit is
441
+ not in the local history (for example a rebase or a shallow clone), so it is
442
+ listed last and its age is unknown. `notAncestor: true` means the commit is
443
+ not behind HEAD but is not an ancestor of it either (HEAD is behind it or on
444
+ another branch), so `commitsBehind` is not a staleness signal there. It changes nothing. For each item worth
445
+ refreshing, re-read the repo, then `memory_update` it with the corrected text
446
+ (if any) and a new `source` at the current HEAD; `source: null` clears it.
447
+ `memory_list` with `sourceRepo` and `verifiedBefore` finds items by when they
448
+ were last verified instead of by commits.
449
+
388
450
  ## Targeting a different repo explicitly
389
451
 
390
452
  The repo attached to a save is normally detected from the cwd's git remote,
@@ -417,8 +479,12 @@ Call `memory_checkRepoStatus` (no arguments) once per session, the first
417
479
  time it's relevant (e.g. before your first save, or if a recall/save
418
480
  result looks unscoped when you expected repo context).
419
481
 
420
- - If the result has no `needsTeamSelection`, nothing to do — the repo is
421
- already linked (or none was detected at all).
482
+ - If the result has `linked: false` and `registered: true`, the repo exists
483
+ but no team owns it. Offer `memory_linkRepoTeam` once (`memory_listTeams`
484
+ lists the teams; mention `teamNameHint` as a guess), and drop it if the
485
+ user declines: saves still work, with Team visibility refused.
486
+ - If the result has neither `needsTeamSelection` nor `linked: false`, nothing
487
+ to do — the repo is already linked (or none was detected at all).
422
488
  - If it has `needsTeamSelection: true`, ask the user directly which team
423
489
  this repo belongs to. Offer `agentTeams` as the likely options, and
424
490
  mention `teamNameHint` as a guess if it's present — e.g. *"This repo
@@ -432,6 +498,17 @@ result looks unscoped when you expected repo context).
432
498
  lists the teams to choose from. Never guess the repo name — ask. To link
433
499
  several repos to one team, pass `repoNames` (up to 50) instead.
434
500
 
501
+ **A repo nobody has linked yet.** If the user has no team for it, or does not
502
+ want to choose one now, call `memory_registerRepo` (no arguments for the current
503
+ repo, or `repoName` as `owner/name`). It creates the repo with no team, or
504
+ returns the existing one: `{ uid, name, teamName, created }`. Items on a repo
505
+ with no team are readable by their author only, so Team visibility is refused
506
+ there (on `memory_save`, `memory_setVisibility` and when moving a Team item onto
507
+ it); use Private, or Org if the human approves sharing it, until the repo is
508
+ linked with `memory_linkRepoTeam`. `memory_listRepos` with `includeUnlinked:
509
+ true` also lists repos with no team (`teamName: null`). `memory_registerRepo`
510
+ is refused in capture mode.
511
+
435
512
  This only needs to happen once per repo per agent. Do this on explicit
436
513
  user confirmation, not a guess of your own — an SE works several client
437
514
  engagements, and guessing wrong silently mixes one client's memory into