@skedulo/memory-hub-mcp 0.2.17 → 0.2.19

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/dist/index.js CHANGED
@@ -8,10 +8,10 @@ const zod_1 = require("zod");
8
8
  const client_1 = require("./client");
9
9
  const list_repos_1 = require("./list-repos");
10
10
  const check_sources_1 = require("./check-sources");
11
+ const annotate_1 = require("./annotate");
11
12
  const source_1 = require("./source");
12
13
  const repo_context_1 = require("./repo-context");
13
14
  const task_context_1 = require("./task-context");
14
- const git_remote_1 = require("./git-remote");
15
15
  const embeddings_1 = require("./embeddings");
16
16
  const bulk_1 = require("./bulk");
17
17
  const set_visibility_1 = require("./set-visibility");
@@ -22,8 +22,10 @@ const guide_check_1 = require("./guide-check");
22
22
  const revise_1 = require("./revise");
23
23
  const similar_notice_1 = require("./similar-notice");
24
24
  const session_context_1 = require("./session-context");
25
+ const version_1 = require("./version");
25
26
  const asset_sync_1 = require("./asset-sync");
26
27
  const tags_1 = require("./tags");
28
+ const ask_prompt_1 = require("./ask-prompt");
27
29
  // The team's one deployed memory-hub function. MEMORY_HUB_FUNCTION_URL only needs to
28
30
  // be set to override this (e.g. pointing at a local `sked function dev` instance).
29
31
  const DEFAULT_FUNCTION_URL = 'https://dev-api.test.skl.io/function/memory-hub/memory-hub';
@@ -45,8 +47,16 @@ const INSTRUCTIONS = [
45
47
  'Before wrapping up a task, save anything durable with memory_save — nothing is',
46
48
  'saved automatically unless the user switched on auto-capture, and on hosts',
47
49
  'without hooks (e.g. Claude Desktop) nothing can capture it.',
50
+ 'Questions about a project or team work without a repo: find project pages with',
51
+ 'memory_list type=Wiki titlePrefix="<Project> ›", and when the hub has nothing, ask',
52
+ 'for sources and say reading them costs tokens.',
53
+ 'Every save gets a deliberate visibility (see "What to share" in memory_getSkillGuide):',
54
+ 'Team for work knowledge about a project or customer, saved with repo: "<owner/name>"',
55
+ 'even from here, passing only a repo that memory_listRepos lists; Org for customer-free',
56
+ 'knowledge about Skedulo\'s platform, products, tools or practices; Private only with a',
57
+ 'stated reason. Unsure between Org and Team: Team. Say the choice and the reason.',
48
58
  ].join(' ');
49
- const server = new mcp_js_1.McpServer({ name: 'memory-hub-mcp', version: '0.1.0' }, { instructions: INSTRUCTIONS });
59
+ const server = new mcp_js_1.McpServer({ name: 'memory-hub-mcp', version: (0, version_1.packageVersion)() }, { instructions: INSTRUCTIONS });
50
60
  // Detected from this process's own working directory, not from anything the model
51
61
  // types. Resolved lazily on the first save so startup never blocks on git or the
52
62
  // network, and degrades to undefined (an unscoped save) on any failure.
@@ -68,6 +78,9 @@ async function joinNoticeBlocks() {
68
78
  },
69
79
  ];
70
80
  }
81
+ function currentStaleness() {
82
+ return (0, annotate_1.stalenessFor)(check_sources_1.execGit, repoContext.repoName);
83
+ }
71
84
  // The save has already happened (dedup only warns), so this just makes the match visible to the agent.
