@skedulo/memory-hub-mcp 0.2.17 → 0.2.18

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");
@@ -24,6 +24,7 @@ const similar_notice_1 = require("./similar-notice");
24
24
  const session_context_1 = require("./session-context");
25
25
  const asset_sync_1 = require("./asset-sync");
26
26
  const tags_1 = require("./tags");
27
+ const ask_prompt_1 = require("./ask-prompt");
27
28
  // The team's one deployed memory-hub function. MEMORY_HUB_FUNCTION_URL only needs to
28
29
  // be set to override this (e.g. pointing at a local `sked function dev` instance).
29
30
  const DEFAULT_FUNCTION_URL = 'https://dev-api.test.skl.io/function/memory-hub/memory-hub';
@@ -45,6 +46,14 @@ const INSTRUCTIONS = [
45
46
  'Before wrapping up a task, save anything durable with memory_save — nothing is',
46
47
  'saved automatically unless the user switched on auto-capture, and on hosts',
47
48
  'without hooks (e.g. Claude Desktop) nothing can capture it.',
49
+ 'Questions about a project or team work without a repo: find project pages with',
50
+ 'memory_list type=Wiki titlePrefix="<Project> ›", and when the hub has nothing, ask',
51
+ 'for sources and say reading them costs tokens.',
52
+ 'Every save gets a deliberate visibility (see "What to share" in memory_getSkillGuide):',
53
+ 'Team for work knowledge about a project or customer, saved with repo: "<owner/name>"',
54
+ 'even from here, passing only a repo that memory_listRepos lists; Org for customer-free',
55
+ 'knowledge about Skedulo\'s platform, products, tools or practices; Private only with a',
56
+ 'stated reason. Unsure between Org and Team: Team. Say the choice and the reason.',
48
57
  ].join(' ');
49
58
  const server = new mcp_js_1.McpServer({ name: 'memory-hub-mcp', version: '0.1.0' }, { instructions: INSTRUCTIONS });
50
59
  // Detected from this process's own working directory, not from anything the model
@@ -68,6 +77,9 @@ async function joinNoticeBlocks() {
68
77
  },
69
78
  ];
70
79
  }
80
+ function currentStaleness() {
81
+ return (0, annotate_1.stalenessFor)(check_sources_1.execGit, repoContext.repoName);
82
+ }
71
83
  // The save has already happened (dedup only warns), so this just makes the match visible to the agent.
72
84
  function similarNoticeBlocks(type, result) {
73
85
  const text = (0, similar_notice_1.similarNotice)(type, result);
@@ -77,18 +89,28 @@ function embeddingNoticeBlocks() {
77
89
  const text = (0, embeddings_1.embeddingNotice)();
78
90
  return text ? [{ type: 'text', text }] : [];
79
91
  }
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 () => {
92
+ // Claude Desktop lists MCP prompts in its menu, which is how /ask reaches people with no skills installed.
93
+ server.registerPrompt('ask', {
94
+ title: 'Ask the hub',
95
+ description: 'Answer a question from what the memory hub knows about a project, a team or the platform.',
96
+ argsSchema: { question: zod_1.z.string().min(1).describe('What you want to know.') },
97
+ }, ({ question }) => ({
98
+ messages: [{ role: 'user', content: { type: 'text', text: (0, ask_prompt_1.askPromptText)(question) } }],
99
+ }));
100
+ 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.', {
101
+ 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.'),
102
+ }, async ({ section }) => {
81
103
  // 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),
104
+ // a developer's local skills/ copy is a thin stub now (see skills/memory-hub/SKILL.md),
83
105
  // so the guide can only go stale here, in the one file that ships with memory-hub-mcp
84
106
  // itself and updates on every `yarn build`, not via a separate manual `cp` step.
85
107
  const guidePath = (0, path_1.join)(__dirname, '..', 'skill-guide.md');
86
108
  const guide = (0, fs_1.readFileSync)(guidePath, 'utf-8');
87
109
  // The SDK has no public tool list; if this internal moves, the check just goes silent.
88
110
  const registered = Object.keys(server._registeredTools ?? {});
89
- return { content: [{ type: 'text', text: (0, guide_check_1.staleBuildNotice)(guide, registered) + guide }] };
111
+ return { content: [{ type: 'text', text: (0, guide_check_1.staleBuildNotice)(guide, registered) + (section ? (0, guide_check_1.guideSection)(guide, section) : guide) }] };
90
112
  });
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.", {
113
+ 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
114
  type: zod_1.z.enum(['Fact', 'Skill', 'Scenario', 'Wiki']),