72
85
  function similarNoticeBlocks(type, result) {
73
86
  const text = (0, similar_notice_1.similarNotice)(type, result);
@@ -77,18 +90,28 @@ function embeddingNoticeBlocks() {
77
90
  const text = (0, embeddings_1.embeddingNotice)();
78
91
  return text ? [{ type: 'text', text }] : [];
79
92
  }
80
- server.tool('memory_getSkillGuide', 'Get the current SE AI Memory Hub usage guide — when to recall, what to save where, sharing rules, repo linking. Call this first when the se-ai-memory-hub skill triggers.', {}, async () => {
93
+ // Claude Desktop lists MCP prompts in its menu, which is how /ask reaches people with no skills installed.
94
+ server.registerPrompt('ask', {
95
+ title: 'Ask the hub',
96
+ description: 'Answer a question from what the memory hub knows about a project, a team or the platform.',
97
+ argsSchema: { question: zod_1.z.string().min(1).describe('What you want to know.') },
98
+ }, ({ question }) => ({
99
+ messages: [{ role: 'user', content: { type: 'text', text: (0, ask_prompt_1.askPromptText)(question) } }],
100
+ }));
101
+ server.tool('memory_getSkillGuide', 'Get the current Memory Hub usage guide — when to recall, what to save where, sharing rules, repo linking. Call this first when the memory-hub skill triggers. Pass section to read one part only (for example "Stale memories"), which costs far fewer tokens.', {
102
+ section: zod_1.z.string().min(1).optional().describe('A "## " heading of the guide, matched without regard to case. Returns only that part; an unknown name returns the list of sections.'),
103
+ }, async ({ section }) => {
81
104
  // Read from disk on every call, not cached at module load — this is the whole point:
82
- // a developer's local skills/ copy is a thin stub now (see skills/se-ai-memory-hub/SKILL.md),
105
+ // a developer's local skills/ copy is a thin stub now (see skills/memory-hub/SKILL.md),
83
106
  // so the guide can only go stale here, in the one file that ships with memory-hub-mcp
84
107
  // itself and updates on every `yarn build`, not via a separate manual `cp` step.
85
108
  const guidePath = (0, path_1.join)(__dirname, '..', 'skill-guide.md');
86
109
  const guide = (0, fs_1.readFileSync)(guidePath, 'utf-8');
87
110
  // The SDK has no public tool list; if this internal moves, the check just goes silent.
88
111
  const registered = Object.keys(server._registeredTools ?? {});
89
- return { content: [{ type: 'text', text: (0, guide_check_1.staleBuildNotice)(guide, registered) + guide }] };
112
+ return { content: [{ type: 'text', text: (0, guide_check_1.staleBuildNotice)(guide, registered) + (section ? (0, guide_check_1.guideSection)(guide, section) : guide) }] };
90
113
  });
91
- server.tool('memory_recall', "Recall this developer's (or their team's) Facts, Skills, Scenarios, or Wiki pages. See memory_getSkillGuide for when to use each type.", {
114
+ server.tool('memory_recall', "Recall this developer's (or their team's) Facts, Skills, Scenarios, or Wiki pages. See memory_getSkillGuide for when to use each type. An item with a `staleness` field cites files that changed since it was verified; follow the skill guide's 'Stale memories' rules before relying on it.", {
92
115
  type: zod_1.z.enum(['Fact', 'Skill', 'Scenario', 'Wiki']),
93
116
  scope: zod_1.z.enum(['self', 'team']),
94
117
  query: zod_1.z.string().optional(),
@@ -97,10 +120,10 @@ server.tool('memory_recall', "Recall this developer's (or their team's) Facts, S
97
120
  maxCharsPerItem: zod_1.z.number().int().positive().optional().describe('Per-item content cap, default 500. Raise it to read longer items inline; prefer memory_get for a single long one.'),
98
121
  maxTotalChars: zod_1.z.number().int().positive().optional().describe('Cap across all items, default 6000.'),
99
122
  }, async (input) => {
100
- const result = await (0, recall_1.performRecall)({ client, embed: embeddings_1.embed }, input);
123
+ const result = await (0, recall_1.performRecall)({ client, embed: embeddings_1.embed, staleness: currentStaleness() }, input);
101
124
  return { content: [...embeddingNoticeBlocks(), { type: 'text', text: JSON.stringify(result) }] };
102
125
  });
103
- 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), with its lastModifiedDate to pass to memory_update as expectedLastModified. 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.", {
126
+ 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), with its lastModifiedDate to pass to memory_update as expectedLastModified. 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. An item with a `staleness` field cites files that changed since it was verified; follow the skill guide's 'Stale memories' rules before relying on it.", {
104
127
  type: zod_1.z.enum(['Fact', 'Skill', 'Scenario', 'Wiki']),
105
128
  uid: zod_1.z.string().min(1).describe('The uid from a memory_recall result.'),
106
129
  }, async (input) => {
@@ -111,7 +134,8 @@ server.tool('memory_get', "Fetch one Fact/Skill/Scenario/Wiki page in full by it
111
134
  : input.type === 'Scenario'
112
135
  ? await client.getScenario({ uid: input.uid })
113
136
  : await client.getWikiPage({ uid: input.uid });
114
- return { content: [{ type: 'text', text: JSON.stringify(result) }] };
137
+ const annotated = await (0, annotate_1.annotateItemCapped)(result, currentStaleness(), { entries: input.type === 'Wiki' });
138
+ return { content: [{ type: 'text', text: JSON.stringify(annotated) }] };
115
139
  });
116
140
  const saveShape = {
117
141
  type: zod_1.z.enum(['Fact', 'Skill', 'Scenario', 'Wiki']),
@@ -122,9 +146,10 @@ const saveShape = {
122
146
  links: zod_1.z.array(zod_1.z.string()).optional().describe('Wiki only — UIDs of other wiki pages this one depends on.'),
123
147
  tags: zod_1.z.array(zod_1.z.enum(tags_1.TAG_VALUES)).optional().describe('Fact, Skill, Wiki only.'),
124
148
  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."),
125
- 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.'),
126
- 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.'),
149
+ repo: zod_1.z.string().min(1).optional().describe('A DevRepos uid from memory_listRepos, or the owner/name of a repo memory_listRepos lists, overriding the current-directory auto-detected repo. A repo on a team you are not on is refused, never joined.'),
150
+ visibility: zod_1.z.enum(['Private', 'Team', 'Org']).optional().describe('Choose it on every save ("What to share" in memory_getSkillGuide). Team: work knowledge about a project or customer (decisions, fixes, root causes, how-tos, gotchas, conventions), on that project\'s repo. Org (everyone in the tenant): knowledge about Skedulo\'s own platform, products, tools or practices with no customer names or data, project detail, commercial terms, credentials, unpatched security detail or anything about a person. Private only with a stated reason: personal, an unverified guess, about a person, or barred by the confidentiality rules. Unsure between Org and Team: Team. Team is refused on a repo no team owns yet. Omit it in capture mode, which saves Private.'),
127
151
  source: source_1.sourceSchema.optional().describe(source_1.SOURCE_DESCRIPTION),
152
+ supersedes: zod_1.z.string().min(1).optional().describe('Fact, Skill, Wiki only — the uid of a memory of the same type that this one replaces. After saving, that memory is tagged Superseded if you may edit it (yours, or a Team item on your repo); otherwise the result says why it was not marked.'),
128
153
  };
129
154
  const saveDeps = {
130
155
  client,
@@ -132,7 +157,7 @@ const saveDeps = {
132
157
  currentRepoUid: () => repoContext.currentRepoUid(),
133
158
  resolveTaskUid: (ref, repoUid) => taskContext.resolveTaskUid(ref, repoUid),
134
159
  };
135
- server.tool('memory_save', 'Save a Fact, Skill, Scenario, or Wiki page to the SE AI Memory Hub. Written Team visibility automatically if the attached repo is already linked to a team, otherwise Private, unless visibility is passed. The result reports the saved visibility, repoId, repoName and teamName. See memory_getSkillGuide for which type to use and which fields it needs. The current repo is detected automatically unless you pass an explicit repo (from memory_listRepos) to target a different one.', saveShape, async (input) => {
160
+ server.tool('memory_save', 'Save a Fact, Skill, Scenario, or Wiki page to the Memory Hub. Decide its visibility on every save by the "What to share" rule (see visibility) and state the choice and the reason in your reply. For work knowledge about a project, pass repo as "<owner/name>" of that project\'s repo, even from Claude Desktop or another folder. Never guess a repo name, and pass only a repo that memory_listRepos lists: a repo on a team you are not on is refused, never joined. When memory_listRepos does not show the project\'s repo, or shows several candidates, ask which repo, or save Private and say why. Team with no repo, given or detected, is refused. Without visibility it is Team when the attached repo is linked to a team, otherwise Private. The result reports the saved visibility, repoId, repoName and teamName. See memory_getSkillGuide for which type to use and which fields it needs. The current repo is detected automatically unless you pass an explicit repo (from memory_listRepos) to target a different one.', saveShape, async (input) => {
136
161
  const outcome = await (0, bulk_1.performSaveItem)(saveDeps, input);
137
162
  if ('refused' in outcome) {
138
163
  return { content: [{ type: 'text', text: outcome.refused }] };
@@ -146,13 +171,13 @@ server.tool('memory_save', 'Save a Fact, Skill, Scenario, or Wiki page to the SE
146
171
  ],
147
172
  };
148
173
  });
149
- server.tool('memory_saveBatch', 'Save up to 25 Facts/Skills/Scenarios/Wiki pages in one call, each item shaped exactly like a memory_save call (same required fields, repo and visibility rules). Items are saved in order; each reports its own result or error, so one bad item does not stop the rest. Possible duplicates are listed compactly per item. Pass visibility only when the human approved sharing this batch in this conversation.', { items: zod_1.z.array(zod_1.z.object(saveShape)).min(1).max(25) }, async (input) => {
150
- const { results, similarNotices } = await (0, bulk_1.performSaveBatch)(saveDeps, input.items);
174
+ server.tool('memory_saveBatch', 'Save up to 25 Facts/Skills/Scenarios/Wiki pages in one call, each item shaped exactly like a memory_save call (same required fields, repo and visibility rules). Items are saved in order; each reports its own result or error, so one bad item does not stop the rest. Possible duplicates are listed compactly per item. Decide each item\'s visibility by the "What to share" rule, as for memory_save, and state the choices and reasons in your reply.', { items: zod_1.z.array(zod_1.z.object(saveShape)).min(1).max(25) }, async (input) => {
175
+ const { results, similarNotices, similarClosing } = await (0, bulk_1.performSaveBatch)(saveDeps, input.items);
151
176
  const similarBlock = similarNotices.length
152
177
  ? [
153
178
  {
154
179
  type: 'text',
155
- text: `Saved, but these look like memories already saved:\n${similarNotices.join('\n')}\nWhere one of yours already covers it, memory_update that uid with the merged text and memory_delete the new copy.`,
180
+ text: `Saved, but these look like memories already saved:\n${similarNotices.join('\n')}\n${similarClosing}`,
156
181
  },
157
182
  ]
158
183
  : [];
@@ -189,7 +214,7 @@ server.tool('memory_upsertPersona', "Update this developer's durable persona pro
189
214
  const result = await client.upsertPersona(input);
190
215
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
191
216
  });
192
- server.tool('memory_setVisibility', "Change who can see a Fact/Scenario/Skill/Wiki page — promote to Team, Org (everyone in the tenant) or Restricted, or demote back to Private. Pass resourceId for one item, or resourceIds (1-100 uids of one resourceType) for a batch; each item reports its own result. Only call this when a human in the conversation explicitly asks to share, promote, or un-share something — never autonomously.", {
217
+ server.tool('memory_setVisibility', "Change who can see a Fact/Scenario/Skill/Wiki page — promote to Team, Org (everyone in the tenant) or Restricted, or demote back to Private. Pass resourceId for one item, or resourceIds (1-100 uids of one resourceType) for a batch; each item reports its own result. Call it for an item you saved in this conversation to apply the \"What to share\" rule, or when a human asks to share, promote or un-share something (\"share them\" included, after the guide\'s checks). Never change other items on your own judgment.", {
193
218
  resourceType: zod_1.z.enum(['Fact', 'Scenario', 'Skill', 'Wiki']),
194
219
  resourceId: zod_1.z.string().min(1).optional().describe('One item. Give exactly one of resourceId or resourceIds.'),
195
220
  resourceIds: zod_1.z.array(zod_1.z.string().min(1)).min(1).max(100).optional().describe('A batch of up to 100 items of the same resourceType.'),
@@ -198,7 +223,7 @@ server.tool('memory_setVisibility', "Change who can see a Fact/Scenario/Skill/Wi
198
223
  const result = await (0, set_visibility_1.performSetVisibility)({ client }, input);
199
224
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
200
225
  });
201
- server.tool('memory_bulkPromoteRepoScoped', "Bulk catch-up: promotes all of this developer's existing Private Facts/Scenarios/Skills/Wiki pages whose repo is already linked to a team, to Team visibility — for content saved before repo-scoped saves started defaulting to Team automatically. Only touches your own items. Only call this when a human in the conversation explicitly asks for it — never autonomously. Re-running it will also re-promote any item you've since deliberately demoted with memory_setVisibility, so don't call it more than once without the human asking again.", {}, async () => {
226
+ server.tool('memory_bulkPromoteRepoScoped', "Bulk catch-up: promotes all of this developer's existing Private Facts/Scenarios/Skills/Wiki pages whose repo is already linked to a team, to Team visibility — for content saved before repo-scoped saves started defaulting to Team automatically. Only touches your own items. Only call this when a human in the conversation explicitly asks for it — never autonomously, and never for \"share them\", which promotes item by item after the guide\'s checks. Re-running it will also re-promote any item you've since deliberately demoted with memory_setVisibility, so don't call it more than once without the human asking again.", {}, async () => {
202
227
  const result = await client.bulkPromoteRepoScoped();
203
228
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
204
229
  });
@@ -233,7 +258,7 @@ server.tool('memory_joinTeam', "Join an EXISTING memory team by name (case-insen
233
258
  const result = await (0, teams_1.performJoinTeam)({ client }, input);
234
259
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
235
260
  });
236
- 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.", {
261
+ 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, even when sharing an item would be your call. 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.", {
237
262
  teamName: zod_1.z.string().min(1),
238
263
  agent: zod_1.z.string().min(1).describe('A DevAgents uid or an exact display name.'),
239
264
  }, async (input) => {
@@ -300,23 +325,28 @@ server.tool('memory_linkRepoTeam', "Link a repo to a team by name (existing or n
300
325
  .describe('Repo to link. Defaults to the current directory\'s repo; required when there is none. Not with repoNames.'),
301
326
  repoNames: zod_1.z.array(zod_1.z.string().min(1)).min(1).max(50).optional().describe('A batch of up to 50 repos to link to teamName.'),
302
327
  }, async (input) => {
303
- const result = await (0, bulk_1.performLinkRepoTeam)({ client, detectRepoName: git_remote_1.detectRepoName }, input);
328
+ const result = await (0, bulk_1.performLinkRepoTeam)({ client, detectRepoName: repoContext.repoName }, input);
304
329
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
305
330
  });
306
- 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.", {
331
+ 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 until memory_linkRepoTeam links it; save them Private meanwhile and say why.", {
307
332
  repoName: zod_1.z.string().min(1).optional().describe("owner/name. Defaults to the current directory's repo; required when there is none."),
308
333
  }, async (input) => {
309
- const result = await (0, list_repos_1.performRegisterRepo)({ client, detectRepoName: git_remote_1.detectRepoName }, input);
334
+ const result = await (0, list_repos_1.performRegisterRepo)({ client, detectRepoName: repoContext.repoName }, input);
310
335
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
311
336
  });
312
337
  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.", {
313
338
  repo: zod_1.z.string().min(1).optional().describe("owner/name. Defaults to the current directory's repo."),
314
339
  }, async (input) => {
315
- const result = await (0, check_sources_1.performCheckSources)({ client, detectRepoName: git_remote_1.detectRepoName }, input);
340
+ const result = await (0, check_sources_1.performCheckSources)({ client, detectRepoName: repoContext.repoName }, input);
316
341
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
317
342
  });
318
343
  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 () => {
319
- const context = await (0, session_context_1.buildSessionContext)({ client, currentRepoUid: repoContext.currentRepoUid });
344
+ const context = await (0, session_context_1.buildSessionContext)({
345
+ client,
346
+ currentRepoUid: repoContext.currentRepoUid,
347
+ staleness: currentStaleness(),
348
+ serverVersion: (0, version_1.packageVersion)(),
349
+ });
320
350
  return { content: [...embeddingNoticeBlocks(), { type: 'text', text: JSON.stringify(context) }] };
321
351
  });
322
352
  (0, asset_sync_1.refreshInstalledAssets)();
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.performRegisterRepo = exports.listReposForTools = void 0;
3
+ exports.performRegisterRepo = exports.collectRepos = exports.listReposForTools = void 0;
4
4
  const capture_1 = require("./capture");
5
5
  // Fans out listTeams() -> listRepos() per team and flattens into one list
6
6
  // labeled with each repo's team name — the small, infrequent list a caller
@@ -10,6 +10,11 @@ const capture_1 = require("./capture");
10
10
  // still useful for picking a repo. includeUnlinked adds one extra call for
11
11
  // repos no team owns, which also works for a user on no teams.
12
12
  async function listReposForTools(client, query, includeUnlinked = false) {
13
+ const { repos } = await collectRepos(client, query, includeUnlinked);
14
+ return repos;
15
+ }
16
+ exports.listReposForTools = listReposForTools;
17
+ async function collectRepos(client, query, includeUnlinked = false) {
13
18
  const { teams } = await client.listTeams();
14
19
  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
20
  const unlinked = includeUnlinked
@@ -21,13 +26,14 @@ async function listReposForTools(client, query, includeUnlinked = false) {
21
26
  const allRepos = settled
22
27
  .filter((result) => result.status === 'fulfilled')
23
28
  .flatMap((result) => result.value);
29
+ const complete = settled.every((result) => result.status === 'fulfilled');
24
30
  if (!query) {
25
- return allRepos;
31
+ return { repos: allRepos, complete };
26
32
  }
27
33
  const normalizedQuery = query.toLowerCase();
28
- return allRepos.filter((repo) => repo.name.toLowerCase().includes(normalizedQuery));
34
+ return { repos: allRepos.filter((repo) => repo.name.toLowerCase().includes(normalizedQuery)), complete };
29
35
  }
30
- exports.listReposForTools = listReposForTools;
36
+ exports.collectRepos = collectRepos;
31
37
  function performRegisterRepo(deps, input) {
32
38
  if ((0, capture_1.isCaptureMode)()) {
33
39
  throw new Error('memory_registerRepo is not allowed in capture mode.');
@@ -0,0 +1,219 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runMigratePlugin = exports.migratePlugin = void 0;
4
+ const fs_1 = require("fs");
5
+ const path_1 = require("path");
6
+ const setup_1 = require("./setup");
7
+ const has = (value, key) => typeof value === 'object' && value !== null && Object.prototype.hasOwnProperty.call(value, key);
8
+ const message = (error) => (error instanceof Error ? error.message : String(error));
9
+ function parseObject(output) {
10
+ const start = output.indexOf('{');
11
+ const end = output.lastIndexOf('}');
12
+ if (start < 0 || end < start)
13
+ return undefined;
14
+ try {
15
+ return JSON.parse(output.slice(start, end + 1));
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ // readJson reads a torn or hand-broken file as {}, and writing that back would wipe the user's settings.
22
+ function readStrict(path) {
23
+ if (!(0, fs_1.existsSync)(path))
24
+ return {};
25
+ try {
26
+ const value = JSON.parse((0, fs_1.readFileSync)(path, 'utf8'));
27
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined;
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ }
33
+ function updateSettings(path, change) {
34
+ const settings = readStrict(path);
35
+ if (!settings)
36
+ return false;
37
+ change(settings);
38
+ (0, setup_1.writeJson)(path, settings);
39
+ return true;
40
+ }
41
+ function pick(source, keys) {
42
+ return Object.fromEntries(keys.filter((key) => has(source, key)).map((key) => [key, JSON.parse(JSON.stringify(source[key]))]));
43
+ }
44
+ function putBack(settings, field, keys, before) {
45
+ for (const key of keys) {
46
+ if (has(before, key))
47
+ (settings[field] ||= {})[key] = before[key];
48
+ else if (has(settings[field], key))
49
+ delete settings[field][key];
50
+ }
51
+ }
52
+ function logLine(status, reason) {
53
+ return `${new Date().toISOString()} ${status} ${reason.replace(/\s+/g, ' ')}`;
54
+ }
55
+ function migratePlugin(deps) {
56
+ const { run, configDir } = deps;
57
+ const finish = (status, reason) => {
58
+ deps.log(logLine(status, reason));
59
+ return { status, reason };
60
+ };
61
+ const settingsPath = (0, path_1.join)(configDir, 'settings.json');
62
+ const installedPath = (0, path_1.join)(configDir, 'plugins', 'installed_plugins.json');
63
+ const knownPath = (0, path_1.join)(configDir, 'plugins', 'known_marketplaces.json');
64
+ const retireOld = (notes) => {
65
+ let left;
66
+ try {
67
+ if (readStrict(settingsPath)?.enabledPlugins?.[setup_1.LEGACY_PLUGIN_ID] === true) {
68
+ const disabled = run(['plugin', 'disable', setup_1.LEGACY_PLUGIN_ID]);
69
+ if (disabled.status !== 0)
70
+ left = `disable failed (${(0, setup_1.lastLine)(disabled.output)})`;
71
+ }
72
+ if (left === undefined) {
73
+ const removed = run(['plugin', 'marketplace', 'remove', setup_1.LEGACY_MARKETPLACE_NAME]);
74
+ if (removed.status !== 0)
75
+ left = (0, setup_1.lastLine)(removed.output);
76
+ }
77
+ }
78
+ catch (error) {
79
+ left = message(error);
80
+ }
81
+ if (left === undefined)
82
+ return;
83
+ notes.push(`old marketplace not removed: ${left}`);
84
+ try {
85
+ const turnedOff = updateSettings(settingsPath, (current) => {
86
+ if (current.enabledPlugins?.[setup_1.LEGACY_PLUGIN_ID] === true)
87
+ current.enabledPlugins[setup_1.LEGACY_PLUGIN_ID] = false;
88
+ });
89
+ if (!turnedOff)
90
+ notes.push(`${setup_1.LEGACY_PLUGIN_ID} still enabled, settings unreadable`);
91
+ }
92
+ catch (error) {
93
+ notes.push(`${setup_1.LEGACY_PLUGIN_ID} still enabled (${message(error)})`);
94
+ }
95
+ };
96
+ const withNotes = (reason, notes) => (notes.length > 0 ? `${reason} (${notes.join('; ')})` : reason);
97
+ const plugins = (0, setup_1.readJson)(installedPath).plugins || {};
98
+ if (!has(plugins, setup_1.LEGACY_PLUGIN_ID))
99
+ return finish('skipped', has(plugins, setup_1.PLUGIN_ID) ? 'already moved' : 'not installed');
100
+ const settings = readStrict(settingsPath);
101
+ if (!settings)
102
+ return finish('skipped', 'settings unreadable');
103
+ const records = Array.isArray(plugins[setup_1.LEGACY_PLUGIN_ID]) ? plugins[setup_1.LEGACY_PLUGIN_ID] : [];
104
+ const userScopeOnly = records.length > 0 && records.every((record) => record?.scope === 'user');
105
+ if (has(plugins, setup_1.PLUGIN_ID)) {
106
+ if (!userScopeOnly)
107
+ return finish('skipped', 'not user scope');
108
+ // A move cut off after the new install leaves both IDs loaded until the old marketplace goes.
109
+ const known = readStrict(knownPath);
110
+ if (!known)
111
+ return finish('skipped', 'marketplaces unreadable');
112
+ if (!has(known, setup_1.LEGACY_MARKETPLACE_NAME) || !(0, setup_1.isHubSource)(known[setup_1.MARKETPLACE_NAME]?.source))
113
+ return finish('skipped', 'already moved');
114
+ const newRecords = Array.isArray(plugins[setup_1.PLUGIN_ID]) ? plugins[setup_1.PLUGIN_ID] : [];
115
+ const newActive = newRecords.some((record) => record?.scope === 'user') && settings.enabledPlugins?.[setup_1.PLUGIN_ID] === true;
116
+ if (!newActive)
117
+ return finish('skipped', 'new install not active');
118
+ const notes = [];
119
+ retireOld(notes);
120
+ return finish('moved', withNotes('retired the old install', notes));
121
+ }
122
+ if (settings.enabledPlugins?.[setup_1.LEGACY_PLUGIN_ID] !== true)
123
+ return finish('skipped', 'disabled');
124
+ if (!userScopeOnly)
125
+ return finish('skipped', 'not user scope');
126
+ const repoCopy = (0, path_1.join)(configDir, 'plugins', 'marketplaces', setup_1.LEGACY_MARKETPLACE_NAME, '.claude-plugin', 'marketplace.json');
127
+ if ((0, setup_1.readJson)(repoCopy).name !== setup_1.MARKETPLACE_NAME)
128
+ return finish('skipped', 'not released yet');
129
+ const declared = settings.extraKnownMarketplaces?.[setup_1.LEGACY_MARKETPLACE_NAME];
130
+ if (!(0, setup_1.isHubSource)(declared?.source))
131
+ return finish('skipped', 'old marketplace not in settings');
132
+ const configured = run(['plugin', 'configure', '--json', setup_1.LEGACY_PLUGIN_ID]);
133
+ const options = configured.status === 0 ? parseObject(configured.output) : undefined;
134
+ if (!options || !Array.isArray(options.configured))
135
+ return finish('failed', 'could not read the plugin options, nothing changed');
136
+ const settingsToken = settings.env?.MEMORY_HUB_MCP_TOKEN;
137
+ const hasSettingsToken = typeof settingsToken === 'string' && settingsToken.trim() !== '';
138
+ if (options.configured.includes('token') && !hasSettingsToken)
139
+ return finish('skipped', 'pasted token');
140
+ if (run(['plugin', 'marketplace', 'update', setup_1.LEGACY_MARKETPLACE_NAME]).status !== 0)
141
+ return finish('skipped', 'cannot reach the marketplace');
142
+ const knownAtStart = readStrict(knownPath);
143
+ if (!knownAtStart || !has(knownAtStart, setup_1.LEGACY_MARKETPLACE_NAME))
144
+ return finish('skipped', 'marketplaces unreadable');
145
+ const capture = options.inputs?.capture === true ? ['--config', 'capture=true'] : [];
146
+ const ref = declared.source.ref || setup_1.MARKETPLACE_REF;
147
+ const knownBefore = new Set(Object.keys(knownAtStart));
148
+ const marketplacesBefore = pick(settings.extraKnownMarketplaces, [setup_1.MARKETPLACE_NAME]);
149
+ const enabledBefore = pick(settings.enabledPlugins, [setup_1.PLUGIN_ID]);
150
+ const addAndInstall = () => {
151
+ const added = run(['plugin', 'marketplace', 'add', `${setup_1.MARKETPLACE_GIT_URL}#${ref}`]);
152
+ if (added.status !== 0)
153
+ return `add failed (${(0, setup_1.lastLine)(added.output)})`;
154
+ if (!(0, setup_1.isHubSource)((0, setup_1.readJson)(knownPath)[setup_1.MARKETPLACE_NAME]?.source))
155
+ return `add failed (the repo did not register as ${setup_1.MARKETPLACE_NAME})`;
156
+ const installed = run(['plugin', 'install', setup_1.PLUGIN_ID, ...capture]);
157
+ if (installed.status !== 0)
158
+ return `install failed (${(0, setup_1.lastLine)(installed.output)})`;
159
+ if ((0, setup_1.installedPluginId)(installedPath) !== setup_1.PLUGIN_ID)
160
+ return `install failed (claude did not list ${setup_1.PLUGIN_ID})`;
161
+ return undefined;
162
+ };
163
+ const undoNew = () => {
164
+ const known = (0, setup_1.readJson)(knownPath);
165
+ for (const name of Object.keys(known)) {
166
+ if (name !== setup_1.LEGACY_MARKETPLACE_NAME && !knownBefore.has(name) && (0, setup_1.isHubSource)(known[name]?.source))
167
+ run(['plugin', 'marketplace', 'remove', name]);
168
+ }
169
+ const restored = updateSettings(settingsPath, (current) => {
170
+ putBack(current, 'extraKnownMarketplaces', [setup_1.MARKETPLACE_NAME], marketplacesBefore);
171
+ putBack(current, 'enabledPlugins', [setup_1.PLUGIN_ID], enabledBefore);
172
+ });
173
+ return restored ? `${setup_1.LEGACY_PLUGIN_ID} untouched` : `${setup_1.LEGACY_PLUGIN_ID} untouched, settings unreadable and left as they are`;
174
+ };
175
+ let failure;
176
+ try {
177
+ failure = addAndInstall();
178
+ }
179
+ catch (error) {
180
+ failure = `add or install failed (${message(error)})`;
181
+ }
182
+ if (failure !== undefined) {
183
+ let outcome;
184
+ try {
185
+ outcome = undoNew();
186
+ }
187
+ catch (error) {
188
+ outcome = `undoing the new marketplace failed (${message(error)})`;
189
+ }
190
+ return finish('failed', `${failure}; ${outcome}`);
191
+ }
192
+ const notes = [];
193
+ retireOld(notes);
194
+ if (declared.autoUpdate === true) {
195
+ try {
196
+ const set = updateSettings(settingsPath, (current) => {
197
+ const known = (current.extraKnownMarketplaces ||= {});
198
+ known[setup_1.MARKETPLACE_NAME] = { source: { source: 'git', url: setup_1.MARKETPLACE_GIT_URL, ref }, ...known[setup_1.MARKETPLACE_NAME], autoUpdate: true };
199
+ });
200
+ if (!set)
201
+ notes.push('auto-update not carried over, settings unreadable');
202
+ }
203
+ catch (error) {
204
+ notes.push(`auto-update not carried over (${message(error)})`);
205
+ }
206
+ }
207
+ return finish('moved', withNotes(`${setup_1.LEGACY_PLUGIN_ID} to ${setup_1.PLUGIN_ID}, loads at the next session`, notes));
208
+ }
209
+ exports.migratePlugin = migratePlugin;
210
+ async function runMigratePlugin(_argv) {
211
+ const log = (line) => console.log(line);
212
+ const run = (0, setup_1.claudeRunner)();
213
+ if (!run) {
214
+ log(logLine('skipped', 'claude CLI not on PATH'));
215
+ return 0;
216
+ }
217
+ return migratePlugin({ run, configDir: (0, setup_1.claudeConfigDir)(), log }).status === 'failed' ? 1 : 0;
218
+ }
219
+ exports.runMigratePlugin = runMigratePlugin;
package/dist/recall.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.performRecall = void 0;
4
+ const annotate_1 = require("./annotate");
4
5
  // In-band, not just a JSON field: an agent skimming the text must still see the cut and the uid.
5
6
  function markCuts(type, listKey, textKey, result) {
6
7
  const items = result?.[listKey];
@@ -25,31 +26,31 @@ function markCuts(type, listKey, textKey, result) {
25
26
  // recallWiki tool handlers — see save.ts's comment for why (index.ts's module-scope
26
27
  // side effects make it untestable directly).
27
28
  async function performRecall(deps, input) {
28
- const { client, embed } = deps;
29
+ const { client, embed, staleness } = deps;
29
30
  const queryEmbedding = input.query ? await embed(input.query).catch(() => undefined) : undefined;
30
31
  const caps = { maxCharsPerItem: input.maxCharsPerItem, maxTotalChars: input.maxTotalChars };
31
32
  switch (input.type) {
32
33
  case 'Fact':
33
- return markCuts('Fact', 'facts', 'content', await client.recall({
34
+ return markCuts('Fact', 'facts', 'content', await (0, annotate_1.annotateListCapped)(await client.recall({
34
35
  scope: input.scope,
35
36
  query: input.query,
36
37
  tags: input.tags,
37
38
  externalRef: input.externalRef,
38
39
  queryEmbedding,
39
40
  ...caps,
40
- }));
41
+ }), 'facts', staleness));
41
42
  case 'Skill':
42
- return markCuts('Skill', 'skills', 'content', await client.listSkills({ scope: input.scope, query: input.query, queryEmbedding, ...caps }));
43
+ return markCuts('Skill', 'skills', 'content', await (0, annotate_1.annotateListCapped)(await client.listSkills({ scope: input.scope, query: input.query, queryEmbedding, ...caps }), 'skills', staleness));
43
44
  case 'Scenario':
44
- return markCuts('Scenario', 'scenarios', 'summary', await client.recallScenarios({
45
+ return markCuts('Scenario', 'scenarios', 'summary', await (0, annotate_1.annotateListCapped)(await client.recallScenarios({
45
46
  scope: input.scope,
46
47
  query: input.query,
47
48
  externalRef: input.externalRef,
48
49
  queryEmbedding,
49
50
  ...caps,
50
- }));
51
+ }), 'scenarios', staleness));
51
52
  case 'Wiki':
52
- return markCuts('Wiki', 'pages', 'content', await client.recallWiki({ scope: input.scope, query: input.query, queryEmbedding, ...caps }));
53
+ return markCuts('Wiki', 'pages', 'content', await (0, annotate_1.annotateListCapped)(await client.recallWiki({ scope: input.scope, query: input.query, queryEmbedding, ...caps }), 'pages', staleness));
53
54
  }
54
55
  }
55
56
  exports.performRecall = performRecall;
@@ -39,13 +39,18 @@ function createRepoContext(client, detectName = git_remote_1.detectRepoName, det
39
39
  let cached;
40
40
  let inFlight;
41
41
  let joinNoticeTaken = false;
42
+ let detected;
43
+ const repoName = () => {
44
+ detected ??= { name: detectName() };
45
+ return detected.name;
46
+ };
42
47
  const resolve = () => {
43
48
  if (cached !== undefined) {
44
49
  return Promise.resolve(cached);
45
50
  }
46
51
  if (!inFlight) {
47
52
  inFlight = (async () => {
48
- const name = detectName();
53
+ const name = repoName();
49
54
  if (!name) {
50
55
  return NO_REPO;
51
56
  }
@@ -85,6 +90,7 @@ function createRepoContext(client, detectName = git_remote_1.detectRepoName, det
85
90
  });
86
91
  };
87
92
  return {
93
+ repoName,
88
94
  async currentRepoUid() {
89
95
  const status = await resolve();
90
96
  return status.uid;