93
115
  scope: zod_1.z.enum(['self', 'team']),
94
116
  query: zod_1.z.string().optional(),
@@ -97,10 +119,10 @@ server.tool('memory_recall', "Recall this developer's (or their team's) Facts, S
97
119
  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
120
  maxTotalChars: zod_1.z.number().int().positive().optional().describe('Cap across all items, default 6000.'),
99
121
  }, async (input) => {
100
- const result = await (0, recall_1.performRecall)({ client, embed: embeddings_1.embed }, input);
122
+ const result = await (0, recall_1.performRecall)({ client, embed: embeddings_1.embed, staleness: currentStaleness() }, input);
101
123
  return { content: [...embeddingNoticeBlocks(), { type: 'text', text: JSON.stringify(result) }] };
102
124
  });
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.", {
125
+ 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
126
  type: zod_1.z.enum(['Fact', 'Skill', 'Scenario', 'Wiki']),
105
127
  uid: zod_1.z.string().min(1).describe('The uid from a memory_recall result.'),
106
128
  }, async (input) => {
@@ -111,7 +133,8 @@ server.tool('memory_get', "Fetch one Fact/Skill/Scenario/Wiki page in full by it
111
133
  : input.type === 'Scenario'
112
134
  ? await client.getScenario({ uid: input.uid })
113
135
  : await client.getWikiPage({ uid: input.uid });
114
- return { content: [{ type: 'text', text: JSON.stringify(result) }] };
136
+ const annotated = await (0, annotate_1.annotateItemCapped)(result, currentStaleness(), { entries: input.type === 'Wiki' });
137
+ return { content: [{ type: 'text', text: JSON.stringify(annotated) }] };
115
138
  });
116
139
  const saveShape = {
117
140
  type: zod_1.z.enum(['Fact', 'Skill', 'Scenario', 'Wiki']),
@@ -122,9 +145,10 @@ const saveShape = {
122
145
  links: zod_1.z.array(zod_1.z.string()).optional().describe('Wiki only — UIDs of other wiki pages this one depends on.'),
123
146
  tags: zod_1.z.array(zod_1.z.enum(tags_1.TAG_VALUES)).optional().describe('Fact, Skill, Wiki only.'),
124
147
  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.'),
148
+ 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.'),
149
+ 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
150
  source: source_1.sourceSchema.optional().describe(source_1.SOURCE_DESCRIPTION),
151
+ 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
152
  };
129
153
  const saveDeps = {
130
154
  client,
@@ -132,7 +156,7 @@ const saveDeps = {
132
156
  currentRepoUid: () => repoContext.currentRepoUid(),
133
157
  resolveTaskUid: (ref, repoUid) => taskContext.resolveTaskUid(ref, repoUid),
134
158
  };
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) => {
159
+ 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
160
  const outcome = await (0, bulk_1.performSaveItem)(saveDeps, input);
137
161
  if ('refused' in outcome) {
138
162
  return { content: [{ type: 'text', text: outcome.refused }] };
@@ -146,13 +170,13 @@ server.tool('memory_save', 'Save a Fact, Skill, Scenario, or Wiki page to the SE
146
170
  ],
147
171
  };
148
172
  });
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);
173
+ 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) => {
174
+ const { results, similarNotices, similarClosing } = await (0, bulk_1.performSaveBatch)(saveDeps, input.items);
151
175
  const similarBlock = similarNotices.length
152
176
  ? [
153
177
  {
154
178
  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.`,
179
+ text: `Saved, but these look like memories already saved:\n${similarNotices.join('\n')}\n${similarClosing}`,
156
180
  },
157
181
  ]
158
182
  : [];
@@ -189,7 +213,7 @@ server.tool('memory_upsertPersona', "Update this developer's durable persona pro
189
213
  const result = await client.upsertPersona(input);
190
214
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
191
215
  });
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.", {
216
+ 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
217
  resourceType: zod_1.z.enum(['Fact', 'Scenario', 'Skill', 'Wiki']),
194
218
  resourceId: zod_1.z.string().min(1).optional().describe('One item. Give exactly one of resourceId or resourceIds.'),
195
219
  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 +222,7 @@ server.tool('memory_setVisibility', "Change who can see a Fact/Scenario/Skill/Wi
198
222
  const result = await (0, set_visibility_1.performSetVisibility)({ client }, input);
199
223
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
200
224
  });
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 () => {
225
+ 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
226
  const result = await client.bulkPromoteRepoScoped();
203
227
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
204
228
  });
@@ -233,7 +257,7 @@ server.tool('memory_joinTeam', "Join an EXISTING memory team by name (case-insen
233
257
  const result = await (0, teams_1.performJoinTeam)({ client }, input);
234
258
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
235
259
  });
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.", {
260
+ 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
261
  teamName: zod_1.z.string().min(1),
238
262
  agent: zod_1.z.string().min(1).describe('A DevAgents uid or an exact display name.'),
239
263
  }, async (input) => {
@@ -300,23 +324,23 @@ server.tool('memory_linkRepoTeam', "Link a repo to a team by name (existing or n
300
324
  .describe('Repo to link. Defaults to the current directory\'s repo; required when there is none. Not with repoNames.'),
301
325
  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
326
  }, async (input) => {
303
- const result = await (0, bulk_1.performLinkRepoTeam)({ client, detectRepoName: git_remote_1.detectRepoName }, input);
327
+ const result = await (0, bulk_1.performLinkRepoTeam)({ client, detectRepoName: repoContext.repoName }, input);
304
328
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
305
329
  });
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.", {
330
+ 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
331
  repoName: zod_1.z.string().min(1).optional().describe("owner/name. Defaults to the current directory's repo; required when there is none."),
308
332
  }, async (input) => {
309
- const result = await (0, list_repos_1.performRegisterRepo)({ client, detectRepoName: git_remote_1.detectRepoName }, input);
333
+ const result = await (0, list_repos_1.performRegisterRepo)({ client, detectRepoName: repoContext.repoName }, input);
310
334
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
311
335
  });
312
336
  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
337
  repo: zod_1.z.string().min(1).optional().describe("owner/name. Defaults to the current directory's repo."),
314
338
  }, async (input) => {
315
- const result = await (0, check_sources_1.performCheckSources)({ client, detectRepoName: git_remote_1.detectRepoName }, input);
339
+ const result = await (0, check_sources_1.performCheckSources)({ client, detectRepoName: repoContext.repoName }, input);
316
340
  return { content: [{ type: 'text', text: JSON.stringify(result) }] };
317
341
  });
318
342
  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 });
343
+ const context = await (0, session_context_1.buildSessionContext)({ client, currentRepoUid: repoContext.currentRepoUid, staleness: currentStaleness() });
320
344
  return { content: [...embeddingNoticeBlocks(), { type: 'text', text: JSON.stringify(context) }] };
321
345
  });
322
346
  (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.');
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;
package/dist/save.js CHANGED
@@ -1,23 +1,91 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.performSave = exports.validateRepoArg = void 0;
3
+ exports.performSave = exports.validateRepoArg = exports.TEAM_NEEDS_REPO = void 0;
4
4
  const source_1 = require("./source");
5
+ const capture_1 = require("./capture");
6
+ const list_repos_1 = require("./list-repos");
5
7
  const UID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
6
8
  const OWNER_NAME_PATTERN = /^[^/\s]+\/[^/\s]+$/;
9
+ exports.TEAM_NEEDS_REPO = "Team needs the project's repo: pass repo as owner/name, or save Private and say why.";
10
+ const REPO_LIST_FAILED = 'Could not check your repos right now; save Private without the repo and say why, or try again.';
11
+ // resolveRepo joins the caller to the repo's team, so a name is matched against the caller's own list instead.
7
12
  async function validateRepoArg(client, repo) {
8
13
  if (UID_PATTERN.test(repo)) {
9
14
  return repo;
10
15
  }
11
16
  if (OWNER_NAME_PATTERN.test(repo)) {
12
- const resolved = await client.resolveRepo({ name: repo });
13
- if (resolved.uid) {
14
- return resolved.uid;
17
+ const wanted = repo.toLowerCase();
18
+ let found;
19
+ try {
20
+ found = await (0, list_repos_1.collectRepos)(client, undefined, true);
15
21
  }
16
- throw new Error(`repo must be a uid from memory_listRepos; "${repo}" is not a registered repo`);
22
+ catch {
23
+ throw new Error(REPO_LIST_FAILED);
24
+ }
25
+ const listed = found.repos.find((candidate) => candidate.name.toLowerCase() === wanted);
26
+ if (listed) {
27
+ return listed.uid;
28
+ }
29
+ if (!found.complete) {
30
+ throw new Error(REPO_LIST_FAILED);
31
+ }
32
+ throw new Error(`No repo named ${repo} is registered in the hub, or you are not on its team. Check the name; if it is right, ask the person whether to join that team, or save Private without the repo and say why.`);
17
33
  }
18
34
  throw new Error(`repo must be a uid from memory_listRepos, got "${repo}"`);
19
35
  }
20
36
  exports.validateRepoArg = validateRepoArg;
37
+ function assertTeamHasRepo(visibility, repo) {
38
+ if (visibility === 'Team' && !repo) {
39
+ throw new Error(exports.TEAM_NEEDS_REPO);
40
+ }
41
+ }
42
+ const SUPERSEDED = 'Superseded';
43
+ function errorMessage(err) {
44
+ return err instanceof Error ? err.message : String(err);
45
+ }
46
+ async function readTags(client, type, uid) {
47
+ const current = type === 'Fact' ? await client.getFact({ uid }) : type === 'Skill' ? await client.getSkill({ uid }) : await client.getWikiPage({ uid });
48
+ return { tags: current.tags ?? [], lastModifiedDate: current.lastModifiedDate };
49
+ }
50
+ function writeTags(client, type, body) {
51
+ return type === 'Fact' ? client.updateFact(body) : type === 'Skill' ? client.updateSkill(body) : client.updateWikiPage(body);
52
+ }
53
+ async function markSuperseded(client, type, uid) {
54
+ try {
55
+ for (let attempt = 0;; attempt++) {
56
+ const { tags, lastModifiedDate } = await readTags(client, type, uid);
57
+ if (tags.includes(SUPERSEDED)) {
58
+ return { supersededMarked: true };
59
+ }
60
+ try {
61
+ await writeTags(client, type, { uid, tags: [...tags, SUPERSEDED], expectedLastModified: lastModifiedDate });
62
+ return { supersededMarked: true };
63
+ }
64
+ catch (err) {
65
+ if (attempt === 0 && errorMessage(err).startsWith('Conflict')) {
66
+ continue;
67
+ }
68
+ throw err;
69
+ }
70
+ }
71
+ }
72
+ catch (err) {
73
+ const reason = errorMessage(err);
74
+ const why = reason.startsWith('Not found')
75
+ ? `you cannot edit ${type} ${uid}, or it no longer exists`
76
+ : reason.startsWith('Conflict')
77
+ ? `${type} ${uid} kept changing while it was being marked`
78
+ : reason;
79
+ return {
80
+ supersededMarked: false,
81
+ supersededNote: `The new memory is saved, but ${type} ${uid} was not marked Superseded: ${why}. Ask its owner to tag it Superseded, or cite it in the new memory.`,
82
+ };
83
+ }
84
+ }
85
+ async function withSupersedes(saved, client, type, supersedes) {
86
+ const result = await saved;
87
+ return supersedes ? { ...result, ...(await markSuperseded(client, type, supersedes)) } : result;
88
+ }
21
89
  // Extracted from four near-identical memory_saveX tool handlers so the per-type
22
90
  // dispatch logic — which fields are required, what gets embedded, which client
23
91
  // method is called — is unit-testable. index.ts's module-scope side effects
@@ -26,7 +94,15 @@ exports.validateRepoArg = validateRepoArg;
26
94
  async function performSave(deps, input) {
27
95
  const { client, embed, currentRepoUid, resolveTaskUid } = deps;
28
96
  (0, source_1.assertSource)(input.source);
29
- const explicitRepo = () => (input.repo === undefined ? undefined : validateRepoArg(client, input.repo));
97
+ const supersedes = (0, capture_1.isCaptureMode)() ? undefined : input.supersedes;
98
+ if (supersedes && input.type === 'Scenario') {
99
+ throw new Error('supersedes applies to a Fact, Skill or Wiki page; a Scenario has no tags to mark Superseded.');
100
+ }
101
+ const resolveRepo = async () => {
102
+ const repo = (input.repo === undefined ? undefined : await validateRepoArg(client, input.repo)) ?? (await currentRepoUid());
103
+ assertTeamHasRepo(input.visibility, repo);
104
+ return repo;
105
+ };
30
106
  // Required-field checks run BEFORE any repo resolution/network call — the old
31
107
  // per-type tools got this for free from Zod (`content: z.string()`, not
32
108
  // `.optional()`), which the consolidated schema can't do since requiredness is
@@ -37,24 +113,24 @@ async function performSave(deps, input) {
37
113
  if (!input.content) {
38
114
  throw new Error("content is required when type is 'Fact'");
39
115
  }
40
- const repo = (await explicitRepo()) ?? (await currentRepoUid());
116
+ const repo = await resolveRepo();
41
117
  const devTaskId = input.externalRef ? await resolveTaskUid(input.externalRef, repo ?? null) : undefined;
42
118
  const embedding = await embed(input.content).catch(() => undefined);
43
- return client.saveFact({ content: input.content, tags: input.tags, devTaskId, repo, embedding, visibility: input.visibility, source: input.source });
119
+ return withSupersedes(client.saveFact({ content: input.content, tags: input.tags, devTaskId, repo, embedding, visibility: input.visibility, source: input.source }), client, 'Fact', supersedes);
44
120
  }
45
121
  case 'Skill': {
46
122
  if (!input.title || !input.content) {
47
123
  throw new Error("title and content are required when type is 'Skill'");
48
124
  }
49
- const repo = (await explicitRepo()) ?? (await currentRepoUid());
125
+ const repo = await resolveRepo();
50
126
  const embedding = await embed(`${input.title}\n\n${input.content}`).catch(() => undefined);
51
- return client.saveSkill({ title: input.title, content: input.content, tags: input.tags, repo, embedding, visibility: input.visibility, source: input.source });
127
+ return withSupersedes(client.saveSkill({ title: input.title, content: input.content, tags: input.tags, repo, embedding, visibility: input.visibility, source: input.source }), client, 'Skill', supersedes);
52
128
  }
53
129
  case 'Scenario': {
54
130
  if (!input.summary) {
55
131
  throw new Error("summary is required when type is 'Scenario'");
56
132
  }
57
- const repo = (await explicitRepo()) ?? (await currentRepoUid());
133
+ const repo = await resolveRepo();
58
134
  const devTaskId = input.externalRef ? await resolveTaskUid(input.externalRef, repo ?? null) : undefined;
59
135
  const embedding = await embed(input.summary).catch(() => undefined);
60
136
  return client.saveScenario({ summary: input.summary, factIds: input.factIds, devTaskId, repo, embedding, visibility: input.visibility, source: input.source });
@@ -63,10 +139,10 @@ async function performSave(deps, input) {
63
139
  if (!input.title || !input.content) {
64
140
  throw new Error("title and content are required when type is 'Wiki'");
65
141
  }
66
- const repo = (await explicitRepo()) ?? (await currentRepoUid());
142
+ const repo = await resolveRepo();
67
143
  const devTaskId = input.externalRef ? await resolveTaskUid(input.externalRef, repo ?? null) : undefined;
68
144
  const embedding = await embed(`${input.title}\n\n${input.content}`).catch(() => undefined);
69
- return client.saveWikiPage({
145
+ const saved = client.saveWikiPage({
70
146
  title: input.title,
71
147
  content: input.content,
72
148
  tags: input.tags,
@@ -77,6 +153,7 @@ async function performSave(deps, input) {
77
153
  visibility: input.visibility,
78
154
  source: input.source,
79
155
  });
156
+ return withSupersedes(saved, client, 'Wiki', supersedes);
80
157
  }
81
158
  }
82
159
  }
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.buildSessionContext = void 0;
4
+ const annotate_1 = require("./annotate");
5
+ const soft_1 = require("./soft");
4
6
  // Matches session-start.sh's --max-time 5 per call. Promise.race does not cancel the
5
7
  // losing fetch, so a hung backend still holds its socket — but the tool answers instead
6
8
  // of hanging the conversation, which is the property that matters here.
@@ -8,18 +10,11 @@ const CALL_TIMEOUT_MS = 5000;
8
10
  // Every leg degrades to empty rather than rejecting: this is startup context, and a
9
11
  // half-populated recall is worth more to the model than a failed tool call. Mirrors
10
12
  // session-start.sh, which tolerates any individual endpoint failing behind its cap.
11
- function soft(p, fallback) {
12
- // Attached before the race, not after: a rejection arriving once the timeout has
13
- // already won would otherwise surface as an unhandled rejection and kill the process.
14
- const handled = p.catch(() => fallback);
15
- let timer;
16
- const capped = new Promise((resolve) => {
17
- timer = setTimeout(() => resolve(fallback), CALL_TIMEOUT_MS);
18
- });
19
- return Promise.race([handled, capped]).finally(() => clearTimeout(timer));
13
+ function soft(p, fallback, ms = CALL_TIMEOUT_MS) {
14
+ return (0, soft_1.soft)(p, fallback, ms);
20
15
  }
21
16
  async function buildSessionContext(deps) {
22
- const { client, currentRepoUid } = deps;
17
+ const { client, currentRepoUid, staleness } = deps;
23
18
  const [persona, factsSelf, factsTeam, skillsSelf, skillsTeam, repoUid] = await Promise.all([
24
19
  // The one piece of context that does not depend on a repo, which makes it the most
25
20
  // valuable leg for a host with no project directory. `configured: false` is the cue
@@ -57,11 +52,17 @@ async function buildSessionContext(deps) {
57
52
  repoSkills = without(s.skills, selfSkills, teamSkills);
58
53
  wiki = w.pages;
59
54
  }
55
+ const toItems = (raws, check) => Promise.all(raws.map((raw) => item(raw, check)));
56
+ const groups = [selfFacts, teamFacts, repoFacts, selfSkills, teamSkills, repoSkills, wiki];
57
+ const plain = await Promise.all(groups.map((raws) => toItems(raws, undefined)));
58
+ const [factsS, factsT, factsR, skillsS, skillsT, skillsR, wikiItems] = staleness
59
+ ? await soft(Promise.all(groups.map((raws) => toItems(raws, staleness))), plain, soft_1.STALENESS_TIMEOUT_MS)
60
+ : plain;
60
61
  return {
61
62
  persona,
62
- facts: { self: selfFacts.map(item), team: teamFacts.map(item), repo: repoFacts.map(item) },
63
- skills: { self: selfSkills.map(item), team: teamSkills.map(item), repo: repoSkills.map(item) },
64
- wiki: wiki.map(item),
63
+ facts: { self: factsS, team: factsT, repo: factsR },
64
+ skills: { self: skillsS, team: skillsT, repo: skillsR },
65
+ wiki: wikiItems,
65
66
  repoScoped: Boolean(repoUid),
66
67
  };
67
68
  }
@@ -70,8 +71,10 @@ function without(items, ...seen) {
70
71
  const taken = new Set(seen.flat().map((x) => x.uid));
71
72
  return items.filter((x) => !taken.has(x.uid));
72
73
  }
73
- function item(x) {
74
+ async function item(x, staleness) {
74
75
  const content = x.title ? `${x.title}: ${x.content}` : x.content;
75
76
  // Date only, no time: the model needs "is this stale", not an ordering key.
76
- return x.lastModifiedDate ? { content, updated: x.lastModifiedDate.slice(0, 10) } : { content };
77
+ const base = x.lastModifiedDate ? { content, updated: x.lastModifiedDate.slice(0, 10) } : { content };
78
+ const { superseded, staleness: changed } = await (0, annotate_1.annotateItem)({ content: x.content, tags: x.tags, source: x.source }, staleness);
79
+ return { ...base, ...(superseded ? { superseded } : {}), ...(changed ? { staleness: changed } : {}) };
77
80
  